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

import cv2
import numpy as np
import matplotlib.pyplot as plt
#遍历文件夹
import glob
from moviepy.editor import VideoFileClip"""参数设置"""
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_radius(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]# 把曲线中的点映射真实世界,再计算曲率# polyfit(x,y,n)。用多项式求过已知点的表达式,其中x为源数据点对应的横坐标,可为行 向 量、矩阵,# y为源数据点对应的纵坐标,可为行向量、矩阵,# n为你要拟合的阶数,一阶直线拟合,二阶抛物线拟合,并非阶次越高越好,看拟合情况而定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)/2# 计算中心点
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#计算车辆偏离中心点的距离
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 img#图片处理流程汇总 方便视频调用
def process_image(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)# 绘制安全区域result = fill_lane_poly(transform_img,left_fit,right_fit)#转换回原来的视角transform_img_inv = img_perspect_transform(result,M_inverse)# 曲率和偏离距离transform_img_inv = cal_radius(transform_img_inv,left_fit,right_fit)#偏离距离transform_img_inv = cal_center_departure(transform_img_inv,left_fit,right_fit)#附加到原图上transform_img_inv = cv2.addWeighted(undistort_img,1,transform_img_inv,0.5,0)#返回处理好的图像return transform_img_invif __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)# 视频处理clip1 = VideoFileClip("./project_video.mp4")white_clip = clip1.fl_image(process_image)white_clip.write_videofile("./output.mp4", audio=False)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/469614.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Django 模板实现(动态)图片/头像展示到页面

Django 模板实现&#xff08;动态&#xff09;图片作头像展示到页面 在网上搜了加载图片到前端的解决方法&#xff0c;大多都比较复杂&#xff0c;要引用PIL&#xff0c;下载Cropper插件&#xff08;可以用于裁图&#xff09;之类的&#xff0c;下面是一个简单易懂的方法实现&…

CSDN编程挑战(交换字符)

如果字符串str3能够由str1和str2中的字符按顺序交替形成&#xff0c;那么称str3为str1和str2的交替字符串。例如str1"abc"&#xff0c;str2"def"&#xff0c;那么"adbecf", "abcdef", "abdecf", "abcdef", "…

Unknown encoder ‘libx264‘的解决方法

1、问题描述&#xff1a; 运行程序的时候出现了这个错误,Unknown encoder ‘libx264’,和ffmpeg库有关. MoviePy error: FFMPEG encountered the following error while writing file run1output_video.mp4: b”Unrecognized option ‘preset’.\nError splitting the argumen…

Django之验证码的实现,简单快捷的方法

Django之验证码的实现&#xff0c;简单快捷的方法 实现验证码随网页变动即时刷新&#xff0c;实现有期限时间 请确保安装好pillow 直接show code&#xff1a; 0、路由urs.py from django.urls import path, re_path from . import views urlpatterns [re_path(r^test/$, vie…

5 Django系列之通过list_display展示多对多与外键内容在admin-web界面下

list_display展示多对多关系的内容 表结构关系 表一 class Server(models.Model):asset models.OneToOneField(Asset)created_by_choices ((auto,Auto),(manual,Manual),)created_by models.CharField(choicescreated_by_choices,max_length32,defaultauto) #auto: auto cre…

智慧交通day04-特定目标车辆追踪01:总览概述

项目介绍&#xff1a; 运动目标跟踪一直以来都是一项具有挑战性的工作, 也是研究的热点方向. 现阶段, 随着硬件设施 的不断完善和人工智能技术的快速发展, 运动目标跟踪技术越来越重要. 目标跟踪在现实生活中有很 多应用, 包括交通视频监控、运动员比赛分析、智能人机交互 、跟…

Python3之字典生成器结合lambda实现按key/value排序

Python3之字典生成器结合lambda实现按key/value排序 1、先介绍不常见的字典按value排序&#xff1a; dict1 {"g": 2, "f": 1, "a": 6} print(dict1.values()) d1 sorted(dict1.items(), keylambda d: d[1], reverseTrue) # 按字典values倒…

XCode8 App上传AppStore更新

1.在这个网站中https://itunesconnect.apple.com 点击“我的APP” 选取需要更新的app 2.点击加号 版本或平台&#xff0c;填写对应的更新版本 3.配置Xcode项目 1 》注意 上图的 套装ID 就是项目中的 Bundle Identity 必须要一模一样 并且不能修改 》配置相同的Bundle Identity…

智慧交通day04-特定目标车辆追踪02:Siamese网络+单样本学习

1.Siamese网络 Siamese network就是“连体的神经网络”&#xff0c;神经网络的“连体”是通过共享权值来实现的&#xff0c;如下图所示。共享权值意味着两边的网络权重矩阵一模一样&#xff0c;甚至可以是同一个网络。 如果左右两边不共享权值&#xff0c;而是两个不同的神经网…

