PyQt5开发口罩检测GUI:从模型部署到界面设计的完整流程
PyQt5开发口罩检测GUI从模型部署到界面设计的完整流程1. 引言想自己动手做一个能实时检测口罩佩戴情况的桌面应用吗今天我来分享如何使用PyQt5和OpenCV从零开始构建一个完整的口罩检测GUI应用程序。无论你是Python初学者还是有一定经验的开发者这个教程都会带你一步步实现一个实用的计算机视觉应用。这个应用不仅能检测图片中的人物是否佩戴口罩还能实时处理摄像头视频流非常适合学习PyQt5界面开发和OpenCV图像处理的结合使用。整个过程不需要复杂的深度学习知识我们会使用现成的模型来快速实现功能。2. 环境准备与安装在开始编码之前我们需要先搭建开发环境。这里我推荐使用Anaconda来管理Python环境这样可以避免包依赖冲突。首先创建并激活一个新的conda环境conda create -n mask_detection python3.8 conda activate mask_detection然后安装所需的依赖包pip install pyqt5 opencv-python numpy matplotlib对于口罩检测模型我们可以使用OpenCV自带的DNN模块配合预训练的Caffe模型。下载模型文件# 下载模型配置文件和预训练权重 wget https://github.com/chandrikadeb7/Face-Mask-Detection/raw/master/face_detector/deploy.prototxt wget https://github.com/chandrikadeb7/Face-Mask-Detection/raw/master/face_detector/res10_300x300_ssd_iter_140000.caffemodel wget https://github.com/chandrikadeb7/Face-Mask-Detection/raw/master/mask_detector.model3. 口罩检测模型集成现在我们来编写口罩检测的核心逻辑。创建一个名为mask_detector.py的文件import cv2 import numpy as np class MaskDetector: def __init__(self): # 加载人脸检测模型 self.face_net cv2.dnn.readNetFromCaffe(deploy.prototxt, res10_300x300_ssd_iter_140000.caffemodel) # 加载口罩分类模型 self.mask_net cv2.dnn.readNetFromTensorflow(mask_detector.model) def detect_masks(self, image): # 获取图像尺寸 (h, w) image.shape[:2] # 构建blob并进行人脸检测 blob cv2.dnn.blobFromImage(image, 1.0, (300, 300), (104.0, 177.0, 123.0)) self.face_net.setInput(blob) detections self.face_net.forward() results [] # 处理检测结果 for i in range(detections.shape[2]): confidence detections[0, 0, i, 2] # 过滤低置信度的检测结果 if confidence 0.5: # 计算人脸边界框坐标 box detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) box.astype(int) # 确保边界框在图像范围内 startX, startY max(0, startX), max(0, startY) endX, endY min(w - 1, endX), min(h - 1, endY) # 提取人脸ROI并进行预处理 face image[startY:endY, startX:endX] if face.size 0: continue face cv2.cvtColor(face, cv2.COLOR_BGR2RGB) face cv2.resize(face, (224, 224)) face face.astype(float32) / 255.0 face np.expand_dims(face, axis0) # 进行口罩检测 self.mask_net.setInput(face) predictions self.mask_net.forward() # 解析预测结果 (mask, withoutMask) predictions[0] label Mask if mask withoutMask else No Mask color (0, 255, 0) if label Mask else (0, 0, 255) # 包含概率信息 label f{label}: {max(mask, withoutMask) * 100:.2f}% results.append({ box: (startX, startY, endX, endY), label: label, color: color, confidence: float(confidence) }) return results4. PyQt5界面设计接下来我们设计应用程序的图形界面。创建main_window.py文件import sys from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QFileDialog, QSlider, QSpinBox, QGroupBox) from PyQt5.QtCore import Qt, QTimer from PyQt5.QtGui import QImage, QPixmap import cv2 from mask_detector import MaskDetector class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle(口罩检测系统) self.setGeometry(100, 100, 1200, 800) # 初始化检测器 self.detector MaskDetector() self.cap None self.timer QTimer() self.init_ui() def init_ui(self): # 创建中央部件 central_widget QWidget() self.setCentralWidget(central_widget) # 主布局 main_layout QHBoxLayout(central_widget) # 左侧控制面板 control_panel QGroupBox(控制面板) control_layout QVBoxLayout() # 文件操作按钮 self.btn_open_image QPushButton(打开图片) self.btn_open_image.clicked.connect(self.open_image) self.btn_open_video QPushButton(打开视频) self.btn_open_video.clicked.connect(self.open_video) self.btn_start_camera QPushButton(启动摄像头) self.btn_start_camera.clicked.connect(self.start_camera) self.btn_stop QPushButton(停止) self.btn_stop.clicked.connect(self.stop) self.btn_stop.setEnabled(False) # 置信度阈值设置 confidence_layout QHBoxLayout() confidence_layout.addWidget(QLabel(置信度阈值:)) self.slider_confidence QSlider(Qt.Horizontal) self.slider_confidence.setRange(0, 100) self.slider_confidence.setValue(50) self.spin_confidence QSpinBox() self.spin_confidence.setRange(0, 100) self.spin_confidence.setValue(50) self.slider_confidence.valueChanged.connect(self.spin_confidence.setValue) self.spin_confidence.valueChanged.connect(self.slider_confidence.setValue) confidence_layout.addWidget(self.slider_confidence) confidence_layout.addWidget(self.spin_confidence) # 添加到控制面板 control_layout.addWidget(self.btn_open_image) control_layout.addWidget(self.btn_open_video) control_layout.addWidget(self.btn_start_camera) control_layout.addWidget(self.btn_stop) control_layout.addWidget(QLabel(检测设置:)) control_layout.addLayout(confidence_layout) control_layout.addStretch() control_panel.setLayout(control_layout) control_panel.setFixedWidth(200) # 右侧图像显示区域 image_panel QGroupBox(预览) image_layout QVBoxLayout() self.label_image QLabel() self.label_image.setAlignment(Qt.AlignCenter) self.label_image.setMinimumSize(640, 480) self.label_image.setStyleSheet(border: 1px solid gray;) self.label_status QLabel(就绪) self.label_status.setAlignment(Qt.AlignCenter) image_layout.addWidget(self.label_image) image_layout.addWidget(self.label_status) image_panel.setLayout(image_layout) # 添加到主布局 main_layout.addWidget(control_panel) main_layout.addWidget(image_panel) # 连接定时器 self.timer.timeout.connect(self.update_frame) def open_image(self): file_path, _ QFileDialog.getOpenFileName( self, 选择图片, , 图片文件 (*.png *.jpg *.jpeg *.bmp) ) if file_path: self.stop() image cv2.imread(file_path) self.process_image(image) def process_image(self, image): # 调整图像大小以适应显示 image self.resize_image(image, 800, 600) results self.detector.detect_masks(image) # 绘制检测结果 for result in results: startX, startY, endX, endY result[box] cv2.rectangle(image, (startX, startY), (endX, endY), result[color], 2) cv2.putText(image, result[label], (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, result[color], 2) # 显示图像 self.display_image(image) self.label_status.setText(f检测到 {len(results)} 个人脸) def open_video(self): file_path, _ QFileDialog.getOpenFileName( self, 选择视频, , 视频文件 (*.mp4 *.avi *.mov) ) if file_path: self.stop() self.cap cv2.VideoCapture(file_path) self.btn_stop.setEnabled(True) self.timer.start(30) # 30ms更新一帧 def start_camera(self): self.stop() self.cap cv2.VideoCapture(0) # 0表示默认摄像头 if self.cap.isOpened(): self.btn_stop.setEnabled(True) self.timer.start(30) self.label_status.setText(摄像头已启动) else: self.label_status.setText(无法打开摄像头) def stop(self): self.timer.stop() if self.cap: self.cap.release() self.cap None self.btn_stop.setEnabled(False) self.label_status.setText(已停止) def update_frame(self): if self.cap and self.cap.isOpened(): ret, frame self.cap.read() if ret: self.process_image(frame) def resize_image(self, image, max_width, max_height): h, w image.shape[:2] if w max_width or h max_height: scale min(max_width / w, max_height / h) new_w, new_h int(w * scale), int(h * scale) image cv2.resize(image, (new_w, new_h)) return image def display_image(self, image): # 转换颜色空间 BGR - RGB image cv2.cvtColor(image, cv2.COLOR_BGR2RGB) h, w, ch image.shape bytes_per_line ch * w # 创建QImage并显示 qt_image QImage(image.data, w, h, bytes_per_line, QImage.Format_RGB888) pixmap QPixmap.fromImage(qt_image) self.label_image.setPixmap(pixmap) def closeEvent(self, event): self.stop() event.accept() def main(): app QApplication(sys.argv) window MainWindow() window.show() sys.exit(app.exec_()) if __name__ __main__: main()5. 功能测试与优化现在让我们测试应用程序的基本功能并添加一些优化措施。首先创建一个简单的测试脚本test_app.pyimport sys import cv2 from main_window import MainWindow from PyQt5.QtWidgets import QApplication def test_with_sample_image(): 使用测试图片验证检测功能 from mask_detector import MaskDetector # 初始化检测器 detector MaskDetector() # 加载测试图片 image cv2.imread(test_image.jpg) # 请准备一张包含人脸的测试图片 if image is not None: results detector.detect_masks(image) print(f检测到 {len(results)} 个人脸) # 绘制检测结果 for result in results: startX, startY, endX, endY result[box] cv2.rectangle(image, (startX, startY), (endX, endY), result[color], 2) cv2.putText(image, result[label], (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, result[color], 2) # 保存结果 cv2.imwrite(result.jpg, image) print(结果已保存到 result.jpg) else: print(无法加载测试图片) if __name__ __main__: # 测试命令行功能 if len(sys.argv) 1 and sys.argv[1] test: test_with_sample_image() else: # 启动GUI应用 app QApplication(sys.argv) window MainWindow() window.show() sys.exit(app.exec_())为了提升性能我们可以添加多线程处理避免界面卡顿。创建一个工作线程类from PyQt5.QtCore import QThread, pyqtSignal class DetectionThread(QThread): finished pyqtSignal(object) # 发送检测结果 def __init__(self, detector, image): super().__init__() self.detector detector self.image image def run(self): try: results self.detector.detect_masks(self.image) self.finished.emit(results) except Exception as e: print(f检测错误: {e}) self.finished.emit([])然后在主窗口中集成多线程检测# 在MainWindow类的process_image方法中改用多线程 def process_image(self, image): # 保存原始图像用于显示 self.current_image image.copy() # 创建并启动检测线程 self.detection_thread DetectionThread(self.detector, image) self.detection_thread.finished.connect(self.on_detection_finished) self.detection_thread.start() # 先显示原始图像 display_image self.resize_image(self.current_image, 800, 600) self.display_image(display_image) def on_detection_finished(self, results): if hasattr(self, current_image): image self.current_image.copy() # 绘制检测结果 for result in results: startX, startY, endX, endY result[box] cv2.rectangle(image, (startX, startY), (endX, endY), result[color], 2) cv2.putText(image, result[label], (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, result[color], 2) # 显示带检测结果的图像 display_image self.resize_image(image, 800, 600) self.display_image(display_image) self.label_status.setText(f检测到 {len(results)} 个人脸)6. 打包与部署完成开发后我们可以使用PyInstaller将应用程序打包成可执行文件方便分发和使用。首先安装PyInstallerpip install pyinstaller创建打包配置文件build.spec# -*- mode: python ; coding: utf-8 -*- block_cipher None a Analysis([main_window.py], pathex[], binaries[], datas[(deploy.prototxt, .), (res10_300x300_ssd_iter_140000.caffemodel, .), (mask_detector.model, .)], hiddenimports[], hookspath[], hooksconfig{}, runtime_hooks[], excludes[], win_no_prefer_redirectsFalse, win_private_assembliesFalse, cipherblock_cipher, noarchiveFalse) pyz PYZ(a.pure, a.zipped_data, cipherblock_cipher) exe EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], nameMaskDetectionApp, debugFalse, bootloader_ignore_signalsFalse, stripFalse, upxTrue, upx_exclude[], runtime_tmpdirNone, consoleFalse, iconapp_icon.ico)然后运行打包命令pyinstaller build.spec打包完成后你可以在dist目录中找到生成的可执行文件。记得将模型文件放在同一目录下或者修改代码中的模型路径。7. 总结通过这个完整的教程我们实现了一个功能完善的口罩检测GUI应用程序。从环境搭建、模型集成、界面设计到最终打包部署每个步骤都涵盖了PyQt5开发的实际应用技巧。这个项目不仅展示了PyQt5和OpenCV的强大功能还演示了如何将机器学习模型集成到桌面应用程序中。你可以在此基础上进一步扩展功能比如添加数据库记录、生成检测报告、支持更多模型格式等。实际开发中可能会遇到性能优化、跨平台兼容性等问题这些都是很好的学习机会。最重要的是保持实践和探索的精神不断改进和完善自己的项目。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2446280.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!