从轮廓列表中删除OpenCV轮廓 [英] Remove an opencv contour from a list of contours

查看:719
本文介绍了从轮廓列表中删除OpenCV轮廓的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用opencv,我正在检测轮廓并选择其中一些:

With opencv, I'm detecting contours and selecting some of them:

CNTS = []
_, contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    if some_condition(c):
        CNTS.append(c)

然后,我遍历轮廓列表的2个子集{c1,c2},并删除其中的一些:

Then I'm looping over 2-subsets {c1, c2} of the list of contours, and removing some of them:

TMP = CNTS[:]  # copy it, to avoid deleting element from a list while looping on it!
for c1, c2 in itertools.combinations(TMP, 2):
    if dist(c1, c2) < 100  # custom function to evaluate distance between 2 contours
        if c1 in CNTS:  # it might have been already removed
            CNTS.remove(c1)

这是CNTS.remove(c1)行中的问题:

ValueError:具有多个元素的数组的真值不明确.使用a.any()或a.all()

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

如何从opencv轮廓列表中正确删除轮廓?

How to correctly remove a contour from a list of opencv contours?

注意:实际上,它在大多数情况下都有效,但是有时经过几次迭代后,我会遇到此错误.也许是因为轮廓是点的列表,然后测试点列表"是否为另一个列表的成员是模棱两可的?

Note: in fact, it works most of the time, but sometimes, after a few iterations, I have this bug. Maybe because a contour is a list of points, and then testing if a "list of points" is member of another list is ambiguous?

更一般地说,在Python中,当测试点列表(= 2个元素的列表!)本身是否是另一个列表的成员时,是否存在一些模棱两可的情况?

More generally, in Python, are there some ambiguous cases when testing if a list of points (=list of lists of 2 elements!) is itself a member of another list?

推荐答案

您已经删除了它.出现此错误是因为您尝试两次将其删除.

You already removed it. The error raised because you try to remove it TWICE.

尝试一下:

popup = []
for i in range(len(CNTS)):
    for j in range(i+1, len(CNTS)):
        if dist(CNTS[i], CNTS[j]) < 100:
            popup.append(i)
            break
for i in popup[::-1]:
    CNTS.pop(i)

这篇关于从轮廓列表中删除OpenCV轮廓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