学习网站(不断更新)

一个师兄给我的在线可编译的网站: http://www.fenby.com/user/me Linux最新内核代码: http://www.kernel.org/如果是拿来学习研究的 Linux早期版本内核代码(简单易学): http://www.oldlinux.org/index_cn.html LDD3例子这个家伙写得非常不错 http://blog.csdn.net/liuhaoy…

CSS如何实现两个a标签元素的文字一个靠左一个靠右,并且能点击分别不同的链接

CSS如何实现两个a标签元素的文字一个靠左一个靠右&#xff0c;并且能点击分别不同的链接 作为一个非专业前端&#xff0c;有时候开发又必须自己写一些简单的前端&#xff0c;在网上有时候不能及时查找到内容&#xff0c;只能自己尝试&#xff0c;如下是实现两个span中的a标签下…

智慧交通day04-特定目标车辆追踪03:siamese在目标跟踪中的应用-SiamFC(2016)

目标追踪任务是指在一个视频中给出第一帧图像的bbox的位置&#xff0c;在后续的帧中追踪该物体的任务。 目标追踪不同于目标检测的是&#xff1a; 1、需要给出首帧的标定框。 2、只需要给出标定框&#xff0c;后续的搜索范围往往在上一帧图像的附近。 孪生网络是使用深度学习…

word-break|overflow-wrap|word-wrap——CSS英文断句浅析

---恢复内容开始--- word-break|overflow-wrap|word-wrap——CSS英文断句浅析 一 问题引入 今天在再次学习 overflow 属性的时候&#xff0c;查看效果时&#xff0c;看到如下结果&#xff0c;内容在 div 中国换行了&#xff0c;可是两个 P 元素的内容并没有换行&#xff0c;搜索…

linux内核定时器编程

1.linux内核定时器基本结构和函数 1&#xff09;struct timer_list 一个struct timer_list对应了一个定时器。 #include <linux/timer.h> 以下列出常用的接口&#xff1a; struct timer_list{/*....*/unsigned long expires;//定时器服务函数开始执行时间void (*func…

django ModuleNotFoundError: No module named 'tinymce***'

django ModuleNotFoundError: No module named ‘***’ 1、检查对应的模块是否有安装&#xff0c;可以使用pip list查看 没有安装请执行安装 python -m pip install *** (--user)&#xff0c;某些电脑user没有权限需要加上括号中的 2、如果有安装 请检查python的django配置安…

度量时间差和jiffies计数器

HZ 1、内核通过定时器中断来跟踪时间流 2、时钟中断由系统定时硬件以周期性的间隔产生&#xff0c;这个间隔由内核根据HZ的值设定&#xff0c;HZ是一个与体系结构有关的常数&#xff0c;定义在<linux/param.h>或者该 文件包含的某个子平台相关的文件中。 jiffies 1、…

智慧交通day04-特定目标车辆追踪03:siamese在目标跟踪中的应用-SiamRPN(2017)

3.2 SiamRPN(2017) 3.2.1 网络结构 Siam-RPN提出了一种基于RPN的孪生网络结构&#xff0c;由孪生子网络和RPN网络组成&#xff0c;前者用来提取特征&#xff0c;后者用来产生候选区域。其中&#xff0c;RPN子网络由两个分支组成&#xff0c;一个是用来区分目标和背景的分类分…

点绛唇-王禹偁

diǎn jinɡ chn ɡǎn xnɡ 点 绛 唇 感 兴 wnɡ yǔ chēnɡ 王 禹 偁 yǔ hn yn chu &#xff0c; jiānɡ nn yī ji chēnɡ jiā l 。 雨 恨 云 愁 &#xff0c; 江 南 依 旧 称 佳 丽 。 shuǐ cūn y sh &#xff0c; y lǚ ɡū yān x…

ubuntu 18 Cannot find installed version of python-django or python3-django.

ubuntu系统下安装了django&#xff0c;但是启动django项目时报错 Cannot find installed version of python-django or python3-django. 原因&#xff1a; ubuntu大于14版本的应该安装python3-django 解决办法&#xff1a; apt-get install python3-django 如果提示你有几个…

智慧交通day04-特定目标车辆追踪03:siamese在目标跟踪中的应用-DaSiamRPN(2018)

DaSiamRPN网络的全称为Distractor-aware SiamRPN&#xff0c;是基于SiamRPN网络结构&#xff0c;提出更好的使用数据&#xff0c;针对跟踪过程的干扰物&#xff0c;利用更好的训练方式是跟踪更加的鲁棒。 DaSiamRPN认识到了现有的目标追踪数据集中存在的不平衡问题&#xff0c…