代码之家  ›  专栏  ›  技术社区  ›  mmt

如何利用opencv和Python获取等高线数组的索引来选择N个最大的等高线?

  •  3
  • mmt  · 技术社区  · 7 年前

    我正在尝试使用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):
        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。绘制等高线(框架,等高线[l\U索引],-1,(0,255,0),2) 索引器错误:列表索引超出范围

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

    1 回复  |  直到 7 年前
        1
  •  3
  •   Suhyeon Lee    7 年前

    第一个答案。

    您正在使用 drawContours 以错误的方式运行。
    的第二个参数 绘制等高线 是的列表 contour (=列表 Point )s和第三个参数是 外形 你想画画。
    因此,您的代码应该是:

    cv.drawContours(frame, contours, l_index, (0, 255, 0), 2)
    


    第二个答案。

    如果你想画两条等高线,只需调用 绘制等高线 两次

    cv.drawContours(frame, contours, l_index, (0, 255, 0), 2)
    cv.drawContours(frame, contours, s_index, (0, 0, 255), 2)