繁体   English   中英

如何使用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,outlines [l_index],-1,(0,255,0),2)IndexError:列表索引超出范围

第二个问题,如果我能做到,我不知道如何绘制它们两者,我该怎么做?

第一个答案。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM