Use OpenCV to find the largest connected region in a binary graph

Source: Internet
Author: User

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 
  1. Cv::mat bwimg;
  2. VECTOR<VECTOR<CV::P oint>> contours;
  3. Two-valued image
  4. Cv::threshold (srcimg, bwimg, 0.0, 255.0, Cv_thresh_binary | Cv_thresh_otsu);
  5. Cv::imshow ("binary image", bwimg);
  6. Cv::waitkey ();
  7. Find outlines, corresponding connected domains
  8. Cv::findcontours (Bwimg,contours,cv_retr_external,cv_chain_approx_none);
  9. Finding the largest connected domain
  10. Double Maxarea = 0;
  11. VECTOR<CV::P oint> maxcontour;
  12. For (size_t i = 0; i < contours.size (); i++)
  13. {
  14. Double area = Cv::contourarea (Contours[i]);
  15. if (Area > Maxarea)
  16. {
  17. Maxarea = area;
  18. Maxcontour = Contours[i];
  19. }
  20. }
  21. Convert Outline to Rectangular box
  22. Cv::rect maxrect = Cv::boundingrect (Maxcontour);
  23. Show connected Domains
  24. Cv::mat Result1, RESULT2;
  25. Bwimg.copyto (RESULT1);
  26. Bwimg.copyto (RESULT2);
  27. For (size_t i = 0; i < contours.size (); i++)
  28. {
  29. Cv::rect r = Cv::boundingrect (Contours[i]);
  30. Cv::rectangle (RESULT1, R, Cv::scalar (255));
  31. }
  32. Cv::imshow ("All Regions", RESULT1);
  33. Cv::waitkey ();
  34. Cv::rectangle (RESULT2, Maxrect, Cv::scalar (255));
  35. Cv::imshow ("Largest region", RESULT2);
  36. Cv::waitkey ();

[CPP]View PlainCopy

Use OpenCV to find the largest connected region in a binary graph

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.