ZeroDivisionError(Python)

ZeroDivisionError(Python),python,opencv,scikit-image,Python,Opencv,Scikit Image,我得到了一些图像的零除法错误(尽管它们中的很多都工作得很好): 代码如下: 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 > t

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

代码如下:

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()

回溯(最近一次呼叫最后一次):
文件“Center.py”,第26行,在
cX=int(M[“m10”]/M[“m00”])
ZeroDivisionError:浮点除以零

提前谢谢

错误是不言而喻的。你不能把一个数字除以零。如果
M[“m00”]
为零,则需要对其进行适当处理。检查
M[“m00”]
中的
0


也许你的轮廓不好

注意,由于轮廓力矩是使用格林公式计算的,因此 对于具有自相交的轮廓,可能会得到看似奇怪的结果, e、 g.蝴蝶形轮廓的零区域(m00)


计算质心的重量,例如:

cx = 0
cy = 0
for p in contour:
    cx += p[0][0]
    cy += p[0][1]
cx = int(cx/len(contour))
cy = int(cy/len(contour))
或研究(3.4.3)


相关:

我认为这并不严格。如果M00为零,则形状的面积为零,并且您应该决定将形状视为无效(即跳过),或者以另一种方式测量中心,但不返回(0, 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
cx = 0
cy = 0
for p in contour:
    cx += p[0][0]
    cy += p[0][1]
cx = int(cx/len(contour))
cy = int(cy/len(contour))