车道线检测是自动驾驶汽车以及一般计算机视觉的关键组件。这个概念用于描述自动驾驶汽车的路径并避免进入另一条车道的风险。

在本文中,我们将构建一个机器学习项目来实时检测车道线。

我们将使用 OpenCV 库使用计算机视觉的概念来做到这一点。为了检测车道,我们必须检测车道两侧的白色标记。

使用 Python 和 OpenCV 进行道路车道线检测

使用 Python 中的计算机视觉技术,我们将识别自动驾驶汽车必须行驶的道路车道线。这将是自动驾驶汽车的关键部分,因为自动驾驶汽车不应该越过它的车道,也不应该进入对面车道以避免事故。

帧掩码和霍夫线变换

要检测车道中的白色标记,首先,我们需要屏蔽帧的其余部分。我们使用帧屏蔽来做到这一点。该帧只不过是图像像素值的 NumPy 数组。为了掩盖帧中不必要的像素,我们只需将 NumPy 数组中的这些像素值更新为 0。

制作后我们需要检测车道线。用于检测此类数学形状的技术称为霍夫变换。霍夫变换可以检测矩形、圆形、三角形和直线等形状。

源代码下载

链接: https://pan.baidu.com/s/1alproBsGU-Q0RYpGsw9zBA

提取码: j52i

按照以下步骤在 Python 中进行车道线检测:

1. 导入包

import matplotlib.pyplot as pltimport numpy as np
import cv2
import os
import matplotlib.image as mpimg
from moviepy.editor import VideoFileClip
import math

2. 应用帧屏蔽并找到感兴趣的区域:

def interested_region(img, vertices):if len(img.shape) > 2: mask_color_ignore = (255,) * img.shape[2]else:mask_color_ignore = 255cv2.fillPoly(np.zeros_like(img), vertices, mask_color_ignore)return cv2.bitwise_and(img, np.zeros_like(img))

3. 霍夫变换空间中像素到线的转换:

def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)lines_drawn(line_img,lines)return line_img

4. 霍夫变换后在每一帧中创建两条线:


def lines_drawn(img, lines, color=[255, 0, 0], thickness=6):global cacheglobal first_frameslope_l, slope_r = [],[]lane_l,lane_r = [],[]α =0.2 for line in lines:for x1,y1,x2,y2 in line:slope = (y2-y1)/(x2-x1)if slope > 0.4:slope_r.append(slope)lane_r.append(line)elif slope < -0.4:slope_l.append(slope)lane_l.append(line)img.shape[0] = min(y1,y2,img.shape[0])if((len(lane_l) == 0) or (len(lane_r) == 0)):print ('no lane detected')return 1slope_mean_l = np.mean(slope_l,axis =0)slope_mean_r = np.mean(slope_r,axis =0)mean_l = np.mean(np.array(lane_l),axis=0)mean_r = np.mean(np.array(lane_r),axis=0)if ((slope_mean_r == 0) or (slope_mean_l == 0 )):print('dividing by zero')return 1x1_l = int((img.shape[0] - mean_l[0][1] - (slope_mean_l * mean_l[0][0]))/slope_mean_l) x2_l = int((img.shape[0] - mean_l[0][1] - (slope_mean_l * mean_l[0][0]))/slope_mean_l)   x1_r = int((img.shape[0] - mean_r[0][1] - (slope_mean_r * mean_r[0][0]))/slope_mean_r)x2_r = int((img.shape[0] - mean_r[0][1] - (slope_mean_r * mean_r[0][0]))/slope_mean_r)if x1_l > x1_r:x1_l = int((x1_l+x1_r)/2)x1_r = x1_ly1_l = int((slope_mean_l * x1_l ) + mean_l[0][1] - (slope_mean_l * mean_l[0][0]))y1_r = int((slope_mean_r * x1_r ) + mean_r[0][1] - (slope_mean_r * mean_r[0][0]))y2_l = int((slope_mean_l * x2_l ) + mean_l[0][1] - (slope_mean_l * mean_l[0][0]))y2_r = int((slope_mean_r * x2_r ) + mean_r[0][1] - (slope_mean_r * mean_r[0][0]))else:y1_l = img.shape[0]y2_l = img.shape[0]y1_r = img.shape[0]y2_r = img.shape[0]present_frame = np.array([x1_l,y1_l,x2_l,y2_l,x1_r,y1_r,x2_r,y2_r],dtype ="float32")if first_frame == 1:next_frame = present_frame        first_frame = 0        else :prev_frame = cachenext_frame = (1-α)*prev_frame+α*present_framecv2.line(img, (int(next_frame[0]), int(next_frame[1])), (int(next_frame[2]),int(next_frame[3])), color, thickness)cv2.line(img, (int(next_frame[4]), int(next_frame[5])), (int(next_frame[6]),int(next_frame[7])), color, thickness)cache = next_frame

5. 处理每一帧视频以检测车道:


def weighted_img(img, initial_img, α=0.8, β=1., λ=0.):return cv2.addWeighted(initial_img, α, img, β, λ)def process_image(image):global first_framegray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)img_hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)lower_yellow = np.array([20, 100, 100], dtype = "uint8")upper_yellow = np.array([30, 255, 255], dtype="uint8")mask_yellow = cv2.inRange(img_hsv, lower_yellow, upper_yellow)mask_white = cv2.inRange(gray_image, 200, 255)mask_yw = cv2.bitwise_or(mask_white, mask_yellow)mask_yw_image = cv2.bitwise_and(gray_image, mask_yw)gauss_gray= cv2.GaussianBlur(mask_yw_image, (5, 5), 0)canny_edges=cv2.Canny(gauss_gray, 50, 150)imshape = image.shapelower_left = [imshape[1]/9,imshape[0]]lower_right = [imshape[1]-imshape[1]/9,imshape[0]]top_left = [imshape[1]/2-imshape[1]/8,imshape[0]/2+imshape[0]/10]top_right = [imshape[1]/2+imshape[1]/8,imshape[0]/2+imshape[0]/10]vertices = [np.array([lower_left,top_left,top_right,lower_right],dtype=np.int32)]roi_image = interested_region(canny_edges, vertices)theta = np.pi/180line_image = hough_lines(roi_image, 4, theta, 30, 100, 180)result = weighted_img(line_image, image, α=0.8, β=1., λ=0.)return result

6. 将输入视频剪辑成帧并得到结果输出视频文件:

first_frame = 1
white_output = '__path_to_output_file__'
clip1 = VideoFileClip("__path_to_input_file__")
white_clip = clip1.fl_image(process_image)
white_clip.write_videofile(white_output, audio=False)

车道线检测项目 GUI 代码:


import tkinter as tk
from tkinter import *
import cv2
from PIL import Image, ImageTk
import os
import numpy as npglobal last_frame1
last_frame1 = np.zeros((480, 640, 3), dtype=np.uint8)
global last_frame2
last_frame2 = np.zeros((480, 640, 3), dtype=np.uint8)
global cap1
global cap2
cap1 = cv2.VideoCapture("path_to_input_test_video")
cap2 = cv2.VideoCapture("path_to_resultant_lane_detected_video")def show_vid():                                       if not cap1.isOpened():                             print("cant open the camera1")flag1, frame1 = cap1.read()frame1 = cv2.resize(frame1,(400,500))if flag1 is None:print ("Major error!")elif flag1:global last_frame1last_frame1 = frame1.copy()pic = cv2.cvtColor(last_frame1, cv2.COLOR_BGR2RGB)     img = Image.fromarray(pic)imgtk = ImageTk.PhotoImage(image=img)lmain.imgtk = imgtklmain.configure(image=imgtk)lmain.after(10, show_vid)def show_vid2():if not cap2.isOpened():                             print("cant open the camera2")flag2, frame2 = cap2.read()frame2 = cv2.resize(frame2,(400,500))if flag2 is None:print ("Major error2!")elif flag2:global last_frame2last_frame2 = frame2.copy()pic2 = cv2.cvtColor(last_frame2, cv2.COLOR_BGR2RGB)img2 = Image.fromarray(pic2)img2tk = ImageTk.PhotoImage(image=img2)lmain2.img2tk = img2tklmain2.configure(image=img2tk)lmain2.after(10, show_vid2)if __name__ == '__main__':root=tk.Tk()                                     lmain = tk.Label(master=root)lmain2 = tk.Label(master=root)lmain.pack(side = LEFT)lmain2.pack(side = RIGHT)root.title("Lane-line detection")            root.geometry("900x700+100+10") exitbutton = Button(root, text='Quit',fg="red",command=   root.destroy).pack(side = BOTTOM,)show_vid()show_vid2()root.mainloop()                                  cap.release()

