本文介绍了ZeroDivisionError(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某些图像上出现了零分割错误(即使很多图像都可以正常工作):

I am getting a Zero Division Error with some images (Even though a lot of them work just fine) :

这是代码:

image = skimage.io.imread('test.png', False)
image_gray = skimage.io.imread('test.png', True)
blurred = cv2.GaussianBlur(img_as_ubyte(image_gray), (5, 5), 0)
thresh = threshold_li(blurred)
binary = blurred > thresh
binary_cv2 = img_as_ubyte(binary)

# find contours in the thresholded image
cnts = cv2.findContours(binary_cv2.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]

# loop over the contours
for c in cnts:
    # compute the center of the contour
    M = cv2.moments(c)
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])

    # draw the contour and center of the shape on the image
    cv2.drawContours(img_as_ubyte(image), [c], -1, (0, 255, 0), 2)
    cv2.circle(img_as_ubyte(image), (cX, cY), 7, (255, 255, 255), -1)
    cv2.putText(img_as_ubyte(image), "center", (cX - 20, cY - 20),
    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)

viewer = ImageViewer(image)
viewer.show()


Traceback (most recent call last):
  File "Center.py", line 26, in <module>
    cX = int(M["m10"] / M["m00"])
ZeroDivisionError: float division by zero

提前谢谢!

推荐答案

错误是不言而喻的.您不能将数字除以零.如果M["m00"]为零,那么您需要适当地处理它.检查M["m00"]中的0值.

Error is self-evident. You cannot divide a number by zero. If M["m00"] is zero, then you need to handle it appropriately. Check for 0 values in M["m00"].

if M["m00"] != 0:
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])
else:
    # set values as what you need in the situation
    cX, cY = 0, 0

这篇关于ZeroDivisionError(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 00:07