python中用Canny边缘检测和霍夫变实现车道线检测方法

描述

Canny边缘检测+霍夫变换

颜色阈值+图像掩模的方法虽然简单,但是只能应对一些固定颜色车道线的场景。图像像素受光照影响将是一个极其常见的问题。

canny边缘检测+霍夫变换是另外一种简单提取车道线的方法。首先依靠canny提取到原图像的边缘信息,再依靠霍夫变换提取满足要求的直线

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2




# Read in and grayscale the image
image = mpimg.imread('test.jpg')
gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)


# Define a kernel size and apply Gaussian smoothing
kernel_size = 5
blur_gray = cv2.GaussianBlur(gray,(kernel_size, kernel_size),0)


# Define our parameters for Canny and apply
low_threshold = 50
high_threshold = 150
edges = cv2.Canny(blur_gray, low_threshold, high_threshold)


# Next we'll create a masked edges image using cv2.fillPoly()
mask = np.zeros_like(edges)
ignore_mask_color = 255


# This time we are defining a four sided polygon to mask
imshape = image.shape
vertices = np.array([[(0,imshape[0]),(0, 0), (imshape[1], 0), (imshape[1],imshape[0])]], dtype=np.int32)  # all image
# vertices = np.array([[(0,imshape[0]),(554, 460), (700, 446), (imshape[1],imshape[0])]], dtype=np.int32)  # defining a quadrilateral region
cv2.fillPoly(mask, vertices, ignore_mask_color)
masked_edges = cv2.bitwise_and(edges, mask)


# Define the Hough transform parameters
# Make a blank the same size as our image to draw on
rho = 1 # distance resolution in pixels of the Hough grid
theta = np.pi/180 # angular resolution in radians of the Hough grid
threshold = 1     # minimum number of votes (intersections in Hough grid cell)
min_line_length = 5 #minimum number of pixels making up a line
max_line_gap = 1    # maximum gap in pixels between connectable line segments
line_image = np.copy(image)*0 # creating a blank to draw lines on


# Run Hough on edge detected image
# Output "lines" is an array containing endpoints of detected line segments
lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]),
                            min_line_length, max_line_gap)


# Iterate over the output "lines" and draw lines on a blank image
for line in lines:
    for x1,y1,x2,y2 in line:
        cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10)


# Create a "color" binary image to combine with line image
color_edges = np.dstack((edges, edges, edges))


# Draw the lines on the edge image
lines_edges = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0)
plt.imshow(lines_edges)
plt.show()

canny边缘后,进行霍夫直线检测的结果

python

在此基础上,增加一个四边形的图像掩模的结果

四边形的设定,写在了代码中,只是进行了注释

python

总结:

以上两种方法只适合简单的demo,显然并不能识别具备一定曲率的车道线,也无法适应光照不同的情况。

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分