【问题标题】:Value Error due to ambiguity for an IF statement in OpenCV-Python由于 OpenCV-Python 中 IF 语句的歧义导致的值错误
【发布时间】:2020-12-04 10:51:42
【问题描述】:

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

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)   

【问题讨论】:

  • 总是用“is None”或“is not None”来测试none,永远不要使用==来测试None。
  • @ChristophRackwitz 有帮助!谢谢。

标签: python opencv opencv-contour


【解决方案1】:

这是因为如果存在轮廓,maxcontour 是一个 NumPy 数组,如果没有轮廓,则 maxcontour 按照默认参数是None

因此,当您检查 if maxcontour == None 时,您可能正在将 NumPy 数组与 None 进行比较。

阅读此帖子了解更多信息: Comparing two NumPy arrays for equality, element-wise


一种可能的解决方案是默认使用[]

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

然后检查长度:

if len(maxcontour) == 0:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    相关资源
    最近更新 更多