Opencv2系列學習筆記10(提取連通區域輪廓) 另一個


http://blog.csdn.net/lu597203933/article/details/17362457

 

連通區域指的是二值圖像中相連像素組成的形狀。而內、外輪廓的概念及opencv1中如何提取二值圖像的輪廓見我的這篇博客:http://blog.csdn.net/lu597203933/article/details/14489225

 輪廓的簡單提取算法如下:

       系統性地掃描圖像直到遇到連通區域的一個點,以它為起始點,跟蹤它的輪廓,標記邊界上的像素。當輪廓完整閉合,掃描回到上一個位置,直到再次發現新的成分。

代碼:

 

[cpp]  view plain  copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. #include <iostream>  
  2. #include <opencv2\core\core.hpp>  
  3. #include <opencv2\highgui\highgui.hpp>  
  4. #include <opencv2\imgproc\imgproc.hpp>  
  5.   
  6. using namespace std;  
  7. using namespace cv;  
  8.   
  9. // 移除過小或過大的輪廓  
  10. void getSizeContours(vector<vector<Point>> &contours)  
  11. {  
  12.     int cmin = 100;   // 最小輪廓長度  
  13.     int cmax = 1000;   // 最大輪廓長度  
  14.     vector<vector<Point>>::const_iterator itc = contours.begin();  
  15.     while(itc != contours.end())  
  16.     {  
  17.         if((itc->size()) < cmin || (itc->size()) > cmax)  
  18.         {  
  19.             itc = contours.erase(itc);  
  20.         }  
  21.         else ++ itc;  
  22.     }  
  23. }  
  24.   
  25. // 計算連通區域的輪廓,即二值圖像中相連像素的形狀  
  26.   
  27. int main()  
  28. {  
  29.     Mat image = imread("E:\\opencv2cv\\lesson7\\Debug\\55.png",0);  
  30.     if(!image.data)  
  31.     {  
  32.         cout << "Fail to load image" << endl;  
  33.         return 0;  
  34.     }  
  35.     Mat imageShold;  
  36.     threshold(image, imageShold, 100, 255, THRESH_BINARY);   // 必須進行二值化  
  37.     vector<vector<Point>> contours;  
  38.     //CV_CHAIN_APPROX_NONE  獲取每個輪廓每個像素點  
  39.     findContours(imageShold, contours, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE, cvPoint(0,0));  
  40.     getSizeContours(contours);  
  41.     cout << contours.size() << endl;  
  42.     Mat result(image.size(), CV_8U, Scalar(255));  
  43.     drawContours(result, contours, -1, Scalar(0), 2);   // -1 表示所有輪廓  
  44.     namedWindow("result");  
  45.     imshow("result", result);  
  46.     namedWindow("image");  
  47.     imshow("image", image);  
  48.     waitKey(0);  
  49.     return 0;  
  50. }  

 

結果:

未移除過大多小的輪廓前:

移除后:

 


免責聲明!

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



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