【问题标题】:Getting division by zero error with Python and OpenCV使用 Python 和 OpenCV 得到零错误除法
【发布时间】:2017-12-26 01:51:57
【问题描述】:

我正在使用此代码从下图中删除行:

我不知道原因,但它在第 34 行 - x0, x1, y0, y1 = (0, im_wb.shape[1], sum(y0_list)/len(y0_list), sum(y1_list)/len(y1_list)) 上给了我输出 ZeroDivisionError: division by zero error

这是什么原因?我该如何解决?

import cv2
import numpy as np

img = cv2.imread('lines.png',0)

# Applies threshold and inverts the image colors
(thresh, im_bw) = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
im_wb = (255-im_bw)

# Line parameters
minLineLength = 100
maxLineGap = 10
color = 255
size = 1

# Substracts the black line
lines = cv2.HoughLinesP(im_wb,1,np.pi/180,minLineLength,maxLineGap)[0]

# Makes a list of the y's located at position x0 and x1
y0_list = []
y1_list = []
for x0,y0,x1,y1 in lines:
    if x0 == 0:
        y0_list.append(y0)
    if x1 == im_wb.shape[1]:
        y1_list.append(y1)

# Calculates line thickness and its half
thick = max(len(y0_list), len(y1_list))
hthick = int(thick/2)

# Initial and ending point of the full line
x0, x1, y0, y1 = (0, im_wb.shape[1], sum(y0_list)/len(y0_list), sum(y1_list)/len(y1_list))

# Iterates all x's and prints makes a vertical line with the desired thickness
# when the point is surrounded by white pixels
for x in range(x1):
    y = int(x*(y1-y0)/x1) + y0
    if im_wb[y+hthick+1, x] == 0 and im_wb[y-hthick-1, x] == 0:
        cv2.line(img,(x,y-hthick),(x,y+hthick),colour,size)

cv2.imshow('clean', img)
cv2.waitKey(0)

问题指向另一个问题:Python: How to OCR characters crossed by a horizontal line

【问题讨论】:

  • 是什么原因? y_0 list 或 y1_list 为空怎么样,len() 将返回 0。
  • 是的,但是它们怎么是空的呢?我的意思是,图片正在加载中......
  • 我不认为HoughLine 是一个好的选择。我更喜欢 morph-op,这是我的结果。 i.stack.imgur.com/IBpyo.png 。你也可以看看这个stackoverflow.com/questions/47667238/…
  • 谢谢。一如既往的好。但是您知道为什么变量为空并给我错误吗?
  • @Silencer,另外,您建议的代码可以找到水平线,但是如果您查看我的答案的“来源”,您会发现该解决方案会通过删除来破坏图像遍地都是。结果应该是like this

标签: python opencv lines divide-by-zero


【解决方案1】:

错误的原因是y0_listy1_list(或两者)的长度为0。由于您在此 for 循环中初始化它们:

for x0,y0,x1,y1 in lines:
    if x0 == 0:
        y0_list.append(y0)
    if x1 == im_wb.shape[1]:
        y1_list.append(y1)

您可以将错误缩小到 lines 没有预期值或您的 2 个 if 语句有错误。我相信问题是由后者引起的,但您可以做的最简单的检查是打印出 lines 并手动检查您的 if 语句是否会被触发。

【讨论】:

  • 这很奇怪,仍然错误...仍然是 0 到 y0 和 y1 列表
  • 我稍微更新了我的答案。你能显示lines 变量的内容吗?您似乎希望在x=0 处找到行首,这似乎不太可能。
  • 你的lines 列表似乎只包含一行:(414, 23) - (416, 23)。这不会触发您的 if 条件,导致空列表,最终导致异常。所以恐怕你基本上有一些错误的推理,这是一个完全不同的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
相关资源
最近更新 更多