使用OpenCV查找二值圖中最大連通區域


http://blog.csdn.net/shaoxiaohu1/article/details/40272875

 

使用OpenCV查找二值圖中最大連通區域

標簽: OpenCVfindCoutours
 分類:
 

上一篇博文中介紹了matlab查找最大連通區域的方法,OpenCV函數中也有類似的函數與之對應,findCoutours。下面代碼為使用示例:

 

[cpp]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. cv::Mat bwImg;  
  2. vector<vector<cv::Point>> contours ;    
  3.   
  4. // 二值化圖像  
  5. cv::threshold(srcImg, bwImg, 0.0, 255.0, CV_THRESH_BINARY | CV_THRESH_OTSU);  
  6.   
  7. cv::imshow("binary image", bwImg);  
  8. cv::waitKey();  
  9.   
  10. // 查找輪廓,對應連通域  
  11. cv::findContours(bwImg,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);  
  12.   
  13. // 尋找最大連通域  
  14. double maxArea = 0;  
  15. vector<cv::Point> maxContour;  
  16. for(size_t i = 0; i < contours.size(); i++)  
  17. {  
  18.     double area = cv::contourArea(contours[i]);  
  19.     if (area > maxArea)  
  20.     {  
  21.         maxArea = area;  
  22.         maxContour = contours[i];  
  23.     }  
  24. }  
  25.   
  26. // 將輪廓轉為矩形框  
  27. cv::Rect maxRect = cv::boundingRect(maxContour);  
  28.   
  29. // 顯示連通域  
  30. cv::Mat result1, result2;  
  31.   
  32. bwImg.copyTo(result1);  
  33. bwImg.copyTo(result2);  
  34.   
  35. for (size_t i = 0; i < contours.size(); i++)  
  36. {  
  37.     cv::Rect r = cv::boundingRect(contours[i]);  
  38.     cv::rectangle(result1, r, cv::Scalar(255));  
  39. }  
  40. cv::imshow("all regions", result1) ;  
  41. cv::waitKey();  
  42.   
  43. cv::rectangle(result2, maxRect, cv::Scalar(255));  
  44. cv::imshow("largest region", result2) ;  
  45. cv::waitKey();  
 
         

 

 

[cpp]  view plain  copy


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM