pyqt5 yolov5目标检测界面按键
时间: 2025-04-22 13:01:56 浏览: 29
### 创建包含YOLOv5目标检测功能的PyQt5界面
为了在PyQt5中集成YOLOv5目标检测并添加功能按钮,可以按照以下方法构建应用程序:
#### 安装依赖库
首先安装必要的Python包来支持PyQt5和YOLOv5的操作。
```bash
pip install pyqt5 pyqt5-tools torch torchvision torchaudio yolov5
```
这些命令会下载并安装PyQt5框架以及用于图像处理和支持YOLOv5模型运行所需的Torch系列库[^4]。
#### 构建基本窗口布局
定义一个继承自`QMainWindow`类的主要应用窗口,在其中设置菜单栏、状态栏和其他控件。这里将加入一个按钮用来触发图片的选择与检测过程。
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QLabel, QFileDialog
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("YOLOv5 Object Detection with PyQt5")
layout = QVBoxLayout()
# 添加文件选择按钮
btn_select_image = QPushButton('Select Image')
btn_select_image.clicked.connect(self.select_image)
layout.addWidget(btn_select_image)
# 显示所选图片路径标签
self.lbl_selected_file = QLabel('')
layout.addWidget(self.lbl_selected_file)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
此部分代码创建了一个具有单个按钮的应用程序窗口,点击该按钮可打开对话框让用户挑选待测验的照片文件[^1]。
#### 实现对象检测逻辑
接下来引入YOLOv5的具体操作流程到上述界面上。当用户选择了想要分析的图片之后,调用预训练好的YOLOv5模型来进行预测,并把结果显示出来。
```python
import cv2
import numpy as np
from PIL import Image
import torch
from pathlib import Path
def load_model():
model_path = 'path/to/yolov5s.pt' # 替换成实际保存的位置
device = "cuda" if torch.cuda.is_available() else "cpu"
model = torch.hub.load('ultralytics/yolov5', 'custom', path=model_path).to(device)
return model
model = load_model()
def detect_objects(image_path):
img = Image.open(str(Path(image_path)))
results = model(img.size)[0].xyxy.cpu().numpy()
detected_img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
for result in results:
label = int(result[-1])
confidence = float(result[4])
top_left_x = max(int(result[0]), 0)
top_left_y = max(int(result[1]), 0)
bottom_right_x = min(int(result[2]), detected_img.shape[1]-1)
bottom_right_y = min(int(result[3]), detected_img.shape[0]-1)
color = (0, 255, 0) # Green bounding box
cv2.rectangle(detected_img,
pt1=(top_left_x, top_left_y),
pt2=(bottom_right_x, bottom_right_y),
color=color,
thickness=2)
text = f'{label}: {confidence:.2f}'
font_face = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.7
font_thickness = 2
((text_width, text_height), _) = cv2.getTextSize(text=text,
fontFace=font_face,
fontScale=font_scale,
thickness=font_thickness)
rectangle_bgr = (0, 255, 0)
padding = 5
rect_top_left = (top_left_x - padding, top_left_y - text_height - padding * 2)
rect_bottom_right = (top_left_x + text_width + padding, top_left_y)
cv2.rectangle(detected_img,
rect_top_left,
rect_bottom_right,
rectangle_bgr,
-1)
cv2.putText(detected_img,
text,
org=(top_left_x, top_left_y - padding),
fontFace=font_face,
fontScale=font_scale,
color=(0, 0, 0),
thickness=font_thickness)
output_filename = str(Path(image_path).with_suffix('.result.jpg'))
cv2.imwrite(output_filename, detected_img)
return output_filename
```
这段函数实现了加载预先训练过的YOLOv5模型并对输入图片执行推理的任务;随后它会在原始照片上绘制边界框标注出识别出来的物体类别及其置信度得分。
#### 将两者结合起来
最后一步就是让之前提到的选择图片按钮能够真正启动这个检测过程并将结果反馈给用户查看。
```python
...
# 修改之前的select_image 方法如下所示:
def select_image(self):
file_dialog = QFileDialog()
image_path, _ = file_dialog.getOpenFileName(None, "Choose an image", "", "*.jpg *.png")
if not image_path:
return
self.lbl_selected_file.setText(f'Selected File: {image_path}')
try:
processed_image_path = detect_objects(image_path)
QMessageBox.information(
None,
"Detection Complete",
f"The detection has been completed.\nResults saved to:\n{processed_image_path}"
)
except Exception as e:
QMessageBox.critical(
None,
"Error Occurred During Processing!",
str(e)
)
...
```
通过这种方式就可以完成一个简易版的支持YOLOv5目标检测能力的PyQt5 GUI 应用了。
阅读全文
相关推荐














