yolov5目标检测交互界面
时间: 2025-03-23 10:13:23 浏览: 58
### YOLOv5目标检测与PyQt5交互界面实现
YOLOv5是一种高效的实时目标检测算法,而PyQt5则是Python中常用的跨平台GUI框架。通过将两者结合起来,可以构建一个具有用户友好的图形化界面的应用程序来执行目标检测任务。
以下是实现YOLOv5目标检测并与PyQt5交互界面结合的主要思路:
#### 1. 加载YOLOv5模型并初始化
在PyQt5应用程序启动时加载预训练的YOLOv5模型,并将其作为全局变量保存以便后续调用[^1]。
```python
import torch
from models.experimental import attempt_load
def load_model(weights_path='yolov5s.pt'):
model = attempt_load(weights_path, map_location=torch.device('cpu'))
return model
```
#### 2. 创建主窗口布局
利用PyQt5中的`QMainWindow`类定义主窗口结构,在其中放置按钮、标签以及图像显示区域等控件[^2]。
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtGui import QPixmap
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("YOLOv5 Object Detection")
layout = QVBoxLayout()
self.image_label = QLabel(self)
layout.addWidget(self.image_label)
button = QPushButton("Detect", self)
button.clicked.connect(self.perform_detection)
layout.addWidget(button)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
def perform_detection(self):
pass # Placeholder for detection logic
```
#### 3. 图像处理与结果显示
当点击“Detect”按钮时触发事件处理器函数,该函数负责读取当前选定图片文件路径,传递给YOLOv5进行推理运算得到边界框坐标及其他属性信息;最后再把这些标注好物体位置的新图绘制出来呈现在界面上。
```python
from PIL import ImageDraw
import cv2
from utils.general import non_max_suppression, scale_coords
from utils.datasets import letterbox
def detect_objects(model, img0):
stride = int(model.stride.max()) # Model stride
img_size = 640
# Padded resize
img = letterbox(img0, new_shape=img_size)[0]
# Convert to tensor and normalize
img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, HWC to CHW
img = np.ascontiguousarray(img).astype(np.float32) / 255.
img_tensor = torch.from_numpy(img).unsqueeze(0)
pred = model(img_tensor)[0]
det = non_max_suppression(pred)[0]
if det is not None and len(det):
det[:, :4] = scale_coords(img.shape[1:], det[:, :4], img0.shape).round()
draw = ImageDraw.Draw(Image.fromarray(cv2.cvtColor(img0, cv2.COLOR_BGR2RGB)))
for *xyxy, conf, cls in reversed(det):
label = f'{model.names[int(cls)]} {conf:.2f}'
draw.rectangle(xyxy, outline="red", width=3)
draw.text((int(xyxy[0]), int(xyxy[1]) - 10), label, fill="white")
result_img = cv2.cvtColor(np.array(draw._image), cv2.COLOR_RGB2BGR)
return result_img
else:
return img0
```
#### 4. 更新UI组件状态
完成上述操作之后需重新渲染更新后的画面至指定label上。
```python
def update_image_display(image_data):
height, width, channel = image_data.shape
bytesPerLine = 3 * width
qImg = QImage(image_data.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped()
pixmap = QPixmap.fromImage(qImg)
self.image_label.setPixmap(pixmap.scaledToWidth(800))
```
以上就是整个流程概述及其对应代码片段示范说明。
阅读全文
相关推荐


















