Search code examples
pythonopencvhough-transform

Python CV2 does not detect obvious lines


Here's the image

I am new to computer vision. The goal is to detect the nearly vertical black lines in a lattice and rotate them to vertical. I applied a Hough line transform. However it is not seeing the obvious black lines.

Here is the code. What did I get wrong?

lines = cv2.HoughLinesP(binary_image, 50, np.pi/180, threshold=50, minLineLength=100, maxLineGap=500)

image_with_lines = binary_image.copy()
for line in lines:
    x1, y1, x2, y2 = line[0]
    angle_rad = np.arctan2(y2 - y1, x2 - x1)  
    angle_deg = np.degrees(angle_rad)
    
    if 88 <= angle_deg <= 92:  
        cv2.line(image_with_lines, (x1, y1), (x2, y2), (0,0,255), 5) 

Thank you for your help!


Solution

  • This is a workaround solution. I did the following steps

    1. Threshold and inverted the binary image.
    2. Dilated the image to create a continuous point close to a complete line. Can use 'DILATE_PARAMETER' to adjust the dilation.
    3. Adjusted cv2.HoughLinesP parameters
    import cv2
    import numpy as np
    #Parameter to control dilation to create a continuous line.
    DILATE_PARAMETER = 2
    
    original_image = cv2.imread('input_image.jpg')
    binary_image = cv2.imread('input_image.jpg',0)
    binary_image[binary_image<127] =0
    binary_image[binary_image>=127] =255
    
    #Inverting the image.
    binary_image = cv2.bitwise_not(binary_image)
    
    kernel = np.ones((3,3), np.uint8)
    binary_image = cv2.dilate(binary_image, kernel, iterations = 2)
    for _ in range(DILATE_PARAMETER-1):
            binary_image = cv2.dilate(binary_image, kernel, iterations = 2)
        
    #print(np.unique(binary_image))
    #print(binary_image.shape)
    
    #Can check the images after inverting and dilation
    cv2.imwrite('binary_image.jpg',binary_image)
    
    lines = cv2.HoughLinesP(binary_image, 1, np.pi/180, threshold=150, minLineLength=400, maxLineGap=20)
    for line in lines:    
        x1, y1, x2, y2 = line[0]
        angle_rad = np.arctan2(y2 - y1, x2 - x1)  
        angle_deg = np.degrees(angle_rad)
        
        if 80 <= angle_deg <= 100:  
            print("Found Line : ", line[0], " in angle :", angle_deg)        
            cv2.line(original_image, (x1, y1), (x2, y2), 255, 5)
    
    cv2.imwrite('image_with_lines.jpg',original_image)
    

    output

    Found Line :  [580   1 608 526]  in angle : 86.94711748520757
    Found Line :  [600  34 608 514]  in angle : 89.04515874612783
    Found Line :  [597  35 606 526]  in angle : 88.94988945946136
    Found Line :  [270  93 277 516]  in angle : 89.0519294294594
    Found Line :  [581  36 606 510]  in angle : 86.98086815086273
    

    enter image description here