You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将YOLO model.predict()结果转为QPixmap在PyQt6 Label中显示?

YOLO预测结果转PyQt6 Pixmap显示问题解决

我正在做图像识别开发,用PyQt6搭建GUI,使用YOLO模型做检测。原本的代码可以通过model.predict()将结果保存到本地,但我想直接把带检测框的预测结果转成Pixmap显示在Label里。尝试了以下代码后无报错,但Label里没有内容:

FileModelPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "WorkFile\\best.pt")
model = YOLO(FileModelPath)
img = Image.open(Ui_MainWindow.FILEPATH)
predictions = model.predict(img, show = True, classes=[0,1], project="C:/foto", hide_labels = False, hide_conf = False, conf=float(0.8),save = False, line_thickness=1)
predictions = np.array(predictions)
image = QImage(predictions.data, predictions.shape[1], predictions.shape[0], QImage.Format.Format_RGB888)
self.labelFoto.setPixmap(QPixmap.fromImage(image))

问题原因与解决方案

问题出在对YOLO predict()返回值的处理上:predict()返回的是Results对象的列表(单张图预测时列表长度为1),直接转成numpy数组无法得到正确的图像数据。正确的做法是从Results对象中提取带标注的图像。

修正后的完整代码

import os
from PIL import Image
from ultralytics import YOLO
from PyQt6.QtGui import QImage, QPixmap

# 加载模型与目标图像
FileModelPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "WorkFile\\best.pt")
model = YOLO(FileModelPath)
img = Image.open(Ui_MainWindow.FILEPATH)

# 执行预测(可去掉show=True,避免弹出YOLO自带的显示窗口)
predictions = model.predict(
    img, 
    classes=[0,1], 
    conf=float(0.8), 
    save=False, 
    line_thickness=1,
    hide_labels=False, 
    hide_conf=False
)

# 提取带检测标注的图像
result = predictions[0]  # 取单张图的预测结果
annotated_img = result.plot()  # 生成叠加检测框/标签的PIL Image

# 将PIL Image转换为QImage
img_rgb = annotated_img.convert("RGB")
width, height = img_rgb.size
bytes_per_line = 3 * width
q_image = QImage(
    img_rgb.tobytes(), 
    width, 
    height, 
    bytes_per_line, 
    QImage.Format.Format_RGB888
)

# 转为QPixmap并设置到Label
pixmap = QPixmap.fromImage(q_image)
self.labelFoto.setPixmap(pixmap)
# 可选:让Label自适应图像大小
self.labelFoto.setScaledContents(True)

关键说明

  • result.plot():YOLO Results对象自带的方法,自动生成叠加了检测框、类别标签、置信度的PIL图像,无需手动编写绘制逻辑
  • PIL转QImage时,需确保图像为RGB格式,并正确计算每行字节数,避免图像变形或显示异常
  • 移除predict()中的show=True后,可直接在PyQt的Label中展示结果,无需额外弹出窗口

内容的提问来源于stack exchange,提问作者Aleksandr Eremin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:05:27