学习目标

  • 知道车道曲率计算的方法
  • 知道计算中心点偏离距离的计算

1.曲率的介绍

曲线的曲率就是针对曲线上某个点的切线方向角对弧长的转动率,通过微分来定义,表明曲线偏离直线的程度。数学上表明曲线在某一点的弯曲程度的数值。曲率越大,表示曲线的弯曲程度越大。曲率的倒数就是曲率半径。

1.1.圆的曲率

下面有三个球体,网球、篮球、地球,半径越小的越容易看出是圆的,所以随着半径的增加,圆的程度就越来越弱了。

定义球体或者圆的“圆”的程度,就是 曲率 ,计算方法为:

其中rr为球体或者圆的半径,这样半径越小的圆曲率越大,直线可以看作半径为无穷大的圆,其曲率为:

1.2.曲线的曲率

不同的曲线有不同的弯曲程度:

怎么来表示某一条曲线的弯曲程度呢?

我们知道三点确定一个圆:

当δ  趋近于0时,我们可以的到曲线在x_0x​0​​处的密切圆,也就是曲线在该点的圆近似:

另,在曲线比较平坦的位置,密切圆较大,在曲线比较弯曲的地方,密切圆较小,

因此,我们通过密切圆的曲率来定义曲线的曲率,定义如下:

2.实现

计算曲率半径的方法,代码实现如下:

def cal_radius(img, left_fit, right_fit):# 图像中像素个数与实际中距离的比率# 沿车行进的方向长度大概覆盖了30米,按照美国高速公路的标准,宽度为3.7米(经验值)ym_per_pix = 30 / 720  # y方向像素个数与距离的比例xm_per_pix = 3.7 / 700  # x方向像素个数与距离的比例# 计算得到曲线上的每个点left_y_axis = np.linspace(0, img.shape[0], img.shape[0] - 1)left_x_axis = left_fit[0] * left_y_axis ** 2 + left_fit[1] * left_y_axis + left_fit[2]right_y_axis = np.linspace(0, img.shape[0], img.shape[0] - 1)right_x_axis = right_fit[0] * right_y_axis ** 2 + right_fit[1] * right_y_axis + right_fit[2]# 获取真实环境中的曲线left_fit_cr = np.polyfit(left_y_axis * ym_per_pix, left_x_axis * xm_per_pix, 2)right_fit_cr = np.polyfit(right_y_axis * ym_per_pix, right_x_axis * xm_per_pix, 2)# 获得真实环境中的曲线曲率left_curverad = ((1 + (2 * left_fit_cr[0] * left_y_axis * ym_per_pix + left_fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * left_fit_cr[0])right_curverad = ((1 + (2 * right_fit_cr[0] * right_y_axis * ym_per_pix + right_fit_cr[1]) ** 2) ** 1.5) / np.absolute(2 * right_fit_cr[0])# 在图像上显示曲率cv2.putText(img, 'Radius of Curvature = {}(m)'.format(np.mean(left_curverad)), (20, 50), cv2.FONT_ITALIC, 1,(255, 255, 255), 5)return img

曲率半径显示效果:

计算偏离中心的距离:

# 1. 定义函数计算图像的中心点位置
def cal_line__center(img):undistort_img = img_undistort(img, mtx, dist)rigin_pipline_img = pipeline(undistort_img)transform_img = img_perspect_transform(rigin_pipline_img, M)left_fit, right_fit = cal_line_param(transform_img)y_max = img.shape[0]left_x = left_fit[0] * y_max ** 2 + left_fit[1] * y_max + left_fit[2]right_x = right_fit[0] * y_max ** 2 + right_fit[1] * y_max + right_fit[2]return (left_x + right_x) / 2# 2. 假设straight_lines2_line.jpg,这张图片是位于车道的中央,实际情况可以根据测量验证.
img =cv2.imread("./test/straight_lines2_line.jpg")
lane_center = cal_line__center(img)
print("车道的中心点为:{}".format(lane_center))# 3. 计算偏离中心的距离
def cal_center_departure(img, left_fit, right_fit):# 计算中心点y_max = img.shape[0]left_x = left_fit[0] * y_max ** 2 + left_fit[1] * y_max + left_fit[2]right_x = right_fit[0] * y_max ** 2 + right_fit[1] * y_max + right_fit[2]xm_per_pix = 3.7 / 700center_depart = ((left_x + right_x) / 2 - lane_center) * xm_per_pix# 在图像上显示偏移if center_depart > 0:cv2.putText(img, 'Vehicle is {}m right of center'.format(center_depart), (20, 100), cv2.FONT_ITALIC, 1,(255, 255, 255), 5)elif center_depart < 0:cv2.putText(img, 'Vehicle is {}m left of center'.format(-center_depart), (20, 100), cv2.FONT_ITALIC, 1,(255, 255, 255), 5)else:cv2.putText(img, 'Vehicle is in the center', (20, 100), cv2.FONT_ITALIC, 1, (255, 255, 255), 5)return img

计算偏离中心显示效果如下:


总结

  1. 曲率是表示曲线的弯曲程度,在这里是计算车道的弯曲程度
  2. 偏离中心的距离:利用已知的在中心的图像计算其他图像的偏离距离

总代码汇总:

# encoding:utf-8from 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")# # 绘制对比图
# def plot_contrast_image(origin_img, converted_img, origin_img_title="origin_img", converted_img_title="converted_img",
#                         converted_img_gray=False):
#     fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 20))
#     ax1.set_title = origin_img_title
#     ax1.imshow(origin_img)
#     ax2.set_title = converted_img_title
#     if converted_img_gray == True:
#         ax2.imshow(converted_img, cmap="gray")
#     else:
#         ax2.imshow(converted_img)
#     plt.show()#相机矫正使用opencv封装好的api
#目的:得到内参、外参、畸变系数
def cal_calibrate_params(file_paths):#存储角点数据的坐标object_points = [] #角点在真实三维空间的位置image_points = [] #角点在图像空间中的位置#生成角点在真实世界中的位置objp = np.zeros((nx*ny,3),np.float32)#以棋盘格作为坐标,每相邻的黑白棋的相差1objp[:,: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,非边缘位置赋值为0sxbinary[(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)] = 1return color_binary#透视变换-->将检测结果转换为俯视图。
#获取透视变换的参数矩阵【二值图的四个点】
def cal_perspective_params(img,points):# x与y方向上的偏移offset_x = 330offset_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_baserightx_current = rightx_base#设置阈值:表示当前滑动窗口中的非0点的个数minpix = 50#记录窗口中,非0点的索引left_lane_inds = []right_lane_inds = []#遍历滑动窗口for window in range(nwindows):# 设置窗口的y的检测范围,因为图像是(行列),shape[0]表示y方向的结果,上面是0win_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 - marginwin_xleft_high = leftx_current + margin# 右车道x的范围win_xright_low = rightx_current - marginwin_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]))# 将检测出的左右车道点转换为arrayleft_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#计算车道线曲率的方法
def cal_readius(img,left_fit,right_fit):# 比例ym_per_pix = 30/720xm_per_pix = 3.7/700# 得到车道线上的每个点left_y_axis = np.linspace(0,img.shape[0],img.shape[0]-1) #个数img.shape[0]-1left_x_axis = left_fit[0]*left_y_axis**2+left_fit[1]*left_y_axis+left_fit[0]right_y_axis = np.linspace(0,img.shape[0],img.shape[0]-1)right_x_axis = right_fit[0]*right_y_axis**2+right_fit[1]*right_y_axis+right_fit[2]# 把曲线中的点映射真实世界,再计算曲率left_fit_cr = np.polyfit(left_y_axis*ym_per_pix,left_x_axis*xm_per_pix,2)right_fit_cr = np.polyfit(right_y_axis*ym_per_pix,right_x_axis*xm_per_pix,2)# 计算曲率left_curverad = ((1+(2*left_fit_cr[0]*left_y_axis*ym_per_pix+left_fit_cr[1])**2)**1.5)/np.absolute(2*left_fit_cr[0])right_curverad = ((1+(2*right_fit_cr[0]*right_y_axis*ym_per_pix *right_fit_cr[1])**2)**1.5)/np.absolute((2*right_fit_cr[0]))# 将曲率半径渲染在图像上 写什么cv2.putText(img,'Radius of Curvature = {}(m)'.format(np.mean(left_curverad)),(20,50),cv2.FONT_ITALIC,1,(255,255,255),5)return img# 计算车道线中心的位置
def cal_line_center(img):#去畸变undistort_img = img_undistort(img,mtx,dist)#提取车道线rigin_pipeline_img = pipeline(undistort_img)#透视变换trasform_img = img_perspect_transform(rigin_pipeline_img,M)#精确定位left_fit,right_fit = cal_line_param(trasform_img)#当前图像的shape[0]y_max = img.shape[0]#左车道线left_x = left_fit[0]*y_max**2+left_fit[1]*y_max+left_fit[2]#右车道线right_x = right_fit[0]*y_max**2+right_fit[1]*y_max+right_fit[2]#返回车道中心点return (left_x+right_x)/2def cal_center_departure(img,left_fit,right_fit):# 计算中心点y_max = img.shape[0]left_x = left_fit[0]*y_max**2 + left_fit[1]*y_max +left_fit[2]right_x = right_fit[0]*y_max**2 +right_fit[1]*y_max +right_fit[2]xm_per_pix = 3.7/700center_depart = ((left_x+right_x)/2-lane_center)*xm_per_pix# 渲染if center_depart>0:cv2.putText(img,'Vehicle is {}m right of center'.format(center_depart), (20, 100), cv2.FONT_ITALIC, 1,(255, 255, 255), 5)elif center_depart<0:cv2.putText(img, 'Vehicle is {}m left of center'.format(-center_depart), (20, 100), cv2.FONT_ITALIC, 1,(255, 255, 255), 5)else:cv2.putText(img, 'Vehicle is in the center', (20, 100), cv2.FONT_ITALIC, 1, (255, 255, 255), 5)return img#计算车辆偏离中心点的距离
def cal_center_departure(img,left_fit,right_fit):# 计算中心点y_max = img.shape[0]#左车道线left_x = left_fit[0]*y_max**2 + left_fit[1]*y_max +left_fit[2]#右车道线right_x = right_fit[0]*y_max**2 +right_fit[1]*y_max +right_fit[2]#x方向上每个像素点代表的距离大小xm_per_pix = 3.7/700#计算偏移距离 像素距离 × xm_per_pix = 实际距离center_depart = ((left_x+right_x)/2-lane_center)*xm_per_pix# 渲染if center_depart>0:cv2.putText(img,'Vehicle is {}m right of center'.format(center_depart), (20, 100), cv2.FONT_ITALIC, 1,(255, 255, 255), 5)elif center_depart<0:cv2.putText(img, 'Vehicle is {}m left of center'.format(-center_depart), (20, 100), cv2.FONT_ITALIC, 1,(255, 255, 255), 5)else:cv2.putText(img, 'Vehicle is in the center', (20, 100), cv2.FONT_ITALIC, 1, (255, 255, 255), 5)return imgif __name__ == "__main__":ret, mtx, dist, rvecs, tvecs = cal_calibrate_params(file_paths)#透视变换#获取原图的四个点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)#计算车道线的中心距离lane_center = cal_line_center(img)

