python - 无法使用openCV获取对象的中心
问题描述
我无法使用 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
解决方案
您可能会找到多个轮廓,并且您想要面积最大的轮廓。
# 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)
推荐阅读
- android - 将 x509 证书解析为 android 时出现 keyfactory 错误
- java - java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:69
- sql-server - 对一个列值应用 concat 函数以从另一个表中获取数据
- html-email - 如何修复适用于所有人且正确的电子邮件模板背景
- arrays - 将字典数组转换为字典
- android - 如何加密和解密 pt 视频播放任何视频播放器?
- apache-kafka - kafka 控制台消费者没有收到来自控制台生产者的消息
- c# - 如何将类数据重定向到 xaml 页面?
- c# - 如何使用 rest api 获取交换日历数据?
- python - 多处理池不改变处理速度?