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

时间:2018-04-04 00:00:11

标签: python opencv image-processing video-processing opencv3.0

我正在尝试使用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:列表索引超出范围

第二个问题,如果我能做到,我不知道如何画两个,我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

第一个答案。

您以错误的方式使用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)