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

相关文章

流媒体平台/视频监控/安防视频汇聚EasyCVR播放暂停后视频画面黑屏是什么原因?

视频智能分析/视频监控/安防监控综合管理系统EasyCVR视频汇聚融合平台,是TSINGSEE青犀视频垂直深耕音视频流媒体技术、AI智能技术领域的杰出成果。该平台以其强大的视频处理、汇聚与融合能力,在构建全栈视频监控系统中展现出了独特的优势。视频监控管理系统EasyCVR平台内置了强大的视频解码、转码、压缩等技术,能够处理多种视频流格式,并以多种格式(RTMP、RTSP、HTTP-FLV、WebS

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

如何用Docker运行Django项目

本章教程,介绍如何用Docker创建一个Django,并运行能够访问。 一、拉取镜像 这里我们使用python3.11版本的docker镜像 docker pull python:3.11 二、运行容器 这里我们将容器内部的8080端口,映射到宿主机的80端口上。 docker run -itd --name python311 -p

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

综合安防管理平台LntonAIServer视频监控汇聚抖动检测算法优势

LntonAIServer视频质量诊断功能中的抖动检测是一个专门针对视频稳定性进行分析的功能。抖动通常是指视频帧之间的不必要运动,这种运动可能是由于摄像机的移动、传输中的错误或编解码问题导致的。抖动检测对于确保视频内容的平滑性和观看体验至关重要。 优势 1. 提高图像质量 - 清晰度提升:减少抖动,提高图像的清晰度和细节表现力,使得监控画面更加真实可信。 - 细节增强:在低光条件下,抖

嵌入式QT开发:构建高效智能的嵌入式系统

摘要: 本文深入探讨了嵌入式 QT 相关的各个方面。从 QT 框架的基础架构和核心概念出发,详细阐述了其在嵌入式环境中的优势与特点。文中分析了嵌入式 QT 的开发环境搭建过程,包括交叉编译工具链的配置等关键步骤。进一步探讨了嵌入式 QT 的界面设计与开发,涵盖了从基本控件的使用到复杂界面布局的构建。同时也深入研究了信号与槽机制在嵌入式系统中的应用,以及嵌入式 QT 与硬件设备的交互,包括输入输出设

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

阿里开源语音识别SenseVoiceWindows环境部署

SenseVoice介绍 SenseVoice 专注于高精度多语言语音识别、情感辨识和音频事件检测多语言识别: 采用超过 40 万小时数据训练,支持超过 50 种语言,识别效果上优于 Whisper 模型。富文本识别:具备优秀的情感识别,能够在测试数据上达到和超过目前最佳情感识别模型的效果。支持声音事件检测能力,支持音乐、掌声、笑声、哭声、咳嗽、喷嚏等多种常见人机交互事件进行检测。高效推

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

在cscode中通过maven创建java项目

在cscode中创建java项目 可以通过博客完成maven的导入 建立maven项目 使用快捷键 Ctrl + Shift + P 建立一个 Maven 项目 1 Ctrl + Shift + P 打开输入框2 输入 "> java create"3 选择 maven4 选择 No Archetype5 输入 域名6 输入项目名称7 建立一个文件目录存放项目,文件名一般为项目名8 确定