pythonopencvhoughlinesp

How can I improve the results of HoughLinesP() in my OpenCV Python script


I am trying to get all the lines in this image:

enter image description here

This is the code that I'm using:

threshold = 30
minLineLength =10
maxLineGap = 10
lines = cv2.HoughLinesP(img,1,np.pi/360, threshold, minLineLength, maxLineGap)

The problem is that I'm getting too many lines (~300):

enter image description here

But if I increase the threshold value it starts to miss some lines:

enter image description here

Is there any way of reducing the number of lines while keeping line-detection accurate?

Thanks in advance!


Solution

  • It works (mostly) fine for me in Python/OpenCV. Adjust your HoughP line arguments as appropriate.

    I think you need to threshold your image first. And perhaps thin the white lines.

    Input:

    enter image description here

    import cv2
    import numpy as np
    
    # read image as color not grayscale
    img = cv2.imread("lines.png", cv2.IMREAD_COLOR)
    
    # convert img to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # do threshold
    thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)[1]
    
    # get hough line segments
    threshold = 30
    minLineLength =10
    maxLineGap = 10
    lines = cv2.HoughLinesP(thresh, 1, np.pi/360, threshold, minLineLength, maxLineGap)
    
    # draw lines
    results = img.copy()
    for [line] in lines:
        print(line)
        x1 = line[0]
        y1 = line[1]
        x2 = line[2]
        y2 = line[3]
        cv2.line(results, (x1,y1), (x2,y2), (0,0,255), 1) 
    
    # show lines
    cv2.imshow("lines", results)
    cv2.waitKey(0)
    
    # write results
    cv2.imwrite("lines_hough.png",results)
    


    Resulting Hough lines in red:

    enter image description here

    You get a lot of parallel very close lines that you may want to merge somehow or thin out the list.