Python – How to get the index of an array of contours using opencv and Python to select the N largest contours?

How to get the index of an array of contours using opencv and Python to select the N largest contours?… here is a solution to the problem.

How to get the index of an array of contours using opencv and Python to select the N largest contours?

I’m trying to find the 2 biggest outlines using python and opencv.

I tried to get the index and then called the drawContour function, but something went wrong.

Here is my code

im2, contours, hierarchy = cv.findContours(roi, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)

largest_area = 0
second_area = 0
l_index = 0
s_index = 0
for i, c in enumerate(contours):
    area = cv.contourArea(c)
    if (area > largest_area):
        if (area > second_area):
            second_area = largest_area
            largest_area = area
            l_index = i
    elif (area > second_area):
        second_area = area
        s_index = i

cv.drawContours(frame, contours[l_index], -1, (0, 255, 0), 2)
cv.imshow('frame',frame)

Here is the error:

cv.drawContours(frame, contours[l_index], -1, (0, 255, 0), 2)
IndexError: list index out of range

The second question, if I can draw, I don’t know how to draw these two, how do I draw?

Solution

The first answer.

You are using the drawContours function in the wrong way.
The second argument of drawContours is the list of contours (=Point list), and the third argument is the index of contour you want to draw.
So your code should be:

cv.drawContours(frame, contours, l_index, (0, 255, 0), 2)

Second answer.

If you want to draw two contours, just call drawContours twice.

cv.drawContours(frame, contours, l_index, (0, 255, 0), 2)
cv.drawContours(frame, contours, s_index, (0, 0, 255), 2)

Related Problems and Solutions