基于python和pyside6写一个基础的GUI界面代码,需要点击按钮可以调用摄像头,基于YOLOv5的实时监测结果展示在界面上
时间: 2024-10-04 20:01:40 浏览: 32
基于YOLOv7+Pyside6的GUI可视化界面检测图像和视频源码+说明文档.zip
在Python中,我们可以使用PySide6库创建GUI,并结合OpenCV(用于处理摄像头和图像识别)以及YOLOv5模型来进行实时监控。下面是一个简单的例子,展示了如何创建一个基础的GUI,有一个按钮用于启动摄像头,然后在QLabel上显示YOLOv5检测到的对象。
```python
import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout
from PySide6.QtGui import QImage, QPixmap
import cv2
from yolov5s import YOLO
class VideoWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("YOLOv5 Real-time Detection")
self.resize(800, 600)
self.button = QPushButton("Start Camera", self)
self.button.clicked.connect(self.start_camera)
self.label = QLabel(self)
self.label.setFixedWidth(640)
self.label.setFixedHeight(480)
self.label.setAlignment(Qt.AlignCenter)
layout = QVBoxLayout()
layout.addWidget(self.button)
layout.addWidget(self.label)
self.setLayout(layout)
def start_camera(self):
cam = cv2.VideoCapture(0) # 使用内置摄像头
if not cam.isOpened():
print("Could not open camera.")
return
while True:
ret, frame = cam.read()
if not ret:
break
img = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
pixmap = QPixmap.fromImage(img)
self.label.setPixmap(pixmap)
# 使用YOLOv5模型进行实时检测
img_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = yolo.detect_image(img_rgb)
for result in results:
label, bbox, score = result
x, y, w, h = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.putText(frame, f'{label}: {score:.2f}', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
self.label.setPixmap(QPixmap.fromImage(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)))
cam.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
app = QApplication(sys.argv)
yolo = YOLO() # 初始化YOLOv5实例
window = VideoWindow()
window.show()
sys.exit(app.exec_())
```
在这个示例中,`start_camera`函数会打开摄像头,实时捕获帧并利用YOLOv5进行对象检测。检测结果显示在`QLabel`控件中。请注意,你需要安装`yolov5s`库才能运行此代码,你可以通过pip安装:
```sh
pip install git+https://github.com/ultralytics/yolov5.git
```
阅读全文