Advanced Lane Detection源码解读(一)

1. 源码解读

1.1 文件目录结构

源码文件下载自GitHub:advanced_lane_detection-master

  • advanced_lane_detection-master
    • camera_cal 存放用于相机标定棋盘格照片
      • *.jpg
    • output_images
      • *.png
    • test_images
      • *.jpg
    • calibrate_camera.p

      pickle文件,由calibrate_camera.py生成并存盘,包含键为mtx和dist的字典,存储了相机校正矩阵。

    • calibrate_camera.py
      def calibrate_camera():

      读取camera_cal/*.jpg照片,调用cv2.findChessboardCorners函数找到棋盘格的角点,再调用cv2.calibrateCamera的得到相机校正矩阵,并返回。

    • combined_thresh.py
      包含以下函数:
      • abs_sobel_thresh(img, orient='x', thresh_min=20, thresh_max=100)

        输入img为RGB图像,在该函数内部会被转为灰度图像。计算其在x或y方向的梯度。
        返回一个0-1的二值图像,选出了x或y梯度在最大、最小范围之间的像素点。

      • mag_thresh(img, sobel_kernel=3, mag_thresh=(30, 100))

        输入img为RGB图像,在该函数内部会被转为灰度图像。计算其梯度值。
        返回一个0-1的二值图像,选出了x或y梯度在最大、最小范围之间的像素点。

      • dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi/2))

        输入img为RGB图像,在该函数内部会被转为灰度图像。计算其梯度方向角。
        返回一个0-1的二值图像,选出了梯度方向角在最大、最小范围之间的像素点。

      • hls_thresh(img, thresh=(100, 255))

        输入img为RGB图像,在该函数内部会被转为HLS图像。提取S通道,选出S通道值在最大、最小范围之间的像素点。

      • combined_thresh(img)

        输入img为RGB图像,分别调用以上的x方向梯度、梯度值、梯度方向角、HLS的S阈值及同时满足这几个阈值范围的五个二值图像。
        return combined, abs_bin, mag_bin, dir_bin, hls_bin

    • gen_example_images.py
    1. 读取test_images文件夹下的jpg文件,调用img = cv2.undistort(img, mtx, dist, None, mtx)函数进行畸变校正,使用matplot进行显示,并将显示结果存为undistort_*.png文件。
    2. 调用img, abs_bin, mag_bin, dir_bin, hls_bin = combined_thresh(img)函数,生成相对应的二值图。使用matplot进行显示,并将显示结果存为binary_*.png文件。
    3. 调用img, binary_unwarped, m, m_inv = perspective_transform(img)生成鸟瞰视图,使用matplot进行显示,并将显示结果存为warped_*.png文件。
    4. 调用ret = line_fit(img)得到曲线拟合后的参数,调用viz2(img, ret, save_file=save_file)进行可视化,并将可视化的结果存为polyfit_*.png文件。
    5. 读取文件,调用undist = cv2.undistort(orig, mtx, dist, None, mtx)进行畸变校正。
    6. 调用left_curve, right_curve = calc_curve(left_lane_inds, right_lane_inds, nonzerox, nonzeroy),计算得到左右车道线曲线参数。
    7. 计算得到vehicle_offset *= xm_per_pix,车辆相对车道线的偏移值。
    8. 调用img = final_viz(undist, left_fit, right_fit, m_inv, left_curve, right_curve, vehicle_offset)将左右车道线和车道的偏移叠加到原图像,并进行显示。
    • Line.py
      • 定义类class Line():
        • 包含的属性:
          n: 移动平均的窗口大小
          detected:
          二次曲线的系数 x = A ∗ y 2 + B ∗ y + C x = A*y^2 + B*y + C x=Ay2+By+C
          二次曲线系数的平均值:A_avg,B_avg,C_avg
        • 包含的方法:
          get_fit(self):返回系数平均值
          def add_fit(self, fit_coeffs):增加一组A,B,C,返回A_avg,B_avg,C_avg
    • line_fit.py
      • 定义函数def line_fit(binary_warped)
        • 输入二值图像。
        • 返回一字典,包含左右车道线的参数。
          	ret = {}
          	ret['left_fit'] = left_fit # left_fit = np.polyfit(lefty, leftx, 2)
          	ret['right_fit'] = right_fit
          	ret['nonzerox'] = nonzerox
          	ret['nonzeroy'] = nonzeroy
          	ret['out_img'] = out_img
          	ret['left_lane_inds'] = left_lane_inds
          	ret['right_lane_inds'] = right_lane_inds
          
        • gen_example_images.py中被调用。img, binary_unwarped, m, m_inv = perspective_transform(img)ret = line_fit(img)
        • line_fit_video.py中被调用。ret = line_fit(binary_warped)
      • 定义函数def tune_fit(binary_warped, left_fit, right_fit)
      • 定义函数def viz1(binary_warped, ret, save_file=None)
      • 定义函数def viz2(binary_warped, ret, save_file=None)
      • 定义函数def calc_curve(left_lane_inds, right_lane_inds, nonzerox, nonzeroy)
        • gen_example_images.py中被调用,left_curve, right_curve = calc_curve(left_lane_inds, right_lane_inds, nonzerox, nonzeroy)
      • 定义函数def calc_vehicle_offset(undist, left_fit, right_fit)
      • 定义函数def final_viz(undist, left_fit, right_fit, m_inv, left_curve, right_curve, vehicle_offset)
    • line_fit_video.py 主程序运行入口
    • perspective_transform.py
      • 定义函数def perspective_transform(img):
      • return warped, unwarped, m, m_inv 返回透视变换后的图像、再反透视变换后的图像、透视变换和反透视变换矩阵。

1.2 源码解析

1.2.1 主程序line_fit_video.py

  • 运行方法。命令行输入python line_fit_video.py,程序会读取project_video.mp4,并且输出标注后的视频out.mp4。
  • 源码如下
  • 相关变量的读取、初始化
# Global variables (just to make the moviepy video annotation work)
with open('calibrate_camera.p', 'rb') as f:
	save_dict = pickle.load(f)
mtx = save_dict['mtx']
dist = save_dict['dist']
window_size = 5  # how many frames for line smoothing
left_line = Line(n=window_size)
right_line = Line(n=window_size)
detected = False  # did the fast line fit detect the lines?
left_curve, right_curve = 0., 0.  # radius of curvature for left and right lanes
left_lane_inds, right_lane_inds = None, None  # for calculating curvature
  • 定义单帧图像的注释函数
# MoviePy video annotation will call this function
def annotate_image(img_in):
	"""
	Annotate the input image with lane line markings
	Returns annotated image
	"""
	# 使用global函数声明全局变量(只是声明,而不是定义)
	global mtx, dist, left_line, right_line, detected
	global left_curve, right_curve, left_lane_inds, right_lane_inds

	# Undistort, threshold, perspective transform
	undist = cv2.undistort(img_in, mtx, dist, None, mtx)
	img, abs_bin, mag_bin, dir_bin, hls_bin = combined_thresh(undist)
	binary_warped, binary_unwarped, m, m_inv = perspective_transform(img)

	# Perform polynomial fit
	if not detected: # 如果不是检测目的,即为第一帧图像。运行彻底拟合。
		# Slow line fit
		ret = line_fit(binary_warped) # 将阈值分割和透视变换后的图像送入line_fit()函数,返回车道检测后的参数,这里是最重要的一个函数
		left_fit = ret['left_fit']
		right_fit = ret['right_fit']
		nonzerox = ret['nonzerox']
		nonzeroy = ret['nonzeroy']
		left_lane_inds = ret['left_lane_inds']
		right_lane_inds = ret['right_lane_inds']

		# Get moving average of line fit coefficients 
		# 使用移动平均法得到曲线拟合的参数
		left_fit = left_line.add_fit(left_fit)
		right_fit = right_line.add_fit(right_fit)

		# Calculate curvature
		left_curve, right_curve = calc_curve(left_lane_inds, right_lane_inds, nonzerox, nonzeroy)

		detected = True  # slow line fit always detects the line

	else:  # implies detected == True
		# Fast line fit
		left_fit = left_line.get_fit()
		right_fit = right_line.get_fit()
		ret = tune_fit(binary_warped, left_fit, right_fit) # 如果不是第一帧,则调用tune_fit()函数进行拟合
		left_fit = ret['left_fit']
		right_fit = ret['right_fit']
		nonzerox = ret['nonzerox']
		nonzeroy = ret['nonzeroy']
		left_lane_inds = ret['left_lane_inds']
		right_lane_inds = ret['right_lane_inds']

		# Only make updates if we detected lines in current frame
		if ret is not None:
			left_fit = ret['left_fit']
			right_fit = ret['right_fit']
			nonzerox = ret['nonzerox']
			nonzeroy = ret['nonzeroy']
			left_lane_inds = ret['left_lane_inds']
			right_lane_inds = ret['right_lane_inds']

			left_fit = left_line.add_fit(left_fit)
			right_fit = right_line.add_fit(right_fit)
			left_curve, right_curve = calc_curve(left_lane_inds, right_lane_inds, nonzerox, nonzeroy)
		else:
			detected = False

	vehicle_offset = calc_vehicle_offset(undist, left_fit, right_fit)

	# Perform final visualization on top of original undistorted image
	result = final_viz(undist, left_fit, right_fit, m_inv, left_curve, right_curve, vehicle_offset)

	return result
  • 定义视频标注函数
def annotate_video(input_file, output_file):
	""" Given input_file video, save annotated video to output_file """
	video = VideoFileClip(input_file)
	annotated_video = video.fl_image(annotate_image)
	annotated_video.write_videofile(output_file, audio=False)
  • 调用以上函数进行测试
if __name__ == '__main__':
	# Annotate the video
	annotate_video('project_video.mp4', 'out.mp4')

	# Show example annotated image on screen for sanity check
	img_file = 'test_images/test2.jpg'
	img = mpimg.imread(img_file)
	result = annotate_image(img)
	result = annotate_image(img)
	result = annotate_image(img)
	plt.imshow(result)
	plt.show()
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值