首页 > 解决方案 > 无法使用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

原图: 在此处输入图像描述

处理后的图像: 在此处输入图像描述

标签: pythonopencv

解决方案


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

# 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)

在此处输入图像描述


推荐阅读