python 计算轮廓/区域的中心

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/968332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:10:48  来源:igfitidea点击:

Calculate the center of a contour/Area

pythonimage-processingopencvcontour

提问by Janusz

I'm working on a Image-processing chain that seperates a single object by color and contour and then calculates the y-position of this object.

我正在研究一个图像处理链,它按颜色和轮廓分隔单个对象,然后计算该对象的 y 位置。

How do I calculate the center of a contour or area with OpenCV?

如何使用 OpenCV 计算轮廓或区域的中心?

Opencv links:

OpenCV 链接:

回答by Kiv

You can get the center of mass in the y direction by first calculating the Moments. Then the center of mass is given by yc = M01 / M00, where M01 and M00 are fields in the structure returned by the Moments call.

您可以通过首先计算Moments来获得 y 方向的质心。然后质心由 给出yc = M01 / M00,其中 M01 和 M00 是 Moments 调用返回的结构中的字段。

If you just want the center of the bounding rectangle, that is also easy to do with BoundingRect. This returns you a CvRect and you can just take half of the height.

如果您只想要边界矩形的中心,使用BoundingRect也很容易。这将返回一个 CvRect,您可以只取高度的一半。

Let me know if this isn't precise enough, I have sample code somewhere I can dig up for you.

如果这不够精确,请告诉我,我在某处可以为您挖掘示例代码。

回答by wsd

I don't exactly know what OpenCV is, but I would suggest this:

我不完全知道 OpenCV 是什么,但我建议这样做:

The Selected cluster of pixels has a maximum width at one point - w - so lets say the area has w vertical columns of pixels. Now I would weight the columns according to how many pixels the column contains, and use these column-wights to determine the Horizontal Center Point.

Selected 像素簇在一个点上有一个最大宽度 - w - 所以假设该区域有 w 个垂直像素列。现在我将根据列包含的像素数对列进行加权,并使用这些列权重来确定水平中心点。

The Same Algorithm could also work for the X Center.

同样的算法也适用于 X 中心。