In opencv using houghlines prints only one line

843 Views Asked by At

I started following some tutorials on opencv and working on houghlines, and noticed that what ever image I give it would only return one line!

I use opencv 4.2.0, and my code is:

import cv2
import numpy as np

image =cv2.imread("sudoku.jpg")
gray=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edges=cv2.Canny(gray, 100, 170,apertureSize=3)
cv2.imshow(" lines",edges)
cv2.waitKey()
cv2.destroyAllWindows()

lines=cv2.HoughLines(edges, 1, np.pi/180, 240)

for rho,theta in lines[0]:
    a=np.cos(theta)
    b=np.sin(theta)
    x0=a*rho
    y0=b*rho
    x1=int(x0+1000*(-b))
    y1=int(y0+1000*(a))
    x2=int(x0-1000*(-b))
    y2=int(y0-1000*(a))
    cv2.line(image,(x1,y1),(x2,y2),(255,0,0),2)

cv2.imshow("hough lines",image)
cv2.waitKey()
cv2.destroyAllWindows()
1

There are 1 best solutions below

1
On BEST ANSWER

Actually, the way data is stored in the lines variable is updated in the newer version of OpenCV due to which you are facing this issue.

Use the below nested for loop instead of you for loop to draw all lines on the image:

for line in lines:
    for rho,theta in line:
        a=np.cos(theta)
        b=np.sin(theta)
        x0=a*rho
        y0=b*rho
        x1=int(x0+1000*(-b))
        y1=int(y0+1000*(a))
        x2=int(x0-1000*(-b))
        y2=int(y0-1000*(a))
        cv2.line(image,(x1,y1),(x2,y2),(255,0,0),2)

To see how the data is stored, you can print lines variable.