使用Python和OpenCV除以零错误 [英] Getting division by zero error with Python and OpenCV

查看:169
本文介绍了使用Python和OpenCV除以零错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using this code to remove the lines from the following image:

我不知道原因,但是它在第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.

I don't know the reason, but it gives me as output ZeroDivisionError: division by zero error on line 34 - x0, x1, y0, y1 = (0, im_wb.shape[1], sum(y0_list)/len(y0_list), sum(y1_list)/len(y1_list)).

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

What's the reason ? How can I fix it ?

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 :如何OCR字符横线交叉

The question reffers to this other one: Python: How to OCR characters crossed by a horizontal line

推荐答案

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

Well the cause of the error is that the length is 0 of either y0_list or y1_list (or both). Since you initialize them in this for loop :

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语句是否会被触发.

You can narrow your error down to either lines not having the expected values or your 2 if statements being faulty. I believe the problem is caused by the latter but the easiest check you can do is print out lines and check manually if your if statements would be triggered.

这篇关于使用Python和OpenCV除以零错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