轮廓中心质点 (Python, OpenCV)

4

我有这张图片:

src

我想要做的是在它内部检测内轮廓(数字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)

以下是错误的结果:

result

为什么质心被绘制在图像的左侧而不是(更或多或少)中心位置?

有没有解决办法?


注:本文中的HTML标签已保留。
1个回答

5
你可以尝试通过对轮廓点的平均值进行计算,这里提到了质心
  imgray = cv2.cvtColor(image, 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_LIST, cv2.CHAIN_APPROX_NONE)

  cnts = cv2.drawContours(image, contours[0], -1, (0, 255, 0), 1)

  kpCnt = len(contours[0])

  x = 0
  y = 0

  for kp in contours[0]:
    x = x+kp[0][0]
    y = y+kp[0][1]

  cv2.circle(image, (np.uint8(np.ceil(x/kpCnt)), np.uint8(np.ceil(y/kpCnt))), 1, (0, 0, 255), 3)


  cv2.namedWindow("Result", cv2.WINDOW_NORMAL)
  cv2.imshow("Result", cnts)
  cv2.waitKey(0)
  cv2.destroyAllWindows()

result


这种方法适用于这种情况,因为您的形状相当圆润,所以轮廓点分布得非常好。例如,如果您有一个“D”,则在“D”的左线上没有轮廓点,因此重心会受到极大的偏差。 - Denis
获取COM的更简单的方法是使用numpy的mean函数:x,y = contour.mean(axis=0)[0] - Griffin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接