如何使用opencv和Python获取轮廓数组的索引以选择N个最大的轮廓?

How to get the indexes of contours' array to choose the N largest contours using opencv and Python?

我正在尝试使用 python 和 opencv 找到 2 个最大的轮廓。

我尝试获取索引然后调用 drawContour 函数,但出现问题。

这是我的代码

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)

这是错误:

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

第二个问题,如果我能画,我不会画这两个,我怎么画?

第一个回答。

您使用 drawContours 函数的方式有误。
drawContours 的第二个参数是 contour 的列表(= Point 的列表),第三个参数是要绘制的 contour 的索引。
所以你的代码应该是:

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


第二个回答。

如果要绘制两个轮廓,只需调用drawContours两次即可。

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