pythonfeature-extraction

How to solve this problem about ZeroDivisionError: float division by zero?


compactness_list = []
circularity_list = []

for contour in contours:
    perimeter =  cv2.arcLength(contour, True)
    area = cv2.contourArea(contour)

    compactness = (perimeter ** 2) /(area)
    compactness_list.append(compactness)

    circularity = (4 * np.pi * area) / (perimeter)
    circularity_list.append(circularity)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-165-aa66a2f29568> in <cell line: 4>()
      6     area = cv2.contourArea(contour)
      7 
----> 8     compactness = (perimeter ** 2) / (area)
      9     compactness_list.append(compactness)
     10 

ZeroDivisionError: float division by zero

Solution

  • You can add a try...except block:

    for contour in contours:
        perimeter =  cv2.arcLength(contour, True)
        area = cv2.contourArea(contour)
    
        try:
            compactness = (perimeter ** 2) / area
            circularity = (4 * np.pi * area) / perimeter
        except ZeroDivisionError:
            compactness = 0  # or any other value 
            circularity = 0  # or any other value 
    
        compactness_list.append(compactness)
        circularity_list.append(circularity)
    

    Or a simple if...else:

    for contour in contours:
        perimeter =  cv2.arcLength(contour, True)
        area = cv2.contourArea(contour)
    
        if area == 0:  # check if area is zero
            compactness = 0  # or any other value
            circularity = 0  # or any other value
        else:
            compactness = (perimeter ** 2) / area
            circularity = (4 * np.pi * area) / perimeter
    
        compactness_list.append(compactness)
        circularity_list.append(circularity)