http://blog.csdn.net/shaoxiaohu1/article/details/40272875
use OpenCV to find the largest connected region in a binary graphTags: opencvfindcoutours2014-10-19 22:31 2802 People read comments (0) favorite reports Classification:images and OpenCV (a)
Copyright NOTICE: This article is Shaoxiaohu original article, welcome reprint, please indicate the source, thank you.
The previous blog post introduced Matlab to find the maximum connected area of the method, OpenCV function also has a similar function with the corresponding, findcoutours. The following code is used for example:
[CPP]View PlainCopy
- Cv::mat bwimg;
- VECTOR<VECTOR<CV::P oint>> contours;
- Two-valued image
- Cv::threshold (srcimg, bwimg, 0.0, 255.0, Cv_thresh_binary | Cv_thresh_otsu);
- Cv::imshow ("binary image", bwimg);
- Cv::waitkey ();
- Find outlines, corresponding connected domains
- Cv::findcontours (Bwimg,contours,cv_retr_external,cv_chain_approx_none);
- Finding the largest connected domain
- Double Maxarea = 0;
- VECTOR<CV::P oint> maxcontour;
- For (size_t i = 0; i < contours.size (); i++)
- {
- Double area = Cv::contourarea (Contours[i]);
- if (Area > Maxarea)
- {
- Maxarea = area;
- Maxcontour = Contours[i];
- }
- }
- Convert Outline to Rectangular box
- Cv::rect maxrect = Cv::boundingrect (Maxcontour);
- Show connected Domains
- Cv::mat Result1, RESULT2;
- Bwimg.copyto (RESULT1);
- Bwimg.copyto (RESULT2);
- For (size_t i = 0; i < contours.size (); i++)
- {
- Cv::rect r = Cv::boundingrect (Contours[i]);
- Cv::rectangle (RESULT1, R, Cv::scalar (255));
- }
- Cv::imshow ("All Regions", RESULT1);
- Cv::waitkey ();
- Cv::rectangle (RESULT2, Maxrect, Cv::scalar (255));
- Cv::imshow ("Largest region", RESULT2);
- Cv::waitkey ();
[CPP]View PlainCopy
Use OpenCV to find the largest connected region in a binary graph