gpt4 book ai didi

python - ZeroDivisionError (Python)

转载 作者:太空宇宙 更新时间:2023-11-03 21:15:10 26 4
gpt4 key购买 nike

我遇到了一些图像的零除法错误(尽管其中很多都工作得很好):

代码如下:

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 值。

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

关于python - ZeroDivisionError (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35247211/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com