【问题标题】:How to get the indexes of contours' array to choose the N largest contours using opencv and Python?如何使用opencv和Python获取轮廓数组的索引以选择N个最大的轮廓?
【发布时间】:2018-09-13 09:50:02
【问题描述】:

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

第二个问题,如果我能做到,我不知道怎么画他们两个,我该怎么做?

【问题讨论】:

  • 找到这两个最大区域的逻辑没有多大意义。 |如果area > largest_area,那么您应该second_area = largest_area 并更新largest_area(当然也要同步更新相应的索引)。否则,如果 area > second_area 您只需更新 second_area(和相应的索引)。 |调试你的代码。最简单的方法是添加一堆 print 语句来显示相关变量的当前状态。
  • 你说得对!!我刚刚修好了!!谢谢!!!

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


【解决方案1】:

第一个答案。

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

【讨论】:

  • 谢谢!!!即使我已经阅读了文档,我也没有注意到它应该放在第三个参数中,谢谢,两个答案都有效!
猜你喜欢
  • 2022-01-10
  • 2020-09-14
  • 2016-06-29
  • 2014-07-12
  • 1970-01-01
  • 2016-09-25
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多