python中zerodivisionerror_ZeroDivisionError(Python)

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

Here's the code :

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

cX = int(M["m10"] / M["m00"])

ZeroDivisionError: float division by zero

Thanks in advance!

解决方案

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值