在 OpenCV 中绘制最大面积轮廓的质心 python

Drawing the centroid for the contour of maximum area in OpenCV python

我想沿着轮廓质心的边绘制最大面积的轮廓。为此,我将轮廓的面积值存储到一个列表中,并选择了最大的区域及其在列表中的位置。

for i in range(len(contours)):
    area = cv2.contourArea(contours[i])
    area_vals.append(area)
        
maxarea = max(area_vals)         #maximum value from the list of contour areas stored 
pos = area_vals.index(maxarea)  #index position of largest contour in list 

然后我用这些找到了具有最大面积及其力矩的轮廓。

maincontour = contours[pos]            #contour that gave the largest contour area 
M = cv2.moments(maincontour)      #moments of that contour

cv2.circle(img, (cX, cY), 6, (0, 0, 255), -2)   #drawing the centroid circle on the image
image = cv2.drawContours(img, maincontour, -1, (0, 255, 0), 5) #drawing main contour on the image 

我用这个方法对吗?这会产生预期的结果吗?从我的结果来看它看起来是正确的,但我想仔细检查该方法背后的方法和逻辑。

我没看到你在哪里使用力矩来获得质心。请始终展示一组可重现的代码。

在Python/OpenCV中,为了得到最大的轮廓,一个高效的方法是:

# get largest contour
contours = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)

获取质心,

M = cv2.moments(big_contour)
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])