使用Python和OpenCV获得零错误除法

问题描述 投票:-1回答:1

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

src

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

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

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)

问题涉及另一个:qazxsw poi

python opencv lines divide-by-zero
1个回答
0
投票

那么错误的原因是Python: How to OCR characters crossed by a horizontal liney0_list(或两者)的长度为0。因为你在这个for循环中初始化它们:

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) 或你的2个lines语句有问题。我认为这个问题是由后者引起的,但你能做的最简单的检查就是打印if并手动检查你的lines语句是否会被触发。

© www.soinside.com 2019 - 2024. All rights reserved.