简体   繁体   English

由于 OpenCV-Python 中 IF 语句的歧义导致的值错误

[英]Value Error due to ambiguity for an IF statement in OpenCV-Python

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.下面的代码根据其最大面积找到一个轮廓,但是当没有找到轮廓时,我通过输入default = None来解决ValueError ,如下面的代码所示。 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()但是,当列表不为空(存在轮廓)时,会出现一个新的ValueError作为ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() . 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)   

It is because if contours are present, maxcontour is a NumPy array, if there are no contours, maxcontour is None as per default parameter.这是因为如果存在轮廓, maxcontour是一个 NumPy 数组,如果没有轮廓, maxcontour根据默认参数为None

So, when you check if maxcontour == None it could happen that you are comparing a NumPy array with None .因此,当您检查if maxcontour == None时,您可能会将 NumPy 数组与None进行比较。

Read this thread for more info: Comparing two NumPy arrays for equality, element-wise阅读此线程以获取更多信息: 比较两个 NumPy arrays 是否相等,元素方面


One possible solution is to use [] as default一种可能的解决方案是使用[]作为默认值

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

then check the length:然后检查长度:

if len(maxcontour) == 0:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM