智慧交通day03-车道线检测实现06:车道线定位及拟合+代码实现

学习目标

  • 了解直方图确定车道线位置的思想

我们根据前面检测出的车道线信息,利用直方图和滑动窗口的方法,精确定位车道线,并进行拟合。

1. 定位思想

下图是我们检测到的车道线结果:

沿x轴方向统计每一列中白色像素点的个数,横坐标是图像的列数,纵坐标表示每列中白色点的数量,那么这幅图就是“直方图”,如下图所示:

对比上述两图,可以发现直方图左半边最大值对应的列数,即为左车道线所在的位置,直方图右半边最大值对应的列数,是右车道线所在的位置。

确定左右车道线的大致位置后,使用”滑动窗口“的方法,在图中对左右车道线的点进行搜索。

滑动窗口的搜索过程:

  • 设置搜索窗口大小(width和height):一般情况下width为手工设定,height为图片大小除以设置搜索窗口数目计算得到。

  • 以搜寻起始点作为当前搜索的基点,并以当前基点为中心,做一个网格化搜索。

  • 对每个搜索窗口分别做水平和垂直方向直方图统计,统计在搜索框区域内非零像素个数,并过滤掉非零像素数目小于50的框。

  • 计算非零像素坐标的均值作为当前搜索框的中心,并对这些中心点做一个二阶的多项式拟合,得到当前搜寻对应的车道线曲线参数。

2.实现

使用直方图和滑动窗口检测车道线的代码如下:

def cal_line_param(binary_warped):
    # 1.确定左右车道线的位置
    # 统计直方图
    histogram = np.sum(binary_warped[:, :], axis=0)
    # 在统计结果中找到左右最大的点的位置,作为左右车道检测的开始点
    # 将统计结果一分为二,划分为左右两个部分,分别定位峰值位置,即为两条车道的搜索位置
    midpoint = np.int(histogram.shape[0] / 2)
    leftx_base = np.argmax(histogram[:midpoint])
    rightx_base = np.argmax(histogram[midpoint:]) + midpoint
    # 2.滑动窗口检测车道线
    # 设置滑动窗口的数量,计算每一个窗口的高度
    nwindows = 9
    window_height = np.int(binary_warped.shape[0] / nwindows)
    # 获取图像中不为0的点
    nonzero = binary_warped.nonzero()
    nonzeroy = np.array(nonzero[0])
    nonzerox = np.array(nonzero[1])
    # 车道检测的当前位置
    leftx_current = leftx_base
    rightx_current = rightx_base
    # 设置x的检测范围,滑动窗口的宽度的一半,手动指定
    margin = 100
    # 设置最小像素点,阈值用于统计滑动窗口区域内的非零像素个数,小于50的窗口不对x的中心值进行更新
    minpix = 50
    # 用来记录搜索窗口中非零点在nonzeroy和nonzerox中的索引
    left_lane_inds = []
    right_lane_inds = []

    # 遍历该副图像中的每一个窗口
    for window in range(nwindows):
        # 设置窗口的y的检测范围,因为图像是(行列),shape[0]表示y方向的结果,上面是0
        win_y_low = binary_warped.shape[0] - (window + 1) * window_height
        win_y_high = binary_warped.shape[0] - window * window_height
        # 左车道x的范围
        win_xleft_low = leftx_current - margin
        win_xleft_high = leftx_current + margin
        # 右车道x的范围
        win_xright_low = rightx_current - margin
        win_xright_high = rightx_current + margin

        # 确定非零点的位置x,y是否在搜索窗口中,将在搜索窗口内的x,y的索引存入left_lane_inds和right_lane_inds中
        good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
                          (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]
        good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
                           (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]
        left_lane_inds.append(good_left_inds)
        right_lane_inds.append(good_right_inds)

        # 如果获取的点的个数大于最小个数,则利用其更新滑动窗口在x轴的位置
        if len(good_left_inds) > minpix:
            leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
        if len(good_right_inds) > minpix:
            rightx_current = np.int(np.mean(nonzerox[good_right_inds]))

    # 将检测出的左右车道点转换为array
    left_lane_inds = np.concatenate(left_lane_inds)
    right_lane_inds = np.concatenate(right_lane_inds)

    # 获取检测出的左右车道点在图像中的位置
    leftx = nonzerox[left_lane_inds]
    lefty = nonzeroy[left_lane_inds]
    rightx = nonzerox[right_lane_inds]
    righty = nonzeroy[right_lane_inds]

    # 3.用曲线拟合检测出的点,二次多项式拟合,返回的结果是系数
    left_fit = np.polyfit(lefty, leftx, 2)
    right_fit = np.polyfit(righty, rightx, 2)
    return left_fit, right_fit

车道线的检测的拟合结果如下图所示:

其中绿色的方框是滑动窗口的结果,中间的黄线是车道线拟合的结果。

下面我们将车道区域绘制处理,即在检测出的车道线中间绘制多边形,代码如下:

def fill_lane_poly(img, left_fit, right_fit):
    # 获取图像的行数
    y_max = img.shape[0]
    # 设置输出图像的大小,并将白色位置设为255
    out_img = np.dstack((img, img, img)) * 255
    # 在拟合曲线中获取左右车道线的像素位置
    left_points = [[left_fit[0] * y ** 2 + left_fit[1] * y + left_fit[2], y] for y in range(y_max)]
    right_points = [[right_fit[0] * y ** 2 + right_fit[1] * y + right_fit[2], y] for y in range(y_max - 1, -1, -1)]
    # 将左右车道的像素点进行合并
    line_points = np.vstack((left_points, right_points))
    # 根据左右车道线的像素位置绘制多边形
    cv2.fillPoly(out_img, np.int_([line_points]), (0, 255, 0))
    return out_img

效果如下图所示:

其中两个方法给大家介绍下:

np.vstack:按垂直方向(行顺序)堆叠数组构成一个新的数组

np.dstack:按水平方向(列顺序)堆叠数组构成一个新的数组

np.hstack(),np.vstack()解读_lllxxq141592654的博客-CSDN博客_np.vstack()https://blog.csdn.net/lllxxq141592654/article/details/84260091https://blog.csdn.net/lllxxq141592654/article/details/84260091icon-default.png?t=LA92https://blog.csdn.net/lllxxq141592654/article/details/84260091

示例如下:

将检测出的车道逆投影到原始图像,直接调用透视变换的方法即可:

transform_img_inverse = img_perspect_transform(result, M_inverse)

效果如下图所示:

最后将其叠加在原图像上,则有:

总结:

知道车道线精确定位的思想:

首先利用直方图的方法确定左右车道线的位置,然后利用滑动窗口的方法,搜索车道线位置,并进行拟合,然后绘制车道区域,并进行反投影,得到原始图像中的车道区域。


代码实现:

# encoding:utf-8

from matplotlib import font_manager
my_font = font_manager.FontProperties(fname="/System/Library/Fonts/PingFang.ttc")

import cv2
import numpy as np
import matplotlib.pyplot as plt
#遍历文件夹
import glob
from moviepy.editor import VideoFileClip
import sys
reload(sys)
sys.setdefaultencoding('utf-8')



"""参数设置"""
nx = 9
ny = 6
#获取棋盘格数据
file_paths = glob.glob("./camera_cal/calibration*.jpg")


#相机矫正使用opencv封装好的api
#目的:得到内参、外参、畸变系数
def cal_calibrate_params(file_paths):
    #存储角点数据的坐标
    object_points = [] #角点在真实三维空间的位置
    image_points = [] #角点在图像空间中的位置
    #生成角点在真实世界中的位置
    objp = np.zeros((nx*ny,3),np.float32)
    #以棋盘格作为坐标,每相邻的黑白棋的相差1
    objp[:,:2] = np.mgrid[0:nx,0:ny].T.reshape(-1,2)
    #角点检测
    for file_path in file_paths:
        img = cv2.imread(file_path)
        #将图像灰度化
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        #角点检测
        rect,coners = cv2.findChessboardCorners(gray,(nx,ny),None)

        #若检测到角点,则进行保存 即得到了真实坐标和图像坐标
        if rect == True :
            object_points.append(objp)
            image_points.append(coners)
    # 相机较真
    ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(object_points, image_points, gray.shape[::-1], None, None)
    return ret, mtx, dist, rvecs, tvecs

# 图像去畸变:利用相机校正的内参,畸变系数
def img_undistort(img, mtx, dist):
    dis = cv2.undistort(img, mtx, dist, None, mtx)
    return dis

#车道线提取
#颜色空间转换--》边缘检测--》颜色阈值--》并且使用L通道进行白色的区域进行抑制
def pipeline(img,s_thresh = (170,255),sx_thresh=(40,200)):
    # 复制原图像
    img = np.copy(img)
    # 颜色空间转换
    hls = cv2.cvtColor(img,cv2.COLOR_RGB2HLS).astype(np.float)
    l_chanel = hls[:,:,1]
    s_chanel = hls[:,:,2]
    #sobel边缘检测
    sobelx = cv2.Sobel(l_chanel,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)
    #边缘位置赋值为1,非边缘位置赋值为0
    sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1

    #对S通道进行阈值处理
    s_binary = np.zeros_like(s_chanel)
    s_binary[(s_chanel >= s_thresh[0]) & (s_chanel <= s_thresh[1])] = 1

    # 结合边缘提取结果和颜色通道的结果,
    color_binary = np.zeros_like(sxbinary)
    color_binary[((sxbinary == 1) | (s_binary == 1)) & (l_chanel > 100)] = 1
    return color_binary

#透视变换-->将检测结果转换为俯视图。
#获取透视变换的参数矩阵【二值图的四个点】
def cal_perspective_params(img,points):
    # x与y方向上的偏移
    offset_x = 330
    offset_y = 0
    #转换之后img的大小
    img_size = (img.shape[1],img.shape[0])
    src = np.float32(points)
    #设置俯视图中的对应的四个点 左上角 右上角 左下角 右下角
    dst = np.float32([[offset_x, offset_y], [img_size[0] - offset_x, offset_y],
                      [offset_x, img_size[1] - offset_y], [img_size[0] - offset_x, img_size[1] - offset_y]])
    ## 原图像转换到俯视图
    M = cv2.getPerspectiveTransform(src, dst)
    # 俯视图到原图像
    M_inverse = cv2.getPerspectiveTransform(dst, src)
    return M, M_inverse

#根据透视变化矩阵完成透视变换
def img_perspect_transform(img,M):
    #获取图像大小
    img_size = (img.shape[1],img.shape[0])
    #完成图像的透视变化
    return cv2.warpPerspective(img,M,img_size)

# 精确定位车道线
#传入已经经过边缘检测的图像阈值结果的二值图,再进行透明变换
def cal_line_param(binary_warped):
    #定位车道线的大致位置==计算直方图
    histogram = np.sum(binary_warped[:,:],axis=0) #计算y轴
    # 将直方图一分为二,分别进行左右车道线的定位
    midpoint = np.int(histogram.shape[0]/2)
    #分别统计左右车道的最大值
    midpoint = np.int(histogram.shape[0] / 2)
    leftx_base = np.argmax(histogram[:midpoint]) #左车道
    rightx_base = np.argmax(histogram[midpoint:]) + midpoint #右车道
    #设置滑动窗口
    #对每一个车道线来说 滑动窗口的个数
    nwindows = 9
    #设置滑动窗口的高
    window_height = np.int(binary_warped.shape[0]/nwindows)
    #设置滑动窗口的宽度==x的检测范围,即滑动窗口的一半
    margin = 100
    #统计图像中非0点的个数
    nonzero = binary_warped.nonzero()
    nonzeroy = np.array(nonzero[0])#非0点的位置-x坐标序列
    nonzerox = np.array(nonzero[1])#非0点的位置-y坐标序列
    #车道检测位置
    leftx_current = leftx_base
    rightx_current = rightx_base
    #设置阈值:表示当前滑动窗口中的非0点的个数
    minpix = 50
    #记录窗口中,非0点的索引
    left_lane_inds = []
    right_lane_inds = []

    #遍历滑动窗口
    for window in range(nwindows):
        # 设置窗口的y的检测范围,因为图像是(行列),shape[0]表示y方向的结果,上面是0
        win_y_low = binary_warped.shape[0] - (window + 1) * window_height #y的最低点
        win_y_high = binary_warped.shape[0] - window * window_height #y的最高点
        # 左车道x的范围
        win_xleft_low = leftx_current - margin
        win_xleft_high = leftx_current + margin
        # 右车道x的范围
        win_xright_low = rightx_current - margin
        win_xright_high = rightx_current + margin

        # 确定非零点的位置x,y是否在搜索窗口中,将在搜索窗口内的x,y的索引存入left_lane_inds和right_lane_inds中
        good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
                          (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]
        good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
                           (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]
        left_lane_inds.append(good_left_inds)
        right_lane_inds.append(good_right_inds)

        # 如果获取的点的个数大于最小个数,则利用其更新滑动窗口在x轴的位置=修正车道线的位置
        if len(good_left_inds) > minpix:
            leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
        if len(good_right_inds) > minpix:
            rightx_current = np.int(np.mean(nonzerox[good_right_inds]))

    # 将检测出的左右车道点转换为array
    left_lane_inds = np.concatenate(left_lane_inds)
    right_lane_inds = np.concatenate(right_lane_inds)

    # 获取检测出的左右车道x与y点在图像中的位置
    leftx = nonzerox[left_lane_inds]
    lefty = nonzeroy[left_lane_inds]
    rightx = nonzerox[right_lane_inds]
    righty = nonzeroy[right_lane_inds]

    # 3.用曲线拟合检测出的点,二次多项式拟合,返回的结果是系数
    left_fit = np.polyfit(lefty, leftx, 2)
    right_fit = np.polyfit(righty, rightx, 2)
    return left_fit, right_fit

#填充车道线之间的多边形
def fill_lane_poly(img,left_fit,right_fit):
    #行数
    y_max = img.shape[0]
    #设置填充之后的图像的大小 取到0-255之间
    out_img = np.dstack((img,img,img))*255
    #根据拟合结果,获取拟合曲线的车道线像素位置
    left_points = [[left_fit[0] * y ** 2 + left_fit[1] * y + left_fit[2], y] for y in range(y_max)]
    right_points = [[right_fit[0] * y ** 2 + right_fit[1] * y + right_fit[2], y] for y in range(y_max - 1, -1, -1)]
    # 将左右车道的像素点进行合并
    line_points = np.vstack((left_points, right_points))
    # 根据左右车道线的像素位置绘制多边形
    cv2.fillPoly(out_img, np.int_([line_points]), (0, 255, 0))
    return out_img



if __name__ == "__main__":
    #透视变换
    #获取原图的四个点
    img = cv2.imread('./test/straight_lines2.jpg')
    points = [[601, 448], [683, 448], [230, 717], [1097, 717]]
    #将四个点绘制到图像上 (文件,坐标起点,坐标终点,颜色,连接起来)
    img = cv2.line(img, (601, 448), (683, 448), (0, 0, 255), 3)
    img = cv2.line(img, (683, 448), (1097, 717), (0, 0, 255), 3)
    img = cv2.line(img, (1097, 717), (230, 717), (0, 0, 255), 3)
    img = cv2.line(img, (230, 717), (601, 448), (0, 0, 255), 3)

    #透视变换的矩阵
    M,M_inverse = cal_perspective_params(img,points)

    #车道线检测演示
    ret, mtx, dist, rvecs, tvecs = cal_calibrate_params(file_paths)
    undistort_img = img_undistort(img,mtx,dist)
    #提取车道线
    pipeline_img = pipeline(undistort_img)
    #透视变换
    trasform_img = img_perspect_transform(pipeline_img,M)
    #计算车道线的拟合结果
    left_fit,right_fit = cal_line_param(trasform_img)
    #进行填充
    result = fill_lane_poly(trasform_img,left_fit,right_fit)
    plt.figure()
    # 反转CV2中BGR 转化为matplotlib的RGB
    plt.imshow(result[:, :, ::-1])
    plt.title("vertical view:FULL")
    plt.show()

    #透视变换的逆变换
    trasform_img_inv = img_perspect_transform(result,M_inverse)
    plt.figure()
    # 反转CV2中BGR 转化为matplotlib的RGB
    plt.imshow(trasform_img_inv[:, :, ::-1])
    plt.title("Original drawing:FULL")
    plt.show()

    #与原图进行叠加
    res = cv2.addWeighted(img,1,trasform_img_inv,0.5,0)
    plt.figure()
    # 反转CV2中BGR 转化为matplotlib的RGB
    plt.imshow(res[:, :, ::-1])
    plt.title("safe work")
    plt.show()

输出:

猜你喜欢

转载自blog.csdn.net/qq_39237205/article/details/121452094#comments_20662539