欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Opencv中如何寻找连通域的几何中心

程序员文章站 2022-05-24 11:08:25
...

拿如下图做解释                                         //图片来自http://www.opencv.org.cn/forum.php?mod=viewthread&tid=2865714

Opencv中如何寻找连通域的几何中心

这张图里面有多个几何图形,如何得到每一个多边形的中心点。我们需要以下几个函数实现

findContours( InputOutputArray image, OutputArrayOfArrays contours,OutputArray hierarchy, int mode,  int method, Point offset=Point());
Moments moments(InputArray array, bool binaryImage=false )
void drawContours(InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar& color, int thickness=1, int lineType=8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point() )

findContours可以寻找图像中的轮廓,而知道了轮廓再去找中心其实是个数学问题。

moments计算轮廓的特征矩,有了特征矩就可以计算中心。至于其中按照什么数学思想进行运算,请参考以下博文:

https://www.cnblogs.com/mikewolf2002/p/3427564.html

drawContours可以画出找得到轮廓。因为本篇关注中线点,这个函数我只是提到,大家有兴趣可以自行查阅:

http://www.opencv.org.cn/opencvdoc/2.3.2/html/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=drawcontours#void drawContours(InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar& color, int thickness, int lineType, InputArray hierarchy, int maxLevel, Point offset)

接下来是实例代码:

int main()
{
	Mat matSrc = imread("qiqiaoban.jpg", 0);
	GaussianBlur(matSrc, matSrc, Size(5, 5), 0);
	vector<vector<Point> > contours;//contours的类型,双重的vector
	vector<Vec4i> hierarchy;//Vec4i是指每一个vector元素中有四个int型数据。
	//阈值
	threshold(matSrc, matSrc, 60, 255, THRESH_BINARY);
	//寻找轮廓,这里注意,findContours的输入参数要求是二值图像,二值图像的来源大致有两种,第一种用threshold,第二种用canny
	findContours(matSrc.clone(), contours, hierarchy,CV_RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
	/// 计算矩
	vector<Moments> mu(contours.size());
	for (int i = 0; i < contours.size(); i++)
	{
		mu[i] = moments(contours[i], false);
	}
	///  计算中心矩:
	vector<Point2f> mc(contours.size());
	for (int i = 0; i < contours.size(); i++)
	{
		mc[i] = Point2f(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00);
	}
	/// 绘制轮廓
	Mat drawing = Mat::zeros(matSrc.size(), CV_8UC1);
	for (int i = 0; i < contours.size(); i++)
	{
		Scalar color = Scalar(255);
		drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
		circle(drawing, mc[i], 4, color, -1, 8, 0);
	}
	imshow("outImage",drawing);
	waitKey();
	return 0;

}

效果如下:

Opencv中如何寻找连通域的几何中心