【发布时间】: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