Getting division by zero error with Python and OpenCV

2024/11/13 9:33:32

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

src

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 npimg = 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) + y0if 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)

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

Answer

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)

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.

https://en.xdnf.cn/q/119369.html

Related Q&A

Pandas complex calculation based on other columns

I have successfully created new columns based on arithmetic for other columns but now I have a more challenging need to first select elements based on matches of multiple columns then perform math and …

how to generate word from a to z [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

How to webscrape all shoes on nike page using python

I am trying to webscrape all the shoes on https://www.nike.com/w/mens-shoes-nik1zy7ok. How do I scrape all the shoes including the shoes that load as you scroll down the page? The exact information I …

Pyo in Python: name Server not defined

I recently installed Pyo, and I entered Python 3.6 and typedfrom pyo import * s = Server().boot() s.start() sf = SfPlayer("C:\Users\myname\Downloads\wot.mp3", speed=1, loop=True).out()but I …

Limited digits with str.format(), and then only when they matter

If were printing a dollar amount, we usually want to always display two decimal digits.cost1, cost2 = 123.456890123456789, 357.000 print {c1:.2f} {c2:.2f}.format(c1=cost1, c2=cost2)shows123.46 357.00…

How is covariance implemented internally in numpy?

This is the definition of a covariance matrix. http://en.wikipedia.org/wiki/Covariance_matrix#DefinitionEach element in the matrix, except in the principal diagonal, (if I am not wrong) simplifies to E…

Pulling excel rows to display as a grid in tkinter

I am imaging fluorescent cells from a 384-well plate and my software spits out a formatted excel analysis of the data (16 rowsx24 columns of images turns into a list of data, with 2 measurements from e…

Django Migrating DB django.db.utils.ProgrammingError: relation django_site does not exist

Doing a site upgrade for Django, now pushing it to the server when I try python manage.py makemigrations I get this error (kpsga) sammy@kpsga:~/webapps/kpsga$ python manage.py makemigrations Traceback …

list intersection algorithm implementation only using python lists (not sets)

Ive been trying to write down a list intersection algorithm in python that takes care of repetitions. Im a newbie to python and programming so forgive me if this sounds inefficient, but I couldnt come …

In keras\tensorflow, How adding CNN layers to last layer of ResNet50V2 that pre-train on imagenet

I am trying to drop the last layer and add a simple CNN instead like the following, model = Sequential() base_model = ResNet50V2(include_top=False, weights="imagenet", input_shape=input_shape…