OpenCV 2 质心
我试图找到轮廓的质心,但在 C++ (OpenCV 2.3.1) 中实现示例代码时遇到问题。有人可以帮我吗?
I am trying to find the centroid of a contour but am having trouble implementing the example code in C++ (OpenCV 2.3.1). Can anyone help me out?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要找到轮廓的质心,可以使用矩量法。并且功能都是OpenCV实现的。
查看这些矩函数(中心矩和空间矩)。
下面的代码取自 OpenCV 2.3 文档教程。 此处有完整代码
另外看看这个SOF,虽然是Python的,但是还是很有用的。它找到轮廓的所有参数。
To find the centroid of a contour, you can use the method of moments. And functions are implemented OpenCV.
Check out these moments function (central and spatial moments).
Below code is taken from OpenCV 2.3 docs tutorial. Full code here.
Also check out this SOF, although it is in Python, it would be useful. It finds all parameters of a contour.
如果您有轮廓区域的掩模,则可以按如下方式找到质心位置:
当有掩模但没有轮廓时,此方法很有用。在这种情况下,与使用 cv::findContours(...) 然后查找质心相比,上述方法在计算上更加高效。
这是来源
If you have the mask of the contour area, you can find the centroid location as follows:
This approach is useful when one has the mask but not the contour. In that case the above method is computationally more efficient vs. using
cv::findContours(...)
and then finding mass center.Here's the source
给定轮廓点和 Wikipedia 中的公式,可以像这样有效地计算质心:
注意:
逆时针顺序。
将
p
的类型和返回值的类型调整为Point2f
或Point2d
可能会很方便,并在 return 语句中将分母添加为
float
或double
。Given the contour points, and the formula from Wikipedia, the centroid can be efficiently computed like this:
Note:
counterclockwise order.
might be convenient to adapt the type of
p
and of the return value toPoint2f
orPoint2d
,and to add a cast to
float
ordouble
to the denominator in the return statement.如果您需要的只是质心的近似值,这里有一些简单的方法可以实现:
或者借助 Opencv 的boundingRect:
If all you need is an approximation of the centroid here are a couple of simple ways to do it:
Or with the help of Opencv's boundingRect: