OpenCV 车道线提取

该代码示例展示了如何在车道线检测中应用HLS颜色空间和Sobel边缘检测算法。首先,将RGB图像转换为HLS空间,然后分别处理色相、饱和度和亮度通道。接着,利用Sobel算子计算饱和度通道的水平梯度,并通过设定阈值获取二值图像。同时,对饱和度通道直接进行阈值处理。最后,将两种结果合并得到车道线的二值图像。这种方法在存在阴影干扰时可能会引入噪声,但能有效定位车道线位置。
摘要由CSDN通过智能技术生成

在车道线检测中,使用的是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 mpimg

def 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_binary

def 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)

代码运行结果:
在这里插入图片描述
总结:

  1. 颜色空间:

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

  2. 车道线提取

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

注: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_
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值