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

标签 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: 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)

关于python - 如何使用 opencv 和 Python 获取轮廓数组的索引以选择 N 个最大的轮廓?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49640744/

相关文章:

c++ - opencv 二进制数据 jpg 图像到 cv::Mat

python - 使用 Powershell 安装最新版本的 Python 的首选方式是什么?打包的二进制文件还是在线安装?

python - 关于在 Python 中关闭文件

python - 无需绘图即可检测轮廓相交

python - 具有灰色世界假设的自动白平衡

c++ - OpenCV 中的叠加图像

python - 在 Pandas 中使用 read_csv 时使用 skiplines 时出错

c# - BeautifulSoup 类似于 C#

c++ - 具有循环色调范围的 HSV 中的高效 InRange

c++ - Qt + OpenCV灰度错误