OpenCV_连通区域分析----Two-Pass法

 

#define MAXLABEL 500
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
uchar parent[MAXLABEL] = { 0 };

//通过while循环查找根节点,因为标签为根节点时parent存放的值是0
int Find(uchar x, uchar parent[])
{
	int i = x;
	while (0 != parent[i])
		i = parent[i];
	return i;
}

//通过while循环找到i,j的根节点,在判断根节点是否一致,不一致,将值小的作为父节点,将关系存储到parent数组里面
void Union(uchar big, uchar small, uchar parent[])
{
	uchar i = big;
	uchar j = small;
	while (0 != parent[i])
		i = parent[i];
	while (0 != parent[j])
		j = parent[j];
	if (i != j)
		parent[i] = j;
}

Mat Label(Mat &I)
{
	/// first pass
	int label = 0;

	Mat dst = Mat::zeros(I.size(), I.type());
	for (int nY = 0; nY < I.rows; nY++)
	{
		for (int nX = 0; nX < I.cols;nX++)
		{
			if (I.at<uchar>(nY, nX) != 0)
			{
				uchar left = nX - 1<0 ? 0 : dst.at<uchar>(nY, nX - 1);//边界点注意
				uchar up = nY - 1<0 ? 0 : dst.at<uchar>(nY - 1, nX);

				if (left != 0 || up != 0)
				{
					if (left != 0 && up != 0)
					{
						dst.at<uchar>(nY, nX) = min(left, up);
						if (left < up)
							Union(up, left, parent);
						else if (up<left)
							Union(left, up, parent);
					}
					else
						dst.at<uchar>(nY, nX) = max(left, up);
				}
				else
				{
					dst.at<uchar>(nY, nX) = ++label;

				}
			}
		}
	}

	/// second pass 
	for (int nY = 0; nY < I.rows; nY++)
	{
		for (int nX = 0; nX < I.cols; nX++)
		{
			if (I.at<uchar>(nY, nX) == 1)
				dst.at<uchar>(nY, nX) = Find(dst.at<uchar>(nY, nX), parent);
		}
	}
	return dst;
}
int main()
{
	Mat image = imread("d:/zimu.png",1);
	Mat gray,thresh;
	cvtColor(image,gray,CV_RGB2GRAY);
	threshold(gray,thresh,40,1,THRESH_BINARY_INV);
	imshow("erzhi", thresh);
	Mat result = Label(thresh);
	namedWindow("结果",0);
	imshow("结果",result);
	
	waitKey();
	return 0;
}

 

参考:https://blog.csdn.net/icvpr/article/details/10259577

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值