我有这张图片:
我想要做的是在它内部检测内轮廓(数字3)的质心。
目前我的代码如下:
import cv2
import numpy as np
im = cv2.imread("three.png")
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnts = cv2.drawContours(im, contours[1], -1, (0, 255, 0), 1)
cv2.imshow('number_cnts', cnts)
cv2.imwrite('number_cnts.png', cnts)
m = cv2.moments(cnts[0])
cx = int(m["m10"] / m["m00"])
cy = int(m["m01"] / m["m00"])
cv2.circle(im, (cx, cy), 1, (0, 0, 255), 3)
cv2.imshow('center_of_mass', im)
cv2.waitKey(0)
cv2.imwrite('center_of_mass.png', cnts)
以下是错误的结果:
为什么质心被绘制在图像的左侧而不是(更或多或少)中心位置?
有没有解决办法?
注:本文中的HTML标签已保留。
mean
函数:x,y = contour.mean(axis=0)[0]
。 - Griffin