python opencv 连通域_OpenCV 快速连通区域分析

(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 }

    

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值