如何获取等高线的索引';使用opencv和Python选择N个最大轮廓的数组?
我正在尝试使用python和opencv查找两个最大的轮廓 我试图获取索引,然后调用drawContour函数,但出现了一些问题 这是我的密码如何获取等高线的索引';使用opencv和Python选择N个最大轮廓的数组?,python,opencv,image-processing,video-processing,opencv3.0,Python,Opencv,Image Processing,Video Processing,Opencv3.0,我正在尝试使用python和opencv查找两个最大的轮廓 我试图获取索引,然后调用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):
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)
这就是错误:
等高线图(框架,等高线[l_索引],-1,(0,255,0),2)
索引器:列表索引超出范围
第二个问题,如果我能做到的话,我不知道如何画这两个,我怎么能做到呢?第一个答案。 您以错误的方式使用了
drawContours
函数。drawContours
的第二个参数是轮廓的列表(=点的列表),第三个参数是要绘制的轮廓的索引。
因此,您的代码应该是:
cv.drawContours(frame, contours, l_index, (0, 255, 0), 2)
第二个答案。
如果要绘制两个等高线,只需调用drawcourts
两次即可
cv.drawContours(frame, contours, l_index, (0, 255, 0), 2)
cv.drawContours(frame, contours, s_index, (0, 0, 255), 2)
找到这两个最大区域的逻辑没有多大意义如果面积>最大面积
,则应第二面积=最大面积
,并更新最大面积
(当然也同步更新相应的索引)。否则,如果area>second\u area
您只需更新second\u area
(以及相应的索引)调试代码。最简单的方法就是添加一堆print
语句来显示相关变量的当前状态。你说得对!!我刚刚修好了!!谢谢谢谢即使我已经阅读了文档,我也没有注意到它应该放在第三个参数,谢谢,这两个答案都有效!