Search code examples
pythonopencvcontourcentroid

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


I want to draw the contour with the maximum area along side that contours centroid. To do this I have stored the area values of the contours onto a list and selected the largest area as well as it's position in the list.

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 

I have then used these to find the contour with the maximum area and its moments.

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 

Am I right in using this method? Would this produce the desired outcome? From my results it looks correct but I wanted to double check the method and logic behind the approach.


Solution

  • I do not see where you use the moments to get the centroid. Please always show a reproducible set of code.

    In Python/OpenCV, to get the largest contour, an efficient method is:

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

    To get the centroid,

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