zoukankan      html  css  js  c++  java
  • 使用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();  
    
    
    
    
  • 相关阅读:
    Android中的5种数据存储方式
    Android Service
    Android BroadcastReceiver
    Android Intent
    Android Fragment
    Android 教学实验计划1
    【Android教学用例程序】计算器
    Android UI 基础知识
    Android 控件
    Android 计算器布局测试2
  • 原文地址:https://www.cnblogs.com/donaldlee2008/p/5229991.html
Copyright © 2011-2022 走看看