Python实现道路车道线检测(附源码)相关推荐

  1. Python实现飞机大战-第二部分(附源码、素材、超详细教程)

    飞机大战第二部分 1.前言 2.飞机射击 2.1.添加子弹的相关设置 2.2.创建文件bullet.py 2.3.修改game_functions.py 2.4.修改mian.py 2.5.射击效果 ...

  2. 疯狂python讲义视频 百度云-疯狂Python讲义 PDF高清版附源码

    内容简介 本书全面,深入地介绍了Python编程的相关内容,大致可分为四个部分.*系统部分介绍了Python的基本语法结构,函数编程,类和对象,模块和包,异常处理等: 第二部分主要介绍Python常用 ...

  3. 熬夜整理出了70个清华大佬都在用的Python经典练手项目【附源码】

    我们都知道,不管学习那门语言最终都要做出实际的东西来,而对于编程而言,这个实际的东西当然就是项目啦,不用我多说大家都知道学编程语言做项目的重要性. 于是,小编熬了几个通宵,终于整理出了70个清华大佬都 ...

  4. python+openCV (入门级)车道线检测 学习笔记

    文章目录 前言 一.openCV安装 二.尝试使用cv2中库函数 1.读取图片 2.图片显示 3.延时/暂停 4.保存图片 5.清楚所有窗口 三.Canny边缘检测 1.高斯滤波 2.图片转换 3.边 ...

  5. Python初步实现车道线检测

    车道线检测是一个常见的问题,本文主要介绍如何简单有效的用python实现这个功能 主要思路 1 读取图像并选择感兴趣的区域ROI进行下一步处理 2 对ROI区域进行预处理包括灰度化,膨胀和腐蚀 3 对 ...

  6. 基于Pytorch的从零开始的目标检测 | 附源码

    01. 引言 目标检测是计算机视觉中一个非常流行的任务,在这个任务中,给定一个图像,你预测图像中物体的包围盒(通常是矩形的) ,并且识别物体的类型.在这个图像中可能有多个对象,而且现在有各种先进的技术 ...

  7. Python实战例子(32个附源码)

    Python是一种高级编程语言,具有简洁.清晰的语法,易于理解和使用,因此受到广泛的欢迎.尤其在数据科学.人工智能.机器学习.自然语言处理等领域,Python已成为最受欢迎的编程语言之一.Python ...

  8. Python基于YOLOv7的火灾检测系统(源码&教程)

    1.项目背景 为解决传统传感器在检测火灾的过程中受到环境.安装距离等因素影响导致适应性差的缺点,本文基于视觉传 感器,通过视觉目标检测技术对火灾进行检测,从而实现火灾的预警. 2.识别效果展示 3.视 ...

  9. Python人物头像动漫化[附源码]!!

    前文 哈哈哈乍一眼看到的第一眼的这张小姐姐图是不是很好看,缩小的是图片的原图,放大的是漫画的图片哦!!当你正在为你换什么头像烦恼时,看看这篇文章叭! 当你有对象的时候还可以用你的女朋友的动漫化的卡通形 ...

最新文章

  1. 关于Messenger实现进程间通信
  2. Junit内部解密之四: Junit单元测试最佳实践
  3. 使用Aspect和Spring Profile进行电子邮件过滤
  4. Ken Thompson爷爷的经典复制自身代码程序 - Python版本(只用两行!)
  5. 前端盒模型的概念和文本溢出解决办法
  6. 分布式文件系统的实现
  7. Github TOP100 Android开源,flutter与android混合开发
  8. 网络重置后,WiFi模块没了,网络适配器感叹号
  9. VR电竞游戏在英特尔®架构上的用户体验优化
  10. libnet、libnids、libpcap轻松搭建Linux网络入侵检测系统
  11. 16岁黑客发现Steam Store审核机制漏洞,可直接发布应用或游戏
  12. 计算机如何更改后缀文件名,如何批量修改文件后缀名(任何文件的扩展名)?
  13. 字符串的方法练习------Python篇
  14. linux中的sh脚本语法
  15. CCC3.0学习笔记_SCP03安全通道
  16. 数据分析——“鲍鱼的年龄”数据集
  17. 联通系统升级服务器地址,联通iptv升级服务器地址
  18. 保持冷静、继续前行——《白说》读后感
  19. 对冲基金表现大盘点(一):DE Shaw
  20. stem科学实验课关联

热门文章

  1. java常用集合浅层解析-面试必备
  2. 限流的4种策略--固定窗口、滑动窗口、漏桶、令牌桶
  3. win10任务栏透明_Win10任务栏美化工具
  4. 触摸查询系统服务器秒退怎么回事,触摸查询系统为我们生活带来什么作用
  5. java税务系统,基于java的税务管理系统
  6. Visual Studio 开发工具下载安装教程
  7. 华工计算机再取硕士有双证吗,华南理工大学首招“周末硕士生”毕业可获双证...
  8. gitblit 自定义URL复制按钮
  9. 带地理信息的课程签到需求实现(使用现有软件)
  10. LeakCanary 原理浅析