pythonopencvhoughlines

Hough Line only writes 1 line in python with OpenCV and Numpy


I'm learning to use HoughLines() with Python, OpenCV, and numpy. I use the following image:

enter image description here

And i'm trying to detect all of the lines, not just the thickest lines. Here is the result:

enter image description here

And here is my code:

import cv2
import numpy as np
import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to the imput image")
args = vars(ap.parse_args())

img = cv2.imread(args['image'])
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
cv2.imwrite('edges_found.jpg',edges)
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)

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

    cv2.line(img, (x1,y1), (x2,y2), (0,0,255), 2)

cv2.imwrite('linesDetected.jpg',img)

I am using the tutorial / code here: https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html

This seems straight forward but in the tutorial, the images used is a sudoku in a newspaper and many lines are returned where I'm getting a single line. As you can see in the code, I have output edges to a separate image to see what is going on there, and this is the result:

enter image description here

It appears that many edges have been found, yet I'm only getting a single red line, rather than many. Where is my code incorrect?


Solution

  • This is because you only display one line in your code, there are actually more than just one.

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

    should be

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