image = cv::Mat(pSrcImage,true); cv::imwrite("binary.jpg",image); // Get the contours of the connected components std::vector<std::vector<cv::Point>> contours; cv::findContours(image, contours, // a vector of contours CV_RETR_EXTERNAL, // retrieve the external contours CV_CHAIN_APPROX_NONE); // retrieve all pixels of each contours // Print contours" length std::cout << "Contours: " << contours.size() << std::endl; std::vector<std::vector<cv::Point>>::const_iterator itContours= contours.begin(); for ( ; itContours!=contours.end(); ++itContours) { std::cout << "Size: " << itContours->size() << std::endl; } // draw black contours on white image cv::Mat result(image.size(),CV_8U,cv::Scalar(255)); cv::drawContours(result,contours, -1, // draw all contours cv::Scalar(0), // in black 2); // with a thickness of 2 cv::namedWindow("Contours"); cv::imshow("Contours",result); // Eliminate too short or too long contours int cmin= 100; // minimum contour length int cmax= 1000; // maximum contour length std::vector<std::vector<cv::Point>>::const_iterator itc= contours.begin(); while (itc!=contours.end()) { if (itc->size() < cmin || itc->size() > cmax) itc= contours.erase(itc); else ++itc; } // draw contours on the original image cv::Mat original= cv::imread(image_name); cv::drawContours(original,contours, -1, // draw all contours cv::Scalar(255,255,0), // in white 2); // with a thickness of 2 cv::namedWindow("Contours on original"); cv::imshow("Contours on original",original); // Let"s now draw black contours on white image result.setTo(cv::Scalar(255)); cv::drawContours(result,contours, -1, // draw all contours cv::Scalar(0), // in black 1); // with a thickness of 1 image= cv::imread("binary.jpg",0); // testing the bounding box