OpenCV 快速连通区域分析


 

(1)cv::connectedComponents()

1 int nccomps=connectedComponents ( 2  cv::InputArrayn image, 3  cv::OutputArray labels, 4         int connectivity = 8, 5        int ltype = CV_32S );

函数返回值nccomps为int型,表示连通域个数;

image: 输入图像(8-bit,单通道图像)

lables:  生成的标记图,部分截图如下图所示,labelsde 尺寸和输入图像大小相等

connetivity: 表示4或8邻域连接(int型)

ltype:  表示输出标记图的类型(CV_32S,CV_16U)

 (2)cv::connectedComponentsWithStats()函数(2)增加了一下重要信息,包围框(bounding box)、面积和质心等。

1 int  nccomps=connectedComponentsWithStats ( 2  cv::InputArrayn image, 3  cv::OutputArray labels, 4  cv::OutputArray stats, 5  cv::OutputArray centroids, 6     int  connectivity = 8, 7     int   ltype= CV_32S 8     );

image: 输入图像(8-bit,单通道图像)

lables:  生成的标记图,部分截图如下图所示,labelsde 尺寸和输入图像大小相等

star:一个5*nccomps的矩阵,分别对应各个轮廓的x,y,width,height和面积

centroids:一个2*nccomps的居住,表示每个连通域的质心

connetivity: 表示4或8邻域连接(int型)

ltype:  表示输出标记图的类型(CV_32S,CV_16U)

star输出图:

话不多说上源码:(面积小于3000的置零)

 1 #include <algorithm>
 2 #include <iostream>
 3 #include<opencv2/opencv.hpp>
 4 using namespace cv;  5 using namespace std;  6 
 7 int main()  8 {  9 
10  Mat img, img_edge, labels, centroids, img_color, stats; 11     img = imread("C:\\Users\\hsy\\Desktop\\3.jpg", 0); 12     threshold(img, img_edge, 0, 255, THRESH_OTSU); 13     int nccomps = connectedComponentsWithStats(img_edge, labels, stats, centroids); 14     cout << "连通域个数: " << nccomps << endl; 15     vector<Vec3b>colors(nccomps + 1);; 16     colors[0] = Vec3b(0, 0, 0); 17     for (int i = 1; i <= nccomps; i++) 18  { 19         colors[i] = Vec3b(rand() % 256, rand() % 256, rand() % 256); 20         if (stats.at<int>(i, CC_STAT_AREA) < 2500) 21             colors[i] = Vec3b(0, 0, 0); 22 
23         cout << stats.at<int>(i - 1, CC_STAT_AREA) << endl;//连通域的面积
24         
25  } 26     img_color = Mat::zeros(img.size(), CV_8UC3); 27     for (int y = 0; y < img_color.rows; y++) 28         for (int x = 0; x < img_color.cols; x++) 29  { 30             int label = labels.at<int>(y, x); 31             CV_Assert(0 <= label && label <= nccomps); 32             img_color.at<Vec3b>(y, x) = colors[label]; 33  } 34 
35     imshow("Labeled map", img_color); 36     imshow("img", img); 37  waitKey(); 38     return 0; 39 }

    

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM