0

The code below finds a contour based on its maximum area but when there is no contour to be found I solve the ValueError by inputting default = None as shown in the code below. However, when the list is not empty (contour is present) a new ValueError arises as ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). Why is that?

contours = cv2.findContours(tframe, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) == 2:
    contours = contours[0]
else:
    contours = contours[1]

maxcontour = max(contours, key=cv2.contourArea, default= None)   #filter maximum contour based on contour area 

if maxcontour == None :
    maxarea = 0
    circularity.append(0)
    area.append(0)
    
else:
    maxarea = cv2.contourArea(maxcontour)
    perimeter = cv2.arcLength(maxcontour,True)
    M = cv2.moments(maxcontour)    #moments of that contour
    circ = circularityfunc(maxarea,perimeter)    #function that calculates circularity of contour 
    circularity.append(circ)   
Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
SyntaxError101
  • 79
  • 1
  • 2
  • 11

1 Answers1

0

It is because if contours are present, maxcontour is a NumPy array, if there are no contours, maxcontour is None as per default parameter.

So, when you check if maxcontour == None it could happen that you are comparing a NumPy array with None.

Read this thread for more info: Comparing two NumPy arrays for equality, element-wise


One possible solution is to use [] as default

maxcontour = max(contours, key=cv2.contourArea, default= [])

then check the length:

if len(maxcontour) == 0:

iGian
  • 11,023
  • 3
  • 21
  • 36