OpenCV+ moviepy + tkinter 视频车道线智能识别项目源码

2024-02-02 23:04

本文主要是介绍OpenCV+ moviepy + tkinter 视频车道线智能识别项目源码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

项目完整源代码,使用 OpenCV 的Hough 直线检测算法,提取出道路车道线并绘制出来。通过tkinter 提供GUI界面展示效果。
在这里插入图片描述

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. 用掩码获取ROI区域

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、Hough变换空间, 转换像素到直线

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、在Hough变换后,每帧增加两条线

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)# gause blue gauss_gray= cv2.GaussianBlur(mask_yw_image, (5, 5), 0)# detect edgecanny_edges=cv2.Canny(gauss_gray, 50, 150,apertureSize=3)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、用moviepy的videofileClip 读出视频,调用process_image方法处理后保存至文件

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

7、用tkinter编写车道线检测项目的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
cap_input = cv2.VideoCapture("path_to_input_test_video")
cap_drawlane = cv2.VideoCapture("path_to_resultant_lane_detected_video")def show_input_video():                                       if not cap_input.isOpened():                             print("无法打开原始视频")flag1, frame1 = cap_input.read()frame1 = cv2.resize(frame1,(400,500))if flag1 is None:print ("原视频读帧错误")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_input_video)def show_drawlane_video():if not cap_drawlane.isOpened():                             print("无法打开车道线视频")flag2, frame2 = cap_drawlane.read()frame2 = cv2.resize(frame2,(400,500))if flag2 is None:print ("车道线视频读帧错误")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_drawlane_video)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("车道线检测")            root.geometry("900x700+100+10") exitbutton = Button(root, text='退出',fg="red",command=   root.destroy).pack(side = BOTTOM,)show_input_video()show_drawlane_video()root.mainloop()                                  cap.release()

这篇关于OpenCV+ moviepy + tkinter 视频车道线智能识别项目源码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


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

相关文章

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

《SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能》:本文主要介绍SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的... 目录原理解析1. mysql主从复制(Master-Slave Replication)2. 读写分离3.

基于Python和MoviePy实现照片管理和视频合成工具

《基于Python和MoviePy实现照片管理和视频合成工具》在这篇博客中,我们将详细剖析一个基于Python的图形界面应用程序,该程序使用wxPython构建用户界面,并结合MoviePy、Pill... 目录引言项目概述代码结构分析1. 导入和依赖2. 主类:PhotoManager初始化方法:__in

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++

用js控制视频播放进度基本示例代码

《用js控制视频播放进度基本示例代码》写前端的时候,很多的时候是需要支持要网页视频播放的功能,下面这篇文章主要给大家介绍了关于用js控制视频播放进度的相关资料,文中通过代码介绍的非常详细,需要的朋友可... 目录前言html部分:JavaScript部分:注意:总结前言在javascript中控制视频播放

Python基于wxPython和FFmpeg开发一个视频标签工具

《Python基于wxPython和FFmpeg开发一个视频标签工具》在当今数字媒体时代,视频内容的管理和标记变得越来越重要,无论是研究人员需要对实验视频进行时间点标记,还是个人用户希望对家庭视频进行... 目录引言1. 应用概述2. 技术栈分析2.1 核心库和模块2.2 wxpython作为GUI选择的优

opencv图像处理之指纹验证的实现

《opencv图像处理之指纹验证的实现》本文主要介绍了opencv图像处理之指纹验证的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录一、简介二、具体案例实现1. 图像显示函数2. 指纹验证函数3. 主函数4、运行结果三、总结一、

Python实现无痛修改第三方库源码的方法详解

《Python实现无痛修改第三方库源码的方法详解》很多时候,我们下载的第三方库是不会有需求不满足的情况,但也有极少的情况,第三方库没有兼顾到需求,本文将介绍几个修改源码的操作,大家可以根据需求进行选择... 目录需求不符合模拟示例 1. 修改源文件2. 继承修改3. 猴子补丁4. 追踪局部变量需求不符合很

一文教你如何将maven项目转成web项目

《一文教你如何将maven项目转成web项目》在软件开发过程中,有时我们需要将一个普通的Maven项目转换为Web项目,以便能够部署到Web容器中运行,本文将详细介绍如何通过简单的步骤完成这一转换过程... 目录准备工作步骤一:修改​​pom.XML​​1.1 添加​​packaging​​标签1.2 添加

tomcat多实例部署的项目实践

《tomcat多实例部署的项目实践》Tomcat多实例是指在一台设备上运行多个Tomcat服务,这些Tomcat相互独立,本文主要介绍了tomcat多实例部署的项目实践,具有一定的参考价值,感兴趣的可... 目录1.创建项目目录,测试文China编程件2js.创建实例的安装目录3.准备实例的配置文件4.编辑实例的

python+opencv处理颜色之将目标颜色转换实例代码

《python+opencv处理颜色之将目标颜色转换实例代码》OpenCV是一个的跨平台计算机视觉库,可以运行在Linux、Windows和MacOS操作系统上,:本文主要介绍python+ope... 目录下面是代码+ 效果 + 解释转HSV: 关于颜色总是要转HSV的掩膜再标注总结 目标:将红色的部分滤