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

Viewed 55

I have been searching on here similar questions but can't find a solution that works.

I have a list of contours, which has eg ten rows, each row has a value eg [[[241 478]]] and a size eg (11, 1, 2). From this list I find the area by generating a rectangle and multiplying the x by y.

I want to remove any contours which are too small or too large, however any approach (including list comprehensions) I take results in the ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

How can I get around this? If there is already a solution on here please point me in the direction.

Thank you

edited to add traceback:

Traceback (most recent call last):

  File "<ipython-input-73-e9296f497e02>", line 15, in <module>
    cnts_keep = [x for x in cnts_list if x not in cnts_area]

  File "<ipython-input-73-e9296f497e02>", line 15, in <listcomp>
    cnts_keep = [x for x in cnts_list if x not in cnts_area]

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

Below is the code as it currently stands, where I store in a new list contours I don't want to keep (' cnts_area '), then compare with the original list (' cnts_list ') to delete them. I've also tried using .remove() and .pop() but get the same error message.

            cnt_area = []
            cnts_area = []
            for c in cnts_list:
                (x, y, w, h) = cv2.boundingRect(c)
                cnt_area = w * h
                if cnt_area == 0:
                    cnts_area.append(c)
                elif cnt_area < min_area or cv2.contourArea(c) > max_area:
                    cnts_area.append(c)
                else:
                    pass

            cnts_keep = []
            cnts_keep = [x for x in cnts_list if x not in cnts_area]
0 Answers
Related