ZeroDivisionError(Python)

时间:2016-02-06 22:22:15

标签: 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 > 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

提前致谢!

3 个答案:

答案 0 :(得分:5)

可能你的轮廓不好

  

注意由于轮廓力矩是使用绿色公式计算的,所以   对于具有自交叉的轮廓,可能会得到看似奇怪的结果,   例如蝴蝶形轮廓的零区域(m00)。

答案 1 :(得分:2)

错误是不言而喻的。您不能将数字除以零。如果for (Match match = Regex.Match(partData, @"^\s*([^=]+?)\s*=\s*(.*?)\s*$", RegexOptions.Multiline); match.Success; match = match.NextMatch()) { // this code runs for each line in your string which has the expected pattern string key = match.Groups[1].Value; string value = match.Groups[2].Value; } 为零,那么您需要适当地处理它。检查M["m00"]中的0值。

M["m00"]

答案 2 :(得分: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))

或查看boundingRect()(3.4.3)。

相关:Finding the center of a contour using opencv and visual c++