图像连通域的计算

OpenCV 4中connectedComponents函数对图像连通域的计算
先说一下函数的原型

int cv::connectedComponents(InputArray image,
							OutputArray labels,
							int connectivity=8,
							int ltype=CV_32S
							)

image:为输入图像,必须为单通道类型(CV_8U)
labels:标记不同连通域的输出图像,与原图像尺寸相同
connectivity:标记连通域时使用的邻域种类,4表示4邻域,8表示8邻域
ltype:输出图像的数据类型,目前支持CV_32S和CV_16U
首先把我的实验图片放上去,需要实验图片的自行下载
在这里插入图片描述
下面是使用OpenCV函数connectedComponents函数实现的图像连通域的计算

#include<opencv2/core/core.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/ximgproc.hpp>
#include<vector>
#include<time.h>

using namespace std;
using namespace cv;

void connect() {
	//读入图像
	Mat image = imread("test01.jpg");
	//判断图像是否读入成功
	if (image.empty()) {
		cout << "图片读入出错,请检查路径是否存在" << endl;
		return;
	}
	//转换为灰度图像
	Mat imageGray;
	cvtColor(image, imageGray, COLOR_BGR2GRAY);
	//得到阈值图像
	Mat imageTredh;
	threshold(imageGray,imageTredh,50,255,THRESH_BINARY);
	//使用时间种子随机生成的颜色区分不同的连通域
	RNG rng(time(NULL));
	Mat outImage;
	int count = connectedComponents(imageTredh, outImage, 8, CV_16U);
	vector<Vec3b> colors;
	for (int i = 0; i < count; i++) {
		Vec3b vec3 = Vec3b(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
		colors.push_back(vec3);
	}
	Mat dst = Mat::zeros(imageGray.size(), image.type());
	int width = dst.cols;
	int height = dst.rows;
	for (int row = 0; row < height; row++) {
		for (int col = 0; col < width; col++) {
			int label = outImage.at<uint16_t>(row, col);
			if (label == 0)continue;
			dst.at<Vec3b>(row, col) = colors[label];
		}
	}
	imshow("org", image);
	imshow("processed", dst);
	waitKey(0);
}
int main(){
connect();
}

下面再放一张实验的效果图
在这里插入图片描述
可以看到,图像中的百事贴由于跟背景的颜色很像,而且加上图像的值量较差,我选取的阈值等条件的相互作用下,在实验结果图中仅剩一个小条。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是小峰呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值