【OpenCV】求图像中几何形状的质心Centroid

1. 找几何形状的轮廓。

2. 求轮廓的矩。

3. 求质心。

img = cv2.imread("test.jpg")
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY_INV)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 255), thickness=1)
cv2.imshow("Image", img)
cv2.waitKey(0)
for c in contours:
    M = cv2.moments(c)
    if M["m00"] != 0:
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
    else:
        cX, cY = 0, 0

    cv2.circle(img, (cX, cY), 5, (0, 0, 255), -1)
    cv2.imshow("Image", img)
    cv2.waitKey(0)

 

发布了437 篇原创文章 · 获赞 590 · 访问量 61万+

猜你喜欢

转载自blog.csdn.net/heiheiya/article/details/103181007