Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find number of lines in an image using hough transform?

I'm not able to get the exact number of lines that are present in the image using hough transform.

I've found the houghLines for the image and now when printing the number of lines using the hough lines mapped image i'm not able to get the exact number of lines.

import cv2
import numpy as np
import matplotlib.pyplot as plt


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

edges=cv2.Canny(img,0,150)


lines = cv2.HoughLinesP(edges, 2, 1*np.pi/180, 45, minLineLength=1, maxLineGap=1)



for line in lines:
  x1,y1,x2,y2=line[0]
  cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2) 


plt.imshow(img)
print(len(lines))

The expected output is 5, but actual output is 7 from the following image:

input image

like image 563
Nandu Avatar asked Dec 04 '25 08:12

Nandu


1 Answers

Instead of using cv2.HoughLinesP(), a much simpler approach is to threshold and find contours. When iterating through cv2.findContours(), you can keep track of the number of lines with a counter. If you insist on using cv2.HoughLinesP(), you could play with the minLineLength and maxLineGap parameters to correctly detect the desired lines


Threshold

enter image description here

Detected lines

enter image description here

Result

5

import cv2

image = cv2.imread('1.png')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY_INV)[1]

cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

lines = 0
for c in cnts:
    cv2.drawContours(image, [c], -1, (36,255,12), 3)
    lines += 1

print(lines)
cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()
like image 87
nathancy Avatar answered Dec 07 '25 00:12

nathancy