下面的代码根据轮廓的最大面积查找轮廓,但当找不到轮廓时,我想将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开始(可能更早),您可以编写
其中
default
表示当列表为空时返回的内容相关问题 更多 >
编程相关推荐