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

Appending a null value when max() is empty

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

The code below finds a contour based on its maximum area but when there is no contour to be found I want to append 0 to a list in order to work around the ValueError: max() arg is an empty sequence error but it fails. Why is that?

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)

Edit: Upon addition of the default = 0 I get an error for 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

As of Python3.8 (it may be earlier), you can write

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

where default says what to return when the list is empty.