OpenCv HoughLinesP bad lines

348 Views Asked by At

I'm a beginner and I'm trying to do some line detection in-game. This is the photo in which I'm trying to detect lanes This is the result The HoughLinesP code: ``` lines = cv2.HoughLinesP(cropped_image, 2, np.pi / 180, 100, np.array([]), minLineLength=50, maxLineGap=5)

# The displaying function:
def displayLines(image, lines):
    line_image = np.zeros_like(image)
    if lines is not None:
        for line in lines:
            x1, x2, y1, y2 = line.reshape(4)
            cv2.line(line_image, (x1, x2), (x2, y2), (0,255,0), 10)
    return line_image```
# Here is the cropping function: 
def region(image):
    height = image.shape[0]
    polygons = np.array([[
        (570, 640), (1600, 700), (863, 520)
    ]])
    mask = np.zeros_like(image)
    cv2.fillPoly(mask, polygons, 255)
    masked_image = cv2.bitwise_and(canny, mask)
    return masked_image
#As input I'm giving image with edges displayed. Function:
def canny(image):
    gray = cv2.cvtColor(lane_image, cv2.COLOR_RGB2GRAY)
    blur = cv2.GaussianBlur(gray, (5,5),0)
    canny = cv2.Canny(blur, 50, 150)
    return canny

I don't know what is the problem

1

There are 1 best solutions below

0
On

I recommend you mask out the noise before attempting to detect lines:

import cv2
import numpy as np

img = cv2.imread("driving_game.jpg")

img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower = np.array([18, 120, 200])
upper = np.array([30, 255, 255])
mask = cv2.inRange(img_hsv, lower, upper)
img_masked = cv2.bitwise_and(img, img, mask=mask)

cv2.imshow("Mask", mask)
cv2.imshow("Masked Image", img_masked)
cv2.waitKey(0)

Output:

enter image description here

enter image description here

Where the

lower = np.array([18, 120, 200])
upper = np.array([30, 255, 255])

are the lower and upper values for the HSV color mask. With the above mask, you won't even need the cv2.HoughLinesP method; you can simply detect the contours of the non-masked object and approximate the results:

import cv2
import numpy as np

def process(img):
    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    lower = np.array([18, 120, 200])
    upper = np.array([30, 255, 255])
    mask = cv2.inRange(img_hsv, lower, upper)
    mask_canny = cv2.Canny(mask, 50, 50)
    kernel = np.ones((2, 2))
    img_dilate = cv2.dilate(mask_canny, kernel, iterations=7)
    return cv2.erode(img_dilate, kernel, iterations=7)

def draw_lines(img):
    contours, _ = cv2.findContours(process(img), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        peri = cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, 0.13 * peri, True)
        cv2.drawContours(img, [approx], -1, (0, 0, 255), 5)

img = cv2.imread("driving_game.jpg")
draw_lines(img)

cv2.imshow("Lines Detected", img)
cv2.waitKey(0)

Output:

enter image description here