Home Detecting almost straight lines using OpenCv in Python
Reply: 0

Detecting almost straight lines using OpenCv in Python

user8084 Published in September 19, 2018, 11:34 am

I am detecting straight lines in an image using OpenCv. Below is the code:

import cv2
import numpy as np

img = cv2.imread('Image.jpg')
img = img[:, 10:img.shape[1]-10]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
minLineLength = img.shape[1] - 300
lines = cv2.HoughLinesP(image=edges, rho=0.02, theta=np.pi / 500, threshold=10, lines=np.array([]), minLineLength=minLineLength, maxLineGap=2)
a, b, c = lines.shape
for i in range(a):
    cv2.line(img, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 2, cv2.LINE_AA)
cv2.imwrite('result.png', img)

For the image(Screenshot of a PDF) Image.jpg(Below) I am getting result.png(Below) as a result which is exactly the output I desire.



But when I give the below Image Test.jpg as an input, my algorithm is not working correctly. It is giving the following error:

a, b, c = lines.shape # 10th Line
AttributeError: 'NoneType' object has no attribute 'shape'

I think because in Test.jpg the horizontal lines are not that straight(because I clicked this by a phone's camera) and also If I change the minLineLength value to let's say 100 it is not showing the above error but showing incomplete faded lines on each row. So can anyone please tell me what params should I change in my algorithm to make it work correctly?


share|improve this question
  • First of all, what does your "10th line" comment mean? You've taken the dimensions of the returned vector of lines. According to the error message, lines is None at that point. I find that very strange: increasing the threshold should reduce the quantity of lines, not enable finding them where the lower value got none. Check that value of lines, and double-check the arguments you give to that call. – Prune Apr 17 at 16:18
  • that error is in the 10th line of the code posted. By changing the minLineLength I meant sorry. Look at the question again. @Prune – Aadit Apr 17 at 18:38

2 Answers 2

active oldest votes
up vote 1 down vote
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.31526 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO