python-opencv标出重心位置
时间: 2023-11-15 15:02:41 浏览: 293
可以使用cv2.moments()函数来计算轮廓的重心位置。具体步骤如下:
1. 读取二值图像并找到轮廓。
2. 对每个轮廓计算其矩,即使用cv2.moments()函数。
3. 计算轮廓的重心位置,即使用矩的一阶矩和二阶矩计算得到。
4. 将重心位置标出来,即在原图上绘制一个圆或者一个十字。
下面是一个示例代码:
```
import cv2
# 读取二值图像并找到轮廓
img = cv2.imread('image.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 对每个轮廓计算其矩
moments = [cv2.moments(cnt) for cnt in contours]
# 计算轮廓的重心位置
centers = [(int(m['m10']/m['m00']), int(m['m01']/m['m00'])) for m in moments]
# 在原图上标出重心位置
for center in centers:
cv2.circle(img, center, 5, (0, 0, 255), -1)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文
相关推荐
















