I am trying to find the 2 largest contours using python and opencv.
I have tried to get the indexes and then call a drawContour function, but something goes wrong.
This 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)
This is the error:
cv.drawContours(frame, contours[l_index], -1, (0, 255, 0), 2) IndexError: list index out of range
A second question, if I could make it, I don't know how to draw both of them, how could I do that?
First answer.
You're using drawContours
function in a wrong way.
2nd parameter of drawContours
is a list of contour
(=a list of Point
)s and 3rd parameter is the index of the 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 both 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.