gpt4 book ai didi

python - 无法使用 openCV 获取对象的中心

转载 作者:行者123 更新时间:2023-12-03 20:12:21 26 4
gpt4 key购买 nike

我无法使用openCV正确找到三角形的中心,中心点是在三角形的底端绘制的。谁能帮我看看代码有什么问题吗?

import cv2
import numpy as np

import stackImages as stack

img = cv2.imread('triangle.jpg',0)
NewImg = img.copy()
ret,thresh = cv2.threshold(img,127,255,0)
contours,hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]
M = cv2.moments(cnt)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])

cv2.circle(NewImg, (cx, cy), 2, (0, 0, 255), 3)

cv2.putText(NewImg, "centroid", (cx, cy),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

while (True):
#imgStack = stack.stackImages(0.8,([img, NewImg]))
cv2.imshow('Sample', NewImg)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break

原始图片: enter image description here

处理后的图像: enter image description here

最佳答案

您可能会找到多个轮廓,并且您想要面积最大的轮廓。

# Sort all contours by increasing area
contours_s = sorted(contours, key=cv2.contourArea)

# Find the second largest contour (the largest is the entire image
cnt = contours_s[-2]

copy = cv2.cvtColor(thresh, cv2.COLOR_GRAY2RGB)
cv2.drawContours(copy, [cnt], 0, (0, 0, 255))
cv2.imshow(copy)

enter image description here

关于python - 无法使用 openCV 获取对象的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62296838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com