1.教程:YOLO数据处理 界面程序 - 白月黑羽 (byhy.net)
YOLO+PyQt 图形界面程序_哔哩哔哩_bilibili
与上文相似,只是对pyside2中部分代码进行修改,适应PyQt6标准,详情可见白月黑羽教程
导包
from PyQt6 import QtWidgets, QtCore, QtGui
import cv2, os, time
from threading import Thread, Lock
import sys
os.environ['YOLO_VERBOSE'] = 'False'
from ultralytics import YOLO
定义主窗口实类
构造初始方法
def __init__(self):
super().__init__()
self.setupUI()# 定义UI界面,
self.camBtn.clicked.connect(self.startCamera)
self.stopBtn.clicked.connect(self.stop)# 链接按钮与功能
self.timer_camera = QtCore.QTimer()
self.timer_camera.timeout.connect(self.show_camera)# 摄像头定时器初始化
self.model = YOLO('yolov8n.pt')# 此处加载yolo模型,如果感觉太大可以用s.tiny
self.frameToAnalyze = [] #用于存储从摄像头捕获到的待处理图像帧
self.frameLock = Lock() # 用于线程安全访问帧列表
self.stopProcessing = False # 用于控制分析线程的运行状态
self.analysis_thread = Thread(target=self.frameAnalyzeThreadFunc, daemon=True)
self.analysis_thread.start()
构建UI的函数不再赘述,和PyQt构建UI界面并调取摄像头一文中一致
startCamera和stop同上
def frameAnalyzeThreadFunc(self):# 用于后台处理从摄像头捕获的图像帧
while not self.stopProcessing:
with self.frameLock:
if not self.frameToAnalyze:
time.sleep(0.01)
continue
frame = self.frameToAnalyze.pop(0)# 先进先出处理帧
try:
results = self.model(frame)[0]
img = results.plot(line_width=1)
qImage = QtGui.QImage(img.data, img.shape[1], img.shape[0], QtGui.QImage.Format.Format_RGB888)
self.label_treated.setPixmap(QtGui.QPixmap.fromImage(qImage))
except Exception as e:
print(f"Error processing frame: {e}")
time.sleep(0.1)# 此处也可以不休眠,要保证你的设备有对应的推理速度
def stop(self):
self.timer_camera.stop()
if hasattr(self, 'cap'):
self.cap.release()
self.label_ori_video.clear()
self.label_treated.clear()
with self.frameLock:
self.frameToAnalyze.clear()
def closeEvent(self, event):
self.stopProcessing = True
if self.analysis_thread.is_alive():
self.analysis_thread.join()
self.stop()
event.accept()