C++&&Opencv 简单的连通区域填充

cv::connectedComponents()

int  nccomps=connectedComponents (
        cv::InputArrayn image,            
        cv::OutputArray labels,               
        int connectivity = 8,     
       int ltype = CV_32S );

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

  • image: 输入图像(8-bit,单通道图像)
  • lables: 生成的标记图,部分截图如下图所示,labelsde 尺寸和输入图像大小相等
  • connetivity: 表示4或8邻域连接(int型)
  • ltype: 表示输出标记图的类型(CV_32S,CV_16U)

cv::connectedComponentsWithStats()函数

int  nccomps=connectedComponentsWithStats (
    cv::InputArrayn image,
    cv::OutputArray labels,
    cv::OutputArray stats,
    cv::OutputArray centroids,
    int  connectivity = 8,
    int   ltype= CV_32S
    )

相比connectedComponents()函数增加了一下重要信息,包围框(bounding box)、面积和质心。

  • image: 输入图像(8-bit,单通道图像)
  • lables: 生成的标记图,部分截图如下图所示,labelsde 尺寸和输入图像大小相等
  • star:一个5*nccomps的矩阵,分别对应各个轮廓的x,y,width,height和面积
  • centroids:一个2*nccomps的矩阵,表示每个连通域的质心
  • connetivity: 表示4或8邻域连接(int型)
  • ltype: 表示输出标记图的类型(CV_32S,CV_16U)

label示意图:
labelstate示意图:
state

功能源码:


int main()
{
    Mat img, img_edge, labels, centroids, img_color, stats;
    img = imread("图片路径", 0);
    threshold(img, img_edge, 0, 255, THRESH_OTSU); // 大津法二值化图像
    int nccomps = connectedComponentsWithStats(img_edge, labels, stats, centroids);
    cout << "连通域个数: " << nccomps << endl;
    vector<Vec3b>colors (nccomps + 1);;
    colors[0] = Vec3b(0, 0, 0);
    for (int i = 1; i <= nccomps; i++)
    {
        colors[i] = Vec3b(rand() % 256, rand() % 256, rand() % 256);
        if (stats.at<int>(i, CC_STAT_AREA) < 2500) // 连通区域面积小于2500被设为黑色(填充)
        /*
			关于CC_STAT_AREA:
			是ConnectedComponentsTypes的结构体属性,除AREA还有:
			CC_STAT_LEFT   = 0, 表示连通区域边界x坐标
		    CC_STAT_TOP    = 1, 表示连通区域边界y坐标                    
    		CC_STAT_WIDTH  = 2, 表示连通区域的宽
    		CC_STAT_HEIGHT = 3, 表示连通区域的高
    		CC_STAT_AREA   = 4, 表示连通区域的面积
    		CC_STAT_MAX    = 5
		*/
            colors[i] = Vec3b(0, 0, 0);

        cout << stats.at<int>(i - 1, CC_STAT_AREA) << endl;//连通域的面积

    }
    img_color = Mat::zeros(img.size(), CV_8UC3);
    for (int y = 0; y < img_color.rows; y++)
        for (int x = 0; x < img_color.cols; x++)
        {
            int label = labels.at<int>(y, x);
            CV_Assert(0 <= label && label <= nccomps);
            img_color.at<Vec3b>(y, x) = colors[label];
        }

    imshow("Labeled map", img_color);
    imshow("img", img);
    waitKey();
    return 0;
}

效果图

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值