Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
轮廓中的质心(Python、OpenCV)_Python_Opencv_Opencv Contour - Fatal编程技术网

轮廓中的质心(Python、OpenCV)

轮廓中的质心(Python、OpenCV),python,opencv,opencv-contour,Python,Opencv,Opencv Contour,我有这样的图像: 我想做的是检测内部轮廓(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,

我有这样的图像:

我想做的是检测内部轮廓(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)
这是(错误的…)结果:

为什么重心被画在图像的左侧而不是(或多或少)中心


对此有什么解决办法吗?

您可以尝试取上面提到的等高线点的平均值


这适用于这种情况,因为您的形状相当圆,因此轮廓点分布非常均匀。例如,如果你有一个“D”,在“D”的左边没有轮廓点,所以重心会有很大的偏差。
  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()