Warm tip: This article is reproduced from serverfault.com, please click

python-max()为空时附加一个空值

(python - Appending a null value when max() is empty)

发布于 2020-12-03 20:32:05

下面的代码根据其最大面积查找轮廓,但是当找不到轮廓时,我想将其附加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)
Questioner
GitGoodCodes
Viewed
0
Frank Yellin 2020-12-04 04:36:01

从Python3.8开始(可能更早),你可以编写

max(contours, key=cv2.contourArea, default=0)

wheredefault表示列表为空时返回的内容。