上一篇博文中介绍了matlab查找最大连通区域的方法,OpenCV函数中也有类似的函数与之对应,findCoutours。下面代码为使用示例:
- cv::Mat bwImg;
- vector<vector<cv::Point>> contours ;
-
- cv::threshold(srcImg, bwImg, 0.0, 255.0, CV_THRESH_BINARY | CV_THRESH_OTSU);
-
- cv::imshow("binary image", bwImg);
- cv::waitKey();
-
- cv::findContours(bwImg,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);
-
- double maxArea = 0;
- vector<cv::Point> maxContour;
- for(size_t i = 0; i < contours.size(); i++)
- {
- double area = cv::contourArea(contours[i]);
- if (area > maxArea)
- {
- maxArea = area;
- maxContour = contours[i];
- }
- }
-
- cv::Rect maxRect = cv::boundingRect(maxContour);
-
- 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();