下面的代码根据其最大面积查找轮廓,但是当找不到轮廓时,我想将其附加0
到列表中以解决ValueError: max() arg is an empty sequence
错误,但是它失败了。这是为什么?
contours = cv2.findContours(binaryimage, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) == 2:
contours = contours[0]
else:
contours = contours[1]
maxcontour = max(contours, key=cv2.contourArea) #filter maximum contour based on contour area
if len(maxcontour) == 0:
areavalue.append(0)
maxarea = cv2.contourArea(maxcontour)
areavalue.append(maxarea)
编辑:添加后,default = 0
我得到一个错误maxarea
maxcontour = max(contours, key=cv2.contourArea, default = 0) #filter maximum contour based on contour area
maxarea = cv2.contourArea(maxcontour)
areavalue.append(maxarea)
从Python3.8开始(可能更早),你可以编写
max(contours, key=cv2.contourArea, default=0)
wheredefault
表示列表为空时返回的内容。
当我这样做时,似乎给了我一个错误。错误的原因来自于我
maxcontour = max(contours, key=cv2.contourArea, default =0)
用于的事实maxarea = cv2.contourArea(maxcontour)
。我已经在问题中编辑了代码以适应这一点。哦。您需要使“ default =”成为适用于这种情况的东西。您要么需要返回一些具有零面积的轮廓,要么需要
default=None
,然后None
在获取面积之前测试案例。关键是default=
摆脱max
了空情况下的错误消息。或者当然,只需在调用之前测试是否
contours
为空(if contours:
)max
。对于您的代码而言,最有意义的是什么。哦,我懂了。这很有意义。谢谢您的回答!
设置时出现
default = None
此错误ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()