Python道路车道线检测的实现


Posted in Python onJune 27, 2021

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

在本文中,我们将构建一个机器学习项目来实时检测车道线。我们将使用 OpenCV 库使用计算机视觉的概念来做到这一点。为了检测车道,我们必须检测车道两侧的白色标记。

Python道路车道线检测的实现

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

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

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

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

1.导入包

import matplotlib.pyplot as plt

import 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 = 255
        
    cv2.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 cache
    global first_frame
    slope_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 1
    slope_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 1
    
    x1_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_l
        y1_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 = cache
        next_frame = (1-α)*prev_frame+α*present_frame
             
    cv2.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_frame

    gray_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.shape
    lower_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/180

    line_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 代码:

Python道路车道线检测的实现

import tkinter as tk
from tkinter import *
import cv2
from PIL import Image, ImageTk
import os
import numpy as np


global 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_frame1
        last_frame1 = frame1.copy()
        pic = cv2.cvtColor(last_frame1, cv2.COLOR_BGR2RGB)     
        img = Image.fromarray(pic)
        imgtk = ImageTk.PhotoImage(image=img)
        lmain.imgtk = imgtk
        lmain.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_frame2
        last_frame2 = frame2.copy()
        pic2 = cv2.cvtColor(last_frame2, cv2.COLOR_BGR2RGB)
        img2 = Image.fromarray(pic2)
        img2tk = ImageTk.PhotoImage(image=img2)
        lmain2.img2tk = img2tk
        lmain2.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道路车道线检测的实现的文章就介绍到这了,更多相关Python 道路车道线检测内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
MySQL最常见的操作语句小结
May 07 Python
解析Mac OS下部署Pyhton的Django框架项目的过程
May 03 Python
python字符串的方法与操作大全
Jan 30 Python
Python编程argparse入门浅析
Feb 07 Python
解决Django后台ManyToManyField显示成Object的问题
Aug 09 Python
Python list与NumPy array 区分详解
Nov 06 Python
Python综合应用名片管理系统案例详解
Jan 03 Python
Python制作简易版小工具之计算天数的实现思路
Feb 13 Python
PyCharm+Miniconda3安装配置教程详解
Feb 16 Python
基于python实现银行管理系统
Apr 20 Python
Python基础之元编程知识总结
May 23 Python
基于tensorflow权重文件的解读
May 26 Python
浅析Django接口版本控制
浅析Python实现DFA算法
解析目标检测之IoU
pycharm代码删除恢复的方法
Python max函数中key的用法及原理解析
Python访问Redis的详细操作
一文搞懂python异常处理、模块与包
You might like
PHP explode()函数用法、切分字符串
2012/10/03 PHP
thinkPHP批量删除的实现方法分析
2016/11/09 PHP
jQuery Ajax文件上传(php)
2009/06/16 Javascript
jQuery的写法不同导致的兼容性问题的解决方法
2010/07/29 Javascript
jquery、js操作checkbox全选反选
2014/03/12 Javascript
使用jquery实现放大镜效果
2014/09/02 Javascript
node.js中的fs.unlink方法使用说明
2014/12/15 Javascript
javascript闭包(Closure)用法实例简析
2015/11/30 Javascript
全面解析Bootstrap图片轮播效果
2015/12/03 Javascript
JavaScript+html5 canvas制作的圆中圆效果实例
2016/01/27 Javascript
Js 获取、判断浏览器版本信息的简单方法
2016/08/08 Javascript
详解JS几种变量交换方式以及性能分析对比
2016/11/25 Javascript
滚动条的监听与内容随着滚动条动态加载的实现
2017/02/08 Javascript
jQuery插件HighCharts绘制2D圆环图效果示例【附demo源码下载】
2017/03/09 Javascript
Nodejs进阶之服务端字符编解码和乱码处理
2017/09/04 NodeJs
原生js实现随机点名功能
2019/11/05 Javascript
vue商城中商品“筛选器”功能的实现代码
2020/07/01 Javascript
在Python的web框架中配置app的教程
2015/04/30 Python
MySQL中表的复制以及大型数据表的备份教程
2015/11/25 Python
Python程序中设置HTTP代理
2016/11/06 Python
Python基于回溯法子集树模板实现图的遍历功能示例
2017/09/05 Python
python使用SMTP发送qq或sina邮件
2017/10/21 Python
Python Socket使用实例
2017/12/18 Python
Python+matplotlib实现计算两个信号的交叉谱密度实例
2018/01/08 Python
python调用百度语音REST API
2018/08/30 Python
符合语言习惯的 Python 优雅编程技巧【推荐】
2018/09/25 Python
Python实现对字典分别按键(key)和值(value)进行排序的方法分析
2018/12/19 Python
基于Python的PIL库学习详解
2019/05/10 Python
PyQt5笔记之弹出窗口大全
2019/06/20 Python
python 串行执行和并行执行实例
2020/04/30 Python
Python headers请求头如何实现快速添加
2020/11/03 Python
解决python3.x安装numpy成功但import出错的问题
2020/11/17 Python
阿迪达斯墨西哥官方网站:adidas墨西哥
2017/11/03 全球购物
澳大利亚最好的在线时尚精品店:Princess Polly
2018/01/03 全球购物
北京英语导游词
2015/02/12 职场文书
大学军训口号大全
2015/12/24 职场文书