欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

OpenCV 车道线提取

发布时间:2025/5/22 编程问答 65 豆豆
生活随笔 收集整理的这篇文章主要介绍了 OpenCV 车道线提取 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

在车道线检测中,使用的是HSL颜色空间,其中H表示色相,即颜色,S表示饱和度,即颜色的纯度,L表示颜色的明亮程度。

本案例基于图像的梯度和颜色特征,定位车道线的位置。

在这里选用Sobel边缘提取算法,Sobel相比于Canny的优秀之处在于,它可以选择横向或纵向的边缘进行提取。从车道的拍摄图像可以看出,车道线在横向上的边缘突变是需要关心的问题。OpenCV提供的cv2.Sobel()函数,将进行边缘提取后的图像做二进制图的转化,即提取到边缘的像素点显示为白色(值为1),未提取到边缘的像素点显示为黑色(值为0)。由于只使用边缘检测,在有树木阴影覆盖的区域时,虽然能提取出车道线的大致轮廓,但会同时引入的噪声,给后续处理带来麻烦。所以在这里引入颜色阈值来解决这个问题。

import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimgdef pipeline(img, s_thresh=(170, 255), sx_thresh=(50, 300)):img = np.copy(img)#1.将图像转换为HLS色彩空间,并分离各个通道hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(np.float64)h_channel = hls[:, :, 0]l_channel = hls[:, :, 1]s_channel = hls[:, :, 2]#2.利用sobel计算x方向的梯度sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0)abs_sobelx = np.absolute(sobelx)# 将导数转换为8bit整数scaled_sobel = np.uint8(255 * abs_sobelx / np.max(abs_sobelx))sxbinary = np.zeros_like(scaled_sobel)sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1# 3.对s通道进行阈值处理s_binary = np.zeros_like(s_channel)s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1# 4. 将边缘检测的结果和颜色空间阈值的结果合并,并结合l通道的取值,确定车道提取的二值图结果color_binary = np.dstack((np.zeros_like(sxbinary), sxbinary, s_binary))return color_binarydef draw_images(img, undistorted, title, cmap):f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))f.tight_layout()ax1.imshow(img)ax1.set_title('Original Image', fontsize=50)if cmap is not None:ax2.imshow(undistorted, cmap=cmap)else:ax2.imshow(undistorted)ax2.set_title(title, fontsize=50)plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)plt.show()if __name__ == '__main__':image = mpimg.imread('./img.png')pipeline_img = pipeline(image)draw_images(image, pipeline_img, 'Pipeline Result', None)

代码运行结果:

总结:

  • 颜色空间:

    HLS:色相,饱和度,明亮程度

  • 车道线提取

    颜色空间转换 → 边缘检测 → 颜色阈值 → 合并得到检测结果。

  • 注:NumPy 1.20.0 后的版本 弃用了 np.float,需要改为 np.float64
    https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations

    弃用的名称相同NumPy标量类型名称
    numpy.boolboolnumpy.bool_
    numpy.intintnumpy.int_(默认)numpy.int64,或numpy.int32
    numpy.floatfloatnumpy.float64,numpy.float_,numpy.double
    numpy.complexcomplexnumpy.complex128,numpy.complex_,numpy.cdouble
    numpy.objectobjectnumpy.object_
    numpy.strstrnumpy.str_
    numpy.longintnumpy.int_,numpy.longlong
    numpy.unicodestrnumpy.unicode_

    总结

    以上是生活随笔为你收集整理的OpenCV 车道线提取的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。