(1)cv::connectedComponents()
1 intnccomps=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_32S8 );
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
2 #include
3 #include
4 using namespacecv;5 using namespacestd;6
7 intmain()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 <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(i, CC_STAT_AREA) < 2500)21 colors[i] = Vec3b(0, 0, 0);22
23 cout << stats.at(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(y, x);31 CV_Assert(0 <= label && label <=nccomps);32 img_color.at(y, x) =colors[label];33 }34
35 imshow("Labeled map", img_color);36 imshow("img", img);37 waitKey();38 return 0;39 }