http://blog.csdn.net/shaoxiaohu1/article/details/40272875
分类:
图像与OpenCV(15)
版权声明:本文为shaoxiaohu原创文章,欢迎转载,请注明出处,谢谢。
上一篇博文中介绍了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();