Remove an opencv contour from a list of contours [duplicate]

…衆ロ難τιáo~ 提交于 2019-12-11 09:50:43

问题


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)

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)

Here comes the problem in the CNTS.remove(c1) line:

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

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?

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?


回答1:


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

Try this:

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)


来源:https://stackoverflow.com/questions/53051275/remove-an-opencv-contour-from-a-list-of-contours

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!