YOLOv5 pyqt计数结果显示
时间: 2024-01-26 15:14:08 浏览: 117
基于yolov5和pyqt的可视化目标检测支持摄像头、视频和图像检测
5星 · 资源好评率100%
基于YOLOv5和pyqt的项目可以实现目标检测并显示计数结果。以下是一个简单的示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtGui import QPixmap
import cv2
import torch
from models.experimental import attempt_load
from utils.general import non_max_suppression, scale_coords
from utils.plots import plot_one_box
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("YOLOv5 Object Detection")
self.setGeometry(100, 100, 800, 600)
self.image_label = QLabel(self)
self.image_label.setGeometry(10, 10, 780, 580)
def detect_objects(self, image_path):
# 加载模型
model = attempt_load('yolov5s.pt', map_location=torch.device('cpu'))
stride = int(model.stride.max())
imgsz = 640
# 读取图像
img0 = cv2.imread(image_path) # BGR
img = img0.copy()
# 图像预处理
img = torch.from_numpy(img).to(torch.device('cpu')).unsqueeze(0).permute(0, 3, 1, 2).float() / 255.0
# 模型推理
pred = model(img)[0]
pred = non_max_suppression(pred, 0.4, 0.5)
# 绘制边界框和计数结果
for det in pred[0]:
if det is not None and len(det):
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img0.shape).round()
for *xyxy, conf, cls in reversed(det):
label = f'{model.names[int(cls)]} {conf:.2f}'
plot_one_box(xyxy, img0, label=label, color=(0, 255, 0), line_thickness=3)
# 显示图像
img_rgb = cv2.cvtColor(img0, cv2.COLOR_BGR2RGB)
h, w, ch = img_rgb.shape
bytes_per_line = ch * w
q_img = QImage(img_rgb.data, w, h, bytes_per_line, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(q_img)
self.image_label.setPixmap(pixmap)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.detect_objects('image.jpg') # 替换为你的图像路径
window.show()
sys.exit(app.exec_())
```
这段代码创建了一个基于pyqt的GUI窗口,可以显示目标检测的结果。你需要将YOLOv5的模型文件`yolov5s.pt`放在同一目录下,并将`image.jpg`替换为你要检测的图像路径。运行代码后,窗口将显示带有边界框和计数结果的图像。
阅读全文