智慧交通day03-车道线检测实现07:车道曲率和中心点偏离距离计算+代码实现相关推荐

  1. 车道曲率和中心点偏离距离计算

    日萌社 人工智能AI:Keras PyTorch MXNet TensorFlow PaddlePaddle 深度学习实战(不定时更新) CNN:RCNN.SPPNet.Fast RCNN.Faste ...

  2. 智慧交通day03-车道线检测实现09:车道线检测代码汇总(Python3.8)

    import cv2 import numpy as np import matplotlib.pyplot as plt #遍历文件夹 import glob from moviepy.editor ...

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

    学习目标 了解直方图确定车道线位置的思想 我们根据前面检测出的车道线信息,利用直方图和滑动窗口的方法,精确定位车道线,并进行拟合. 1. 定位思想 下图是我们检测到的车道线结果: 沿x轴方向统计每一列 ...

  4. 智慧交通day03-车道线检测实现04:车道线提取原理+代码实现+效果图

    我们基于图像的梯度和颜色特征,定位车道线的位置. 在这里选用Sobel边缘提取算法,Sobel相比于Canny的优秀之处在于,它可以选择横向或纵向的边缘进行提取.从车道的拍摄图像可以看出,我们关心的正 ...

  5. 智慧交通day03-车道线检测实现05:透视变换+代码实现

    为了方便后续的直方图滑窗对车道线进行准确的定位,我们在这里利用透视变换将图像转换成俯视图,也可将俯视图恢复成原有的图像,代码如下: 计算透视变换所需的参数矩阵: def cal_perspective ...

  6. 智慧交通day03-车道线检测实现03:相机校正和图像校正的实现

    1.相机标定 根据张正友校正算法,利用棋盘格数据校正对车载相机进行校正,计算其内参矩阵,外参矩阵和畸变系数. 标定的流程是: 准备棋盘格数据,即用于标定的图片 对每一张图片提取角点信息 在棋盘上绘制提 ...

  7. 智慧交通day03-车道线检测实现02-1:相机校正

    1. 相机标定的意义 我们所处的世界是三维的,而照片是二维的,我们可以把相机认为是一个函数,输入量是一个场景,输出量是一幅灰度图.这个从三维到二维的过程的函数是不可逆的. 相机标定的一个目的是要找一个 ...

  8. 基于深度强化学习的车道线检测和定位(Deep reinforcement learning based lane detection and localization) 论文解读+代码复现

    之前读过这篇论文,导师说要复现,这里记录一下.废话不多说,再重读一下论文. 注:非一字一句翻译.个人理解,一定偏颇. 基于深度强化学习的车道检测和定位 官方源码下载:https://github.co ...

  9. 车道线检测在AR导航中的应用与挑战

    点击上方"3D视觉工坊",选择"星标" 干货第一时间送达 1. 导读 现代社会中,随着车辆的普及,人的活动范围在逐步扩大,单单依靠人类记忆引导行驶到达目的地已经 ...

最新文章

  1. R语言-处理异常值或报错的三个示例
  2. NTFRS事件ID:13568
  3. .net session 有效时间_Python中requests模拟登录的三种方式(携带cookie/session进行请求网站)...
  4. 【Python】Python语言学习:pip工具使用知识,模型保存pickle,PDF与docx相互转换处理...
  5. complete checkbox in Fiori
  6. C# 9 record 并非简单属性 POCO 的语法糖
  7. 微服务架构基础之Service Mesh
  8. paip.c++ qt 图片处理 检测损坏的图片
  9. 寻找阿姆斯特朗数(北理乐学)
  10. 【数学建模】第一讲-层次分析法
  11. Hebb和Delta学习规则
  12. matlab里方框一个叉号,Word输入×叉号和方框打叉方法
  13. 视频:《博物馆3》猴子闹罗宾哭 大表哥客串
  14. Python 爬影评,《悬崖之上》好看在哪里?
  15. 农民抗征地住帐篷夜间起火1死3伤
  16. 计算机网络vlan的作用,计算机网络 篇一:一根网线解决IPTV和路由器联网--基于VLAN的IPTV和宽带单线复用解决方案...
  17. FYI | Thomas Yeo的组在招博士和博后@新加坡国立
  18. psid mysql_DB2常用SQL的写法(持续更新中...)
  19. SSH连接越狱iPhone
  20. PMI-ACP考试如何办理紧急缓考?

热门文章

  1. vim文本编辑器的配置vimrc
  2. JSP request response session
  3. Python面试题总结(6)--数据类型(综合)
  4. loewe测试软件,实测Loewe三角包 最轻的小包最贴心的设计
  5. Django,Ajax,Vue实现文章评论功能
  6. java聊天软件课程设计_[计算机课程设计] JAVA课程设计-聊天室
  7. php_flag .htaccess,Apache服务器中.htaccess文件的实用配置示例集锦
  8. smtplib python教程_Python使用poplib模块和smtplib模块收发电子邮件的教程
  9. linux中的信号3——alarm、pause函数
  10. 交流电的有效值rms值_【电工基础知识:三、正弦交流电的产生】2正弦交流电的三要素...