我正在尝试使用 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/