opencvhough-transformhoughlinesp

houghlinesp and thresholding


I am using opencv Houghlinesp to detect lines in a parking lot. Here is the source image

When I did a hough transform-p to detect the lines, I got final image like this.

It did detect empty spaces. Any ideas how these noisy lines on top of the cars can be removed? Or any direction on alternative algorithms or approaches highly appreciated.

img = cv.imread('Parking-Lot.jpg')
threshold=100
minLineLength = 60
rho=2
maxLineGap=20
theta = np.pi/180
edges = cv.Canny(img, 100, 200)
lines = cv.HoughLinesP(edges, rho, theta, threshold, np.array([]), minLineLength =minLineLength , maxLineGap=maxLineGap)
 for i in range(len(lines)):
    for line in lines[i]:
        cv.line(img, (line[0],line[1]), (line[2],line[3]), (0,255,0), 2)
cv2.imwrite("lines.jpg", img)

Solution

  • You can remove most of the noise by thresholding your image before you apply the edge detection. That way you will remove (most of) the cars and keep your white space lines you are interested in:

    import cv2
    import numpy as np
    
    img = cv2.imread('Parking-Lot.jpg')
    threshold=100
    minLineLength = 60
    rho=2
    maxLineGap=20
    theta = np.pi/180
    
    # here you convert the image to grayscale and then threshhold to binary
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret,thresh = cv2.threshold(gray,180,255,cv2.THRESH_BINARY)
    
    # continue with the threshholded image instead
    edges = cv2.Canny(thresh, 100, 200)
    lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]), minLineLength =minLineLength , maxLineGap=maxLineGap)
    for i in range(len(lines)):
      for line in lines[i]:
         cv2.line(img, (line[0],line[1]), (line[2],line[3]), (0,255,0), 2)
    cv2.imwrite("lines.jpg", img)
    

    This will yield you a much cleaner result:

    enter image description here

    Feel free to experiment with the threshold parameters; you will need to find a threshold that excludes most of the cars while keeping all the lines that you want to detect.