基于YOLOv5的疲劳驾驶检测系统,疲劳驾驶数据集

📅 2026/7/9 12:34:44
基于YOLOv5的疲劳驾驶检测系统,疲劳驾驶数据集
基于YOLOv5的疲劳驾驶检测系统如何配置环境如何构建数据集模型项目介绍软件PycharmAnaconda环境python3.8 tensorflow2.9.1 torch1.8.0 PyQt5文件1.完整程序文件.py等2.UI界面源文件、图标.ui、.qrc、.py等3.测试图片、视频文件.jpeg、.mp4、.avi等4.模型参数、配置文件.weights、.cfg等功能基于YOLOv5的疲劳驾驶检测系统使用深度学习技术检测常见驾驶图片、视频和实时视频中的疲劳行为识别其闭眼、打哈欠等结果并记录和保存。在界面中可以选择各种图片、视频进行检测识别;可对图像中存在的多目标进行识别分类检测速度快、识别精度。1.选择图片识别2.视频识别3. 摄像头实时检测声明以下代码仅供参考基于YOLOv5构建一个疲劳驾驶检测系统。以下是详细的步骤和完整的代码示例。假设你已经有一个训练好的YOLOv5模型并且环境已经配置好。步骤概述安装依赖准备数据集加载预训练模型实现疲劳驾驶检测逻辑构建GUI应用程序运行应用程序1. 安装依赖确保你已经安装了所有必要的库包括PyTorch、YOLOv5和其他相关库。conda create-nfatigue_detectionpython3.8conda activate fatigue_detection pipinstalltorch1.8.0torchvision0.9.0 PyQt5 opencv-python-headless matplotlib pillow2. 准备数据集假设你的数据集已经转换为YOLOv5格式并且目录结构如下dataset/ ├── images/ │ ├── train/ │ │ ├── image1.jpg │ │ └── ... │ ├── val/ │ │ ├── image1.jpg │ │ └── ... │ └── test/ │ ├── image1.jpg │ └── ... └── labels/ ├── train/ │ ├── image1.txt │ └── ... ├── val/ │ ├── image1.txt │ └── ... └── test/ ├── image1.txt └── ...每个图像文件对应一个标签文件标签文件包含对象的类别ID和边界框坐标x_center, y_center, width, height归一化到[0, 1]范围。3. 加载预训练模型假设你已经有了一个训练好的YOLOv5模型权重文件best.pt。4. 实现疲劳驾驶检测逻辑我们将使用YOLOv5进行目标检测并识别闭眼和打哈欠等行为。fatigue_detection_logic.pyimportcv2importtorchfrompathlibimportPathfrommodels.experimentalimportattempt_loadfromutils.generalimportnon_max_suppression,scale_coordsfromutils.plotsimportplot_one_boxfromutils.torch_utilsimportselect_deviceclassFatigueDetection:def__init__(self,weightsbest.pt):self.deviceselect_device()self.modelattempt_load(weights,map_locationself.device)self.strideint(self.model.stride.max())# model strideself.namesself.model.module.namesifhasattr(self.model,module)elseself.model.names# get class namesdefdetect_image(self,img):img0img.copy()imgself.preprocess(img)withtorch.no_grad():predself.model(img)[0]prednon_max_suppression(pred,0.4,0.5,classesNone,agnosticFalse)fori,detinenumerate(pred):# detections per imagegntorch.tensor(img0.shape)[[1,0,1,0]]# normalization gain whwhiflen(det):det[:,:4]scale_coords(img.shape[2:],det[:,:4],img0.shape).round()for*xyxy,conf,clsinreversed(det):labelf{self.names[int(cls)]}{conf:.2f}plot_one_box(xyxy,img0,labellabel,color(0,255,0),line_thickness3)returnimg0defpreprocess(self,img):imgcv2.cvtColor(img,cv2.COLOR_BGR2RGB)imgcv2.resize(img,(640,640))imgimg/255.0imgnp.transpose(img,(2,0,1))[::-1]imgnp.ascontiguousarray(img)imgtorch.from_numpy(img).to(self.device)imgimg.float()img/255.0ifimg.ndimension()3:imgimg.unsqueeze(0)returnimg5. 构建GUI应用程序使用PyQt5构建一个简单的GUI应用程序允许用户上传图像、视频并进行实时摄像头检测。GUI 应用程序[titleFatigue Driving Detection GUI using YOLOv5]importsysimportcv2importnumpyasnpfromPyQt5.QtWidgetsimportQApplication,QMainWindow,QLabel,QPushButton,QVBoxLayout,QWidget,QFileDialog,QMessageBox,QComboBoxfromPyQt5.QtGuiimportQPixmap,QImagefromfatigue_detection_logicimportFatigueDetectionclassFatigueDetectionApp(QMainWindow):def__init__(self):super().__init__()self.setWindowTitle(Fatigue Driving Detection Using YOLOv5)self.setGeometry(100,100,800,600)self.original_image_labelQLabel(self)self.detected_image_labelQLabel(self)self.upload_buttonQPushButton(Upload Image,self)self.upload_button.clicked.connect(self.upload_image)self.video_buttonQPushButton(Upload Video,self)self.video_button.clicked.connect(self.upload_video)self.camera_buttonQPushButton(Camera Detection,self)self.camera_button.clicked.connect(self.start_camera)self.stop_buttonQPushButton(Stop Camera,self)self.stop_button.clicked.connect(self.stop_camera)self.stop_button.setEnabled(False)self.method_comboQComboBox(self)self.method_combo.addItems([Image,Video,Camera])self.method_combo.currentIndexChanged.connect(self.update_method)layoutQVBoxLayout()layout.addWidget(self.original_image_label)layout.addWidget(self.detected_image_label)layout.addWidget(self.upload_button)layout.addWidget(self.video_button)layout.addWidget(self.camera_button)layout.addWidget(self.stop_button)layout.addWidget(self.method_combo)containerQWidget()container.setLayout(layout)self.setCentralWidget(container)self.fatigue_detectorFatigueDetection(weightsbest.pt)self.detection_methodImageself.capNonedefupdate_method(self,index):self.detection_method[Image,Video,Camera][index]defupload_image(self):optionsQFileDialog.Options()file_name,_QFileDialog.getOpenFileName(self,QFileDialog.getOpenFileName(),,Images (*.png *.xpm *.jpg);;All Files (*),optionsoptions)iffile_name:imagecv2.imread(file_name)detected_imageself.fatigue_detector.detect_image(image)original_pixmapQPixmap(file_name)detected_pixmapQPixmap.fromImage(self.convert_to_qimage(detected_image))self.original_image_label.setPixmap(original_pixmap.scaled(350,350))self.detected_image_label.setPixmap(detected_pixmap.scaled(350,350))defupload_video(self):optionsQFileDialog.Options()file_name,_QFileDialog.getOpenFileName(self,QFileDialog.getOpenFileName(),,Videos (*.mp4 *.avi);;All Files (*),optionsoptions)iffile_name:capcv2.VideoCapture(file_name)whilecap.isOpened():ret,framecap.read()ifnotret:breakdetected_frameself.fatigue_detector.detect_image(frame)cv2.imshow(Detected Video,detected_frame)ifcv2.waitKey(25)0xFFord(q):breakcap.release()cv2.destroyAllWindows()defstart_camera(self):self.capcv2.VideoCapture(0)ifnotself.cap.isOpened():QMessageBox.warning(self,Warning,Cannot open camera.)returnself.timerQTimer(self)self.timer.timeout.connect(self.update_frame)self.timer.start(25)self.stop_button.setEnabled(True)defstop_camera(self):ifself.capisnotNone:self.cap.release()self.timer.stop()self.stop_button.setEnabled(False)defupdate_frame(self):ret,frameself.cap.read()ifret:detected_frameself.fatigue_detector.detect_image(frame)detected_pixmapQPixmap.fromImage(self.convert_to_qimage(detected_frame))self.detected_image_label.setPixmap(detected_pixmap.scaled(350,350))defconvert_to_qimage(self,cv_image):rgb_imagecv2.cvtColor(cv_image,cv2.COLOR_BGR2RGB)h,w,chrgb_image.shape bytes_per_linech*w qimageQImage(rgb_image.data,w,h,bytes_per_line,QImage.Format_RGB888)returnqimageif__name____main__:appQApplication(sys.argv)windowFatigueDetectionApp()window.show()sys.exit(app.exec_())解释安装依赖确保安装了所有必要的库。准备数据集按照YOLOv5的要求组织数据集。加载预训练模型加载训练好的YOLOv5模型权重文件best.pt。实现疲劳驾驶检测逻辑使用YOLOv5进行目标检测并识别闭眼和打哈欠等行为。构建GUI应用程序创建主窗口和布局。添加按钮用于上传图像、视频和启动/停止摄像头检测。实现图像上传功能。实现视频上传功能。实现摄像头实时检测功能。运行应用程序保存上述脚本到相应的Python文件中然后运行训练和评估脚本conda activate fatigue_detection python fatigue_detection_gui.py