本文介绍了轮廓中的质心(Python,OpenCV)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这张图片:
我要做的是检测内部轮廓(数字3)的质心.
What I am trying to do is to detect the center of mass of the inner contour (number 3) inside it.
这是我现在拥有的代码:
This is the code I have right now:
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)
这是(错误..)结果:
This is the (wrong..) result:
为什么质心已绘制在图像的左侧而不是(或多或少)中心?
Why the center of mass has been draw in the left part of the image instead of in the (more or less) center ?
有什么解决办法吗?
推荐答案
您可以尝试采用轮廓点的平均值,如此处.
You can try by taking the average of contour points, mentioned here.
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()
这篇关于轮廓中的质心(Python,OpenCV)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!