opencv 连通域操作示例代码记录connectedComponentsWithStats()函数示例

opencv 连通域操作示例代码记录connectedComponentsWithStats()函数示例_第1张图片

void CrelaxMyFriendDlg::OnBnClickedOk()
{
	hdc = this->GetDC()->GetSafeHdc();
	// TODO: 在此添加控件通知处理程序代码
	string imAddr = "c:/Users/actorsun/Pictures/";
	string imAddr1 = imAddr+"rice.png";
	Mat relax1, positive;
	relax1 = imread(imAddr1);
	Mat relax;
	cvtColor(relax1, relax, COLOR_BGR2GRAY);
	threshold(relax, positive, 50, 255, THRESH_BINARY);
	imshow(positive);
	RNG rng(101);
	Mat a, b;
	int cout = connectedComponentsWithStats(positive, positive,a,b,8,CV_16U);
	imshow("1", positive);
	waitKey();
	vector colors;
	for (int i = 0; i < cout; i++)
	{
		Vec3b vec(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
		colors.push_back(vec);
	}
	Mat result(positive.rows,positive.cols,relax1.type());
	for (int row = 0; row < relax1.rows; row++)
	{
		for (int col = 0; col < relax1.cols; col++)
		{
			int temp = positive.at(row,col);
			if (temp == 0)
				continue;
			result.at(row, col) = colors[temp];
		}
	}
	imshow("标记后的图", result);
	waitKey();
	return;
}

上面这个代码是MFC程序里面的一个函数,不能够直接运行,但是如果学过MFC相信没有问题完全能够看得懂。

opencv 连通域操作示例代码记录connectedComponentsWithStats()函数示例_第2张图片opencv 连通域操作示例代码记录connectedComponentsWithStats()函数示例_第3张图片

上例当中,count=7.说明检测到7个连通域。

opencv 连通域操作示例代码记录connectedComponentsWithStats()函数示例_第4张图片

你可能感兴趣的:(opencv,机器人,c++,计算机视觉,单片机)