开始使用

使用 Ultralytics YOLO 进行模型预测

Ultralytics YOLO ecosystem and integrations

简介#

在机器学习和计算机视觉中,使用训练好的模型理解视觉数据的过程称为推理或预测。Ultralytics YOLO26 的 predict 模式可在多种数据源上执行快速的实时推理。

查看尚未发布的 YOLO27 预览版,了解计划中的推理示例。



观看:使用 Python 中的 Ultralytics YOLO26 提取边界框、掩码、关键点、OBB、深度等 🚀

实际应用#

制造业体育安全
车辆备件检测足球运动员检测人员跌倒检测

为什么使用 Ultralytics YOLO 进行推理?#

使用 YOLO26 predict 模式的主要理由:

  • 多功能性:可对图像、视频和实时流执行推理。
  • 高性能:专为实时高速处理而设计,同时不牺牲准确率。
  • 易于使用:直观的 Python 和 CLI 接口,可快速部署和测试。
  • 高度可定制:提供各种设置和参数,可根据你的具体需求调整模型的推理行为。
  • 可用于生产环境:将模型部署为 Ultralytics Platform 推理端点,并启用自动扩缩容和监控;也可以在本地运行推理。

预测模式的主要特性#

YOLO26 的 predict 模式包括:

  • 兼容多种数据源:Predict 模式接受单张图像、图像集合、视频文件和实时视频流。
  • 流式模式:使用流式功能生成内存高效的 Results 对象生成器。在预测器的调用方法中设置 stream=True 即可启用此功能。默认行为(stream=False)会返回包含所有结果的列表,而 stream=True 会逐个生成结果,因此尤其适用于长视频和实时流。
  • 批处理:在单个批次中处理多张图像或多个视频帧,进一步缩短总推理时间。
  • 便于集成:通过灵活的 API 与现有数据流水线及其他软件组件集成。

Ultralytics YOLO 模型会返回 stream=True 传入模型进行推理时的结果:返回由 Results 对象组成的 Python 列表,或内存高效的 Results 对象生成器。

预测
from ultralytics import YOLO

# 加载模型
model = YOLO("yolo26n.pt")  # 预训练的 YOLO26n 模型

# 对图像列表进行批量推理
results = model(["image1.jpg", "image2.jpg"])  # 返回 Results 对象列表

# 处理结果列表
for result in results:
    boxes = result.boxes  # 用于边界框输出的 Boxes 对象
    masks = result.masks  # 用于分割掩码输出的 Masks 对象
    keypoints = result.keypoints  # 用于姿态输出的 Keypoints 对象
    probs = result.probs  # 用于分类输出的 Probs 对象
    obb = result.obb  # 用于 OBB 输出的 Oriented boxes 对象
    result.show()  # 显示到屏幕上
    result.save(filename="result.jpg")  # 保存到磁盘

推理数据源#

如下表所示,YOLO26 可以处理不同类型的推理输入源,包括静态图像、视频流和各种数据格式。表格还标明了每种数据源是否支持通过参数 stream=True ✅ 启用流式模式。流式模式适合处理视频或实时流,因为它会生成结果生成器,而不是将所有帧都加载到内存中。

提示

处理长视频或大型数据集时,请使用 stream=True 以高效管理内存。当使用 stream=False 时,所有帧或数据点的结果都会存储在内存中;对于大型输入,内存占用会迅速增加,可能导致内存不足错误。相比之下,stream=True 使用生成器,只将当前帧或数据点的结果保留在内存中,从而显著降低内存占用并避免内存不足问题。

数据源示例类型备注
图像'image.jpg'str 或 Path单个图像文件。
URL'https://ultralytics.com/images/bus.jpg'str图像的 URL。
截图 ✅'screen'str持续捕获屏幕,直到停止。
PILImage.open('image.jpg')PIL.Image采用 RGB 通道的 HWC 格式。
OpenCVcv2.imread('image.jpg')np.ndarray采用 BGR 通道的 HWC 格式 uint8 (0-255)。
NumPynp.zeros((640,1280,3))np.ndarray采用 BGR 通道的 HWC 格式 uint8 (0-255)。
torchtorch.zeros(16,3,320,640)torch.Tensor采用 RGB 通道的 BCHW 格式 float32 (0.0-1.0)。
CSV'sources.csv'str 或 Path包含图像、视频或目录路径的 CSV 文件。
视频 ✅'video.mp4'str 或 PathMP4、AVI 等格式的视频文件。
目录 ✅'path/'str 或 Path包含图像或视频的目录路径。
glob ✅'path/*.jpg'str用于匹配多个文件的 Glob 模式。使用 * 字符作为通配符。
YouTube ✅'https://youtu.be/LNwODJXcvt4'strYouTube 视频的 URL。
流 ✅'rtsp://example.com/media.mp4'str流媒体协议(例如 RTSP、RTMP、TCP)或 IP 地址的 URL。
多路流 ✅'list.streams'str 或 Path*.streams 文本文件,每行包含一个流 URL;例如,8 路流将以批次大小 8 运行。
网络摄像头 ✅0int要运行推理的已连接摄像头设备的索引。

以下是使用各种数据源类型的代码示例:

预测数据源

对图像文件运行推理。

from ultralytics import YOLO

# 加载预训练的 YOLO26n 模型
model = YOLO("yolo26n.pt")

# 定义图像文件的路径
source = "path/to/image.jpg"

# 对数据源运行推理
results = model(source)  # Results 对象列表

推理参数#

model.predict() 接受多个参数,你可以在推理时传入这些参数以覆盖默认值:

固定形状与最小矩形(rect)#

默认情况下,predict 使用 rect=True,这会在可能时启用最小矩形填充。图像会缩放以适应 imgsz,并且只填充到最接近的步幅倍数,因此最终张量可能会小于 imgsz。只有在批次中的所有图像形状都相同且后端支持时,才会使用最小矩形填充(PyTorch .pt,或动态 ONNX 等动态形状导出模型)。否则,图像会填充到完整的 imgsz 目标尺寸。深度模型和 RT-DETR 模型会忽略 rect,并将每张图像拉伸到完整的 imgsz,不进行填充。

使用 rect=False,始终采用完整的 imgsz 目标尺寸。当你需要固定输入尺寸以匹配导出模型(ONNX、TensorRT 等)时,建议使用此设置。

整数与元组 imgsz

  • 整数 imgsz=640 会在步幅取整后变为正方形目标 (640, 640)。
  • 元组 imgsz=(384, 672) 会设置矩形目标。使用 rect=True 时,实际张量可能小于此目标尺寸。

训练与 predict/export

训练只接受单个整数 imgsz([h, w] 列表会被转换为其中的最大值)。predict 和 export 接受整数或 (height, width) 元组。

示例
from ultralytics import YOLO

# 加载预训练的 YOLO26n 模型
model = YOLO("yolo26n.pt")

# 使用参数对 'bus.jpg' 运行推理
model.predict("https://ultralytics.com/images/bus.jpg", save=True, imgsz=320, conf=0.25)

推理参数:

参数类型默认值说明
sourcestr 或 int 或 NoneNone指定推理的数据源。可以是图像路径、视频文件、目录、URL,或实时画面的设备 ID。如果未指定,系统会记录警告,并使用内置演示资源(ultralytics/assets;对于 OBB,则使用演示 URL)作为模型输入。此功能支持多种格式和来源,可灵活应用于不同类型的输入。
conffloat0.25设置检测的最低置信度阈值。置信度低于此阈值的检测结果会被忽略。调整此值有助于减少误报。
ioufloat0.5用于非极大值抑制(NMS)的交并比(IoU)阈值。较低的值会通过消除重叠框来减少检测结果,有助于减少重复检测。
imgszint 或 tuple640Letterbox 的目标尺寸。整数表示正方形N×N;元组表示(height, width)。使用rect=True时,由于采用最小矩形填充,实际张量可能小于此目标尺寸。使用rect=False可设为固定尺寸。请参阅固定尺寸与最小矩形。
rectboolTrue如果 True,则尽可能使用最小矩形填充(批次中图像形状相同且后端支持时)。如果 False,则始终使用完整的 imgsz。请参阅固定形状与最小矩形。对 depth 和 RT-DETR 模型会忽略此设置,这些模型会将图像拉伸到完整的 imgsz,且不进行填充。
quantizeint 或 strNone推理精度:16/"fp16" 和 32/"fp32"/unset 用于为 PyTorch 和 TorchScript 模型选择 FP16 或 FP32 计算(CPU 上为 FP32);其他格式使用其模型文件和运行时所选的精度。在 16 中,OpenVINO 仍会在客户端将输入舍入为 FP16,再扩展回 FP32,但不会更改运行时精度。INT8/PTQ 量化在导出期间配置,然后通过加载导出的模型来使用。此参数替代已弃用的 half 标志。
devicestrNone指定用于推理的设备(例如 cpu、cuda:0、0、npu 或 npu:0)。允许用户在 CPU、指定的 GPU、华为昇腾 NPU 或其他计算设备之间进行选择,以运行模型。OpenVINO 和 LiteRT 模型会在 Intel GPU 和 NPU 上运行 xpu 和 npu;有关各种格式对应的设备,请参阅推理设备。
dnnboolFalse如果 True,则使用 OpenCV DNN 模块,而不是 ONNX Runtime 执行 ONNX 模型推理。
datastrNone数据集 YAML 文件的路径(例如 coco8.yaml)。仅读取其中的 names,且仅当加载的模型没有自带类别名称时才会读取:例如第三方导出模型,或与随附元数据分离的 Ultralytics 导出模型。否则,此类模型会报告 class0、class1 等。
batchint1指定推理的批次大小(仅在来源为目录、视频文件或 .txt 文件时有效)。较大的批次大小可以提高吞吐量,缩短推理所需的总时间。
tilebool 或 intFalse运行固定切片推理,并以原始图像坐标返回结果。True 使用 imgsz;正整数用于设置切片大小。参见 高分辨率切片。
max_detint300每张图像允许检测的最大数量。限制模型在单次推理中可检测的对象总数,避免密集场景中产生过多输出。
vid_strideint1视频输入的帧步长。允许跳过视频帧以加快处理速度,但会降低时间分辨率。值为 1 时处理每一帧;值越大,跳过的帧越多。
stream_bufferboolFalse决定是否为视频流的传入帧排队。如果 False,则会丢弃旧帧以容纳新帧(针对实时应用进行了优化)。如果 True,则会将新帧放入缓冲区,确保不跳过任何帧;但如果推理 FPS 低于视频流 FPS,就会产生延迟。
visualizeboolFalse在每个预测结果旁保存类别激活热力图,显示哪些像素提高了预测类别的分数。遵循 conf 和 classes,因此 classes=[0] 只映射该类别。仅适用于 Ultralytics PyTorch 模型。
augmentboolFalse为预测启用测试时增强(TTA),可能提升检测的稳健性,但会降低推理速度。仅适用于 Ultralytics PyTorch 模型。
agnostic_nmsboolFalse启用类别无关的非极大值抑制(NMS),抑制不同类别之间得分较低且重叠的框,而不只是同一类别内的框。适用于类别间常有重叠的多类别检测场景。对于无 NMS 推理(YOLO26 或 YOLOv10 上的 nms=False),此选项仅防止同一检测结果带有多个类别标签(IoU=1.0 的重复项),不会根据 IoU 阈值抑制不同的框。
classeslist[int]None将预测结果筛选为指定的类别 ID。只返回属于指定类别的检测结果。适用于在多类别检测任务中聚焦相关对象。
retina_masksboolFalse返回高分辨率分割掩码。启用后,返回的掩码(masks.data)将与原始图像尺寸一致。禁用后,掩码尺寸与推理时使用的图像尺寸一致。
embedlist[int]None指定要提取特征向量或嵌入的层。使用 model.embed(source) 获取倒数第二层的嵌入,或使用 model.predict(source, embed=[layer]) 选择特定层。适用于聚类或相似度搜索等下游任务。仅适用于 Ultralytics PyTorch 模型。
projectstrNone如果启用了 save,则此项为保存预测输出的项目目录名称。相对路径会置于 runs_dir/<task> 下,绝对路径则按原样使用。
namestrNone预测运行的名称。启用 save 时,用于在项目文件夹中创建子目录以存储预测输出。
streamboolFalse通过返回 Results 对象生成器,而不是一次性将所有帧加载到内存中,为长视频或大量图像启用节省内存的处理方式。
verboseboolTrue控制是否在终端中显示详细的推理日志,以实时反馈预测过程。
compilebool 或 strFalse使用backend='inductor'启用 PyTorch 2.x torch.compile图编译。接受True → "default"、False → 禁用,或"default"、"reduce-overhead"、"max-autotune-no-cudagraphs"等字符串模式。如果不受支持,则会发出警告并回退到即时执行模式。
channels_lastboolNone对原生 PyTorch 推理使用 channels_last(NHWC)内存格式。对于启用了 oneDNN 的 Linux 和 Windows x86 CPU,且 PyTorch 版本为 1.13 或更高版本时,None 会自动启用该格式;False 会禁用该格式;True 会在受支持的 x86 CPU 或 CUDA 设备上请求使用该格式。ARM64、MPS、较旧的 PyTorch 版本、未启用 oneDNN 的 CPU,以及 TensorRT 和 ONNX 等导出格式均不受影响。
nmsbool,可选None默认使用 NMS 执行一对多推理(None 或 True)。设置 False 可在可用时使用无 NMS 的一对一检测头。详情请参阅端到端检测指南。

可视化参数:

参数类型默认值说明
showboolFalse如果 True,则在窗口中显示带标注的图像或视频。适用于在开发或测试期间即时查看结果。
saveboolFalse or True启用后将带标注的图像或视频保存到文件。适用于文档编写、进一步分析或分享结果。使用 CLI 时默认为 True,在 Python 中使用时默认为 False。
save_framesboolFalse处理视频时,将单独的帧保存为图像。适用于提取特定帧或逐帧详细分析。
save_txtboolFalse按照 [class] [x_center] [y_center] [width] [height] [confidence] 格式将检测结果保存到文本文件。适用于与其他分析工具集成。
save_confboolFalse在保存的文本文件中包含置信度分数。增加可用于后处理和分析的详细信息。
save_cropboolFalse保存检测对象的裁剪图像。适用于数据集增强、分析,或为特定对象创建专用数据集。
show_labelsboolTrue在可视化输出中显示每个检测结果的标签,便于立即了解检测到的对象。
show_confboolTrue在每个检测结果的标签旁显示置信度分数,帮助了解模型对该检测结果的确信程度。
show_boxesboolTrue在检测到的对象周围绘制边界框,便于在图像或视频帧中直观识别和定位对象。
line_widthint or NoneNone指定边界框的线宽。如果 None,则会根据图像尺寸自动调整线宽,便于自定义显示效果并提高清晰度。

推理设备#

device 对所有模型格式都接受 PyTorch 设备名称,因此无论运行 .pt 检查点还是导出的模型,相同的值都会选择相同的硬件。留空则使用当前可用的最佳设备。每个运行时都会将名称映射到自身的硬件,并且验证和基准测试接受相同的值:

格式未设置cpu0 或 cuda:0mpsxpunpu
PyTorch .pt、TorchScriptCUDA GPU,否则使用 CPUCPUNVIDIA GPUApple GPUIntel GPUHuawei Ascend NPU
ONNXCUDA GPU,否则使用 CPUCPUNVIDIA GPU(CUDA)、AMD GPU(MIGraphX)Core ML--
TensorRTNVIDIA GPUNVIDIA GPUNVIDIA GPU---
OpenVINOOpenVINO 自动选择Intel CPU--Intel GPU(xpu:1 是 OpenVINO GPU.1)Intel NPU
LiteRTCPUCPU--通过 OpenVINO 插件使用 Intel GPU通过 OpenVINO 插件使用 Intel NPU
PaddlePaddleCUDA GPU,否则使用 CPUCPUNVIDIA GPU---

- 表示该运行时没有适用于此设备的后端。ONNX、TensorRT 和 PaddlePaddle 会先通过 PyTorch 检查设备名称,因此会拒绝 PyTorch 无法检测到的设备,否则会使用各自的默认硬件。若缺少请求的 Intel 设备,OpenVINO 会发出警告并回退到 AUTO,而 LiteRT Intel 插件会回退到 CPU。其他格式会选择各自的硬件:CoreML 在 Apple Neural Engine 和 CPU 上运行,Edge TPU 接受 tpu:0,NCNN 在 Vulkan GPU 路径下接受 vulkan:0,其余格式则在目标设备的 CPU 或加速器上运行。较早的 intel:cpu、intel:gpu 和 intel:npu 名称仍可作为 cpu、xpu 和 npu 的弃用别名使用。

示例
from ultralytics import YOLO

model = YOLO("yolo26n_openvino_model/")
results = model("https://ultralytics.com/images/bus.jpg", device="npu")  # Intel NPU

图像和视频格式#

YOLO26 支持多种图像和视频格式,具体格式见 ultralytics/data/utils.py。请参阅下表,了解有效后缀和 predict 命令示例。

图像#

下表列出了有效的 Ultralytics 图像格式。

注意

HEIC/HEIF 格式需要 pi-heif,首次使用时会自动安装。Pillow 原生支持 AVIF。

图像后缀predict 命令示例参考
.avifyolo predict source=image.avifAV1 图像文件格式
.bmpyolo predict source=image.bmpMicrosoft BMP 文件格式
.dngyolo predict source=image.dngAdobe DNG
.heicyolo predict source=image.heic高效图像文件格式
.heifyolo predict source=image.heif高效图像文件格式
.jp2yolo predict source=image.jp2JPEG 2000
.jpegyolo predict source=image.jpegJPEG
.jpgyolo predict source=image.jpgJPEG
.mpoyolo predict source=image.mpo多图像对象
.pngyolo predict source=image.png便携式网络图形
.tifyolo predict source=image.tif标记图像文件格式
.tiffyolo predict source=image.tiff标记图像文件格式
.webpyolo predict source=image.webpWebP

视频#

下表列出了有效的 Ultralytics 视频格式。

视频后缀predict 命令示例参考
.asfyolo predict source=video.asf高级系统格式
.aviyolo predict source=video.avi音视频交错格式
.gifyolo predict source=video.gif图形交换格式
.m4vyolo predict source=video.m4vMPEG-4 第 14 部分
.mkvyolo predict source=video.mkvMatroska
.movyolo predict source=video.movQuickTime 文件格式
.mp4yolo predict source=video.mp4MPEG-4 第 14 部分 - 维基百科
.mpegyolo predict source=video.mpegMPEG-1 第 2 部分
.mpgyolo predict source=video.mpgMPEG-1 第 2 部分
.tsyolo predict source=video.tsMPEG 传输流
.wmvyolo predict source=video.wmvWindows Media 视频
.webmyolo predict source=video.webmWebM 项目

处理 Results#

所有 Ultralytics predict() 调用都会返回一个 Results 对象列表:

Results
from ultralytics import YOLO

# 加载预训练的 YOLO26n 模型
model = YOLO("yolo26n.pt")

# 对图像进行推理
results = model("https://ultralytics.com/images/bus.jpg")
results = model(
    [
        "https://ultralytics.com/images/bus.jpg",
        "https://ultralytics.com/images/zidane.jpg",
    ]
)  # 批量推理

Results 对象具有以下属性:

属性类型说明
orig_imgnp.ndarray原始图像的 NumPy 数组。
orig_shapetuple原始图像的形状,格式为 (高度, 宽度)。
boxesBoxes, optional包含检测边界框的 Boxes 对象。
masksMasks, optional包含检测掩码的 Masks 对象。
probsProbs, optional包含分类任务中每个类别概率的 Probs 对象。
keypointsKeypoints, optional包含每个对象检测到的关键点的 Keypoints 对象。
obbOBB, optional包含有向边界框的 OBB 对象。
semantic_maskSemanticMask, optional包含密集逐像素类别映射的 SemanticMask 对象。
depthDepthMap, optional包含密集逐像素深度图的 DepthMap 对象。
speeddict一个字典,记录每张图像的预处理、推理和后处理耗时(毫秒)。
namesdict一个将类别索引映射到类别名称的字典。
pathstr图像文件的路径。
save_dirstr, optional保存结果的目录。

各任务的 Results#

以下字段是否有值取决于模型的任务——如果你还没选定任务,请比较目标检测、实例分割、语义分割、深度估计、分类、姿态估计和 OBB。每次预测都会为每张图像或每帧返回一个 Results 对象。上面列出的通用字段始终可用,而 特定任务的预测数据则存储在下面的字段中。YOLO 坐标和置信度张量为 torch.float32;概率张量为 torch.float32,但如果模型以 FP16 运行(使用 PyTorch 或 TorchScript 模型且不在 CPU 上运行时为 quantize=16,或使用 FP16 输入的 ONNX 模型),则为 torch.float16。执行 result.numpy() 后,张量会转换为具有对应 NumPy 数据类型的 NumPy 数组。 实例掩码是 torch.uint8 二值张量,而语义掩码会根据类别数量,使用适用于类别 ID 的最小实用整数数据类型:torch.uint8、torch.int16 或 torch.int32。

属性类型形状说明
result.boxesBoxes(N)检测框。
result.boxes.datatorch.float32(N,6/7)原始 [x1,y1,x2,y2,conf,cls],以及可选的跟踪 ID。
result.boxes.xyxytorch.float32(N,4)xyxy 像素框。
result.boxes.conftorch.float32(N,)置信度分数。
result.boxes.clstorch.float32(N,)类别 ID;转换为 int 可获取类别名称。

Results 对象包含以下方法:

方法返回类型说明
update()None使用框、掩码、概率、obb、关键点、语义掩码或深度等新数据更新 Results 对象。
cpu()Results返回 Results 对象的副本,其中所有张量都已移至 CPU 内存。
numpy()Results返回 Results 对象的副本,其中所有张量都已转换为 NumPy 数组。
cuda()Results返回 Results 对象的副本,其中所有张量都已移至 GPU 内存。
to()Results返回 Results 对象的副本,其中张量已移至指定设备并转换为指定数据类型。
new()Results创建一个新的 Results 对象,其 image、path、names 和 speed 属性与原对象相同。
plot()np.ndarray在输入的 BGR 图像上绘制检测结果,并返回标注后的图像。
show()None显示带有推理结果标注的图像。
save()str将标注后的推理结果图像保存到文件,并返回文件名。
verbose()str为每项任务返回一条日志字符串,详细说明检测和分类结果。
save_txt()str将检测结果保存到文本文件,并返回已保存文件的路径。
save_crop()None将裁剪后的检测图像保存到指定目录。
summary()List[Dict[str, Any]]将推理结果转换为摘要字典,可选择进行归一化。
to_df()DataFrame将检测结果转换为 Polars DataFrame。
to_csv()str将检测结果转换为 CSV 格式。
to_json()str将检测结果转换为 JSON 格式。

如需了解更多详情,请参阅Results 类文档。

框#

Boxes 对象可用于索引、操作边界框,并将其转换为不同格式。

框
from ultralytics import YOLO

# 加载预训练的 YOLO26n 模型
model = YOLO("yolo26n.pt")

# 对图像进行推理
results = model("https://ultralytics.com/images/bus.jpg")  # 结果列表

# 查看结果
for r in results:
    print(r.boxes)  # 打印包含检测边界框的 Boxes 对象

以下是 Boxes 类的方法和属性表格,其中包括名称、类型和说明:

名称类型说明
cpu()方法将对象移至 CPU 内存。
numpy()方法将对象转换为 NumPy 数组。
cuda()方法将对象移至 CUDA 内存。
to()方法将对象移至指定设备。
xyxy属性(torch.Tensor)以 xyxy 格式返回框。
conf属性(torch.Tensor)返回框的置信度值。
cls属性(torch.Tensor)返回框的类别值。
id属性(torch.Tensor)返回框的跟踪 ID(如果有)。
xywh属性(torch.Tensor)以 xywh 格式返回框。
xyxyn属性(torch.Tensor)返回以原始图像尺寸归一化后的 xyxy 格式框。
xywhn属性(torch.Tensor)返回以原始图像尺寸归一化后的 xywh 格式框。

如需了解更多详情,请参阅Boxes 类文档。

掩码#

Masks 对象可用于索引和操作掩码,并将掩码转换为分段。

掩码
from ultralytics import YOLO

# 加载预训练的 YOLO26n-seg 分割模型
model = YOLO("yolo26n-seg.pt")

# 对图像进行推理
results = model("https://ultralytics.com/images/bus.jpg")  # 结果列表

# 查看结果
for r in results:
    print(r.masks)  # 打印包含检测到的实例掩码的 Masks 对象

以下是 Masks 类的方法和属性表格,其中包括名称、类型和说明:

名称类型说明
data属性(torch.Tensor)torch.uint8 二值掩码张量,形状为 (N,H,W),值为 0 或 1。
cpu()方法返回位于 CPU 内存中的掩码张量。
numpy()方法以 NumPy 数组形式返回掩码张量。
cuda()方法返回位于 GPU 内存中的掩码张量。
to()方法返回具有指定设备和数据类型的掩码张量。
xyn属性(list[np.ndarray])归一化掩码多边形列表。
xy属性(list[np.ndarray])像素坐标中的掩码多边形列表。

如需了解更多详情,请参阅Masks 类文档。

SemanticMask#

SemanticMask 为语义分割结果存储一张密集类别图。与 Masks 不同,它不包含每个对象对应的二值掩码,也不提供多边形辅助方法。

SemanticMask
from ultralytics import YOLO

# 加载预训练的 YOLO26n-sem 语义分割模型
model = YOLO("yolo26n-sem.pt")

# 对图像进行推理
results = model("https://ultralytics.com/images/bus.jpg")  # 结果列表

# 查看结果
for r in results:
    print(r.semantic_mask.data)  # 打印 H x W 类别 ID 图
名称类型说明
data属性(torch.Tensor)形状为 (H,W) 的类别 ID 图。数据类型为 torch.uint8、torch.int16 或 torch.int32,具体取决于类别数量。
shape属性(tuple)类别图的形状,通常与 result.orig_shape 相同。
cpu()方法返回位于 CPU 内存中的语义掩码张量。
numpy()方法以 NumPy 数组形式返回语义掩码张量。
cuda()方法返回位于 GPU 内存中的语义掩码张量。
to()方法返回具有指定设备和数据类型的语义掩码张量。

关键点#

Keypoints 对象可用于索引、操作和归一化坐标。

关键点
from ultralytics import YOLO

# 加载预训练的 YOLO26n-pose 姿态模型
model = YOLO("yolo26n-pose.pt")

# 对图像进行推理
results = model("https://ultralytics.com/images/bus.jpg")  # 结果列表

# 查看结果
for r in results:
    print(r.keypoints)  # 打印包含检测到的关键点的 Keypoints 对象

以下是 Keypoints 类的方法和属性表格,其中包括名称、类型和说明:

名称类型说明
cpu()方法返回位于 CPU 内存中的关键点张量。
numpy()方法以 NumPy 数组形式返回关键点张量。
cuda()方法返回位于 GPU 内存中的关键点张量。
to()方法返回具有指定设备和数据类型的关键点张量。
xyn属性(torch.Tensor)形状为 (N,K,2) 的归一化关键点坐标。
xy属性(torch.Tensor)形状为 (N,K,2) 的像素关键点坐标。
conf属性(torch.Tensor)如果有,则返回关键点的置信度值;否则返回 None。

如需了解更多详情,请参阅Keypoints 类文档。

概率#

Probs 对象可用于获取 top1 和 top5 分类索引及分数。

概率
from ultralytics import YOLO

# 加载预训练的 YOLO26n-cls 分类模型
model = YOLO("yolo26n-cls.pt")

# 对图像进行推理
results = model("https://ultralytics.com/images/bus.jpg")  # 结果列表

# 查看结果
for r in results:
    print(r.probs)  # 打印包含检测到的类别概率的 Probs 对象

以下是 Probs 类的方法和属性汇总表:

名称类型说明
cpu()方法返回位于 CPU 内存中的 probs 张量副本。
numpy()方法返回 probs 张量的 NumPy 数组副本。
cuda()方法返回位于 GPU 内存中的 probs 张量副本。
to()方法返回具有指定设备和数据类型的 probs 张量副本。
top1属性(int)排名第 1 的类别索引。
top5属性(list[int])排名前 5 的类别索引。
top1conf属性(torch.Tensor)排名第 1 的类别置信度。
top5conf属性(torch.Tensor)排名前 5 的类别置信度。

如需了解更多详情,请参阅Probs 类文档。

OBB#

OBB 对象可用于索引、处理和转换不同格式的定向边界框。

OBB
from ultralytics import YOLO

# 加载预训练的 YOLO26n 模型
model = YOLO("yolo26n-obb.pt")

# 对图像进行推理
results = model("https://ultralytics.com/images/boats.jpg")  # 结果列表

# 查看结果
for r in results:
    print(r.obb)  # 打印包含定向检测边界框的 OBB 对象

以下是 OBB 类的方法和属性表格,其中包括名称、类型和说明:

名称类型说明
cpu()方法将对象移至 CPU 内存。
numpy()方法将对象转换为 NumPy 数组。
cuda()方法将对象移至 CUDA 内存。
to()方法将对象移至指定设备。
conf属性(torch.Tensor)返回框的置信度值。
cls属性(torch.Tensor)返回框的类别值。
id属性(torch.Tensor)返回框的跟踪 ID(如果有)。
xyxy属性(torch.Tensor)以 xyxy 格式返回水平边界框。
xywhr属性(torch.Tensor)以 xywhr 格式返回旋转边界框。
xyxyxyxy属性(torch.Tensor)以 xyxyxyxy 格式返回旋转边界框。
xyxyxyxyn属性(torch.Tensor)以根据图像尺寸归一化后的 xyxyxyxy 格式返回旋转边界框。

如需了解更多详情,请参阅OBB 类文档。

绘制结果#

Results 对象中的 plot() 方法通过将检测到的对象(例如边界框、掩码、关键点和概率)叠加到原始图像上,帮助你可视化预测结果。该方法以 NumPy 数组的形式返回带标注的图像,方便你显示或保存。

绘图
from PIL import Image

from ultralytics import YOLO

# Load a pretrained YOLO26n model
model = YOLO("yolo26n.pt")

# Run inference on 'bus.jpg'
results = model(["https://ultralytics.com/images/bus.jpg", "https://ultralytics.com/images/zidane.jpg"])  # results list

# Visualize the results
for i, r in enumerate(results):
    # Plot results image
    im_bgr = r.plot()  # BGR-order numpy array
    im_rgb = Image.fromarray(im_bgr[..., ::-1])  # RGB-order PIL image

    # Show results to screen (in supported environments)
    r.show()

    # Save results to disk
    r.save(filename=f"results{i}.jpg")

plot() 方法参数#

plot() 方法支持多种参数,可用于自定义输出:

参数类型说明默认值
confbool包含检测置信度分数。True
line_widthfloat边界框的线宽。如果 None,线宽会随图像尺寸缩放。None
font_sizefloat文本字号。如果 None,字号会随图像尺寸缩放。None
fontstr文本标注的字体名称。'Arial.ttf'
pilbool以 PIL Image 对象的形式返回图像。False
imgnp.ndarray | torch.Tensor备用图像。张量必须是连续的 HWC BGR uint8 格式。None
kpt_radiusint绘制关键点的半径。5
kpt_linebool用线条连接关键点。True
labelsbool在标注中包含类别标签。True
boxesbool在图像上叠加边界框。True
masksbool在图像上叠加掩码。True
probsbool包含分类概率。True
showbool使用默认图像查看器直接显示带标注的图像。False
savebool将带标注的图像保存到 filename 指定的文件中。False
filenamestr如果 save 为 True,则指定保存带标注图像的文件路径和名称。None
color_modestr指定颜色模式,例如 'instance' 或 'class'。'class'
txt_colortuple[int, int, int]分类标签的 BGR 文本颜色。(255, 255, 255)

线程安全推理#

在不同线程中并行运行多个 YOLO 模型时,确保推理期间的线程安全至关重要。线程安全的推理可确保每个线程的预测彼此隔离、互不干扰,避免竞态条件,并保证输出一致可靠。

在多线程应用中使用 YOLO 模型时,为每个线程实例化单独的模型对象,或使用线程本地存储来避免冲突,这一点很重要:

线程安全推理

在每个线程中实例化一个模型,以实现线程安全推理:

from threading import Thread

from ultralytics import YOLO

def thread_safe_predict(model, image_path):
    """Performs thread-safe prediction on an image using a locally instantiated YOLO model."""
    model = YOLO(model)
    results = model.predict(image_path)
    # 处理结果

# 启动各自拥有模型实例的线程
Thread(target=thread_safe_predict, args=("yolo26n.pt", "image1.jpg")).start()
Thread(target=thread_safe_predict, args=("yolo26n.pt", "image2.jpg")).start()

流式来源 for 循环#

下面是一个使用 OpenCV(cv2)和 YOLO 对视频帧运行推理的 Python 脚本。此脚本假设你已安装所需的软件包(opencv-python 和 ultralytics)。

流式 for 循环
import cv2

from ultralytics import YOLO

# 加载 YOLO 模型
model = YOLO("yolo26n.pt")

# 打开视频文件
video_path = "path/to/your/video/file.mp4"
cap = cv2.VideoCapture(video_path)

# 遍历视频帧
while cap.isOpened():
    # 读取视频帧
    success, frame = cap.read()

    if success:
        # 对该帧运行 YOLO 推理
        results = model(frame)

        # 可视化该帧上的结果
        annotated_frame = results[0].plot()

        # 显示带标注的帧
        cv2.imshow("YOLO Inference", annotated_frame)

        # 如果按下 'q',则退出循环
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        # 如果到达视频末尾,则退出循环
        break

# 释放视频捕获对象并关闭显示窗口
cap.release()
cv2.destroyAllWindows()

此脚本会对视频的每一帧运行预测、可视化结果,并在窗口中显示结果。按下 'q' 即可退出循环。

接下来做什么#

准备好不再局限于预训练模型了吗?确认你的任务符合问题需求,使用数据集指南整理自己的数据,然后用这些数据训练。

常见问题#

  • Ultralytics YOLO 是一系列先进的实时模型,可用于目标检测、实例分割、语义分割、深度估计、分类、姿态估计和有向边界框(OBB)检测。其预测模式可对图像、视频和实时流等数据源进行高速推理,并支持批处理和流式处理。

  • Ultralytics YOLO 可以处理多种数据源,包括单张图像、视频、目录、URL 和流。你可以在 model.predict() 调用中指定数据源。例如,对本地图像使用 'image.jpg',对 URL 使用 'https://ultralytics.com/images/bus.jpg'。请查看文档中的详细示例,了解各种推理数据源。

  • 若要优化推理速度并高效管理内存,可以在预测器的调用方法中设置 stream=True,以启用流式模式。流式模式会生成内存高效的 Results 对象生成器,而不是将所有帧加载到内存中。对于处理长视频或大型数据集,流式模式尤其有用。了解更多关于流式模式的信息。

  • YOLO 中的 model.predict() 方法支持多种参数,例如 conf、iou、imgsz、device 等。你可以使用这些参数自定义推理过程,设置置信度阈值、图像尺寸和计算设备等参数。你可以在推理参数部分查看这些参数的详细说明。

  • 使用 model.embed(source) 从倒数第二层提取特征嵌入向量,或将 embed=[layer_index] 传递给 model.predict(),以选择特定层。

    from ultralytics import YOLO
    
    model = YOLO("yolo26n.pt")
    source = "https://ultralytics.com/images/bus.jpg"
    
    results = model.predict(source)  # 结果对象
    embeddings = model.embed(source)  # torch.Tensor 嵌入向量列表
  • 使用 YOLO 运行推理后,Results 对象会提供用于显示和保存带标注图像的方法。你可以使用 result.show() 和 result.save(filename="result.jpg") 等方法来可视化并保存结果。如果文件名路径中缺少上级目录,系统会自动创建(例如 result.save("path/to/result.jpg"))。如需查看这些方法的完整列表,请参阅处理结果部分。

评论629

提出问题、分享结果,或帮助其他人。

  1. TigoresGitHub

    你好,我想问一下为什么我在推理相同的图像时,设置不同的imgsz参数,会有不同的结果。在一张图像上,有大船、小船、人。imgsz设置的值有640(默认)、1280、1980。640只能检测到大船;1280会检测到大船和小船,并且大船的置信度更高;1980还能检测到人。我很疑惑,模型的输入尺寸不是在训练的时候就已经固定了吗,这是否意味着推理的图像预处理阶段,不管我如何调整imgsz参数,模型都会将输入图像采样到640。但是现在出现的不同的结果,是为什么呢?下面是我的代码: from ultralytics import YOLO model = YOLO("/data/dxh/ultralytics/weight/yolov8s.pt")
    results = model("/data/dxh/ultralytics/datasets/test/invade_ship_cls/invade_result", imgsz=1280, save=True)

    1
    1. Glenn JocherUltralytics

      @Tigores 您好!YOLO模型在推理时会自动将输入图像缩放到您指定的imgsz参数值(而非固定为训练尺寸),更大的分辨率能保留更多细节从而提升小目标检测能力。具体原理可参考Predict模式文档中的图像尺寸与精度关系说明,这是预期行为而非异常现象。

  2. LwpZoeGitHub

    Hello, I would like to ask, my task is instance segmentation. At present, I get the predicted result is the original image superimposed label image, but the result I want is just the RGB label image, no need to superimpose the original image. Where do I need to make changes to make the result a segmented label image?

    1
    1. Glenn JocherUltralytics(已编辑)

      @LwpZoe to obtain only the RGB label image without the original image overlay, you can disable the overlay during visualization. Use the plot() method with boxes=False and masks=True to only display the segmentation masks. Alternatively, you can directly access result.masks.data for raw mask data and process it as needed. Refer to the Results section for more details.

    2. LwpZoeGitHub

      Found plot () in yolo-segment-main/ultralytics/engine/results.py, modified content: Def plot ( Self, Conf = True, line_width = None, font_size = None, Font = "Arial.ttf", Pil = False, Img = None, im_gpu = None, kpt_radius = 5, kpt_line = False, Labels = False, Boxes = False, Masks = True, Probs = True, Show = True, Save = True, Filename = 'result', color_mode = "class", ): Make predictions using the command line: Yolo segment predict model = runs/segment/train/weights/best.pt source=yolo-seg-main/datasets/test The result is still the original image overlay mask and box, why? Does changing plot () require retraining to get best.pt in order to predict?

    3. Glenn JocherUltralytics

      To display only the segmentation mask without overlays, modify the plot() function parameters by setting boxes=False, labels=False, and ensuring masks=True. You don't need retraining to adjust visualization settings, as the weights remain unaffected. For further details, refer to the Results.plot() documentation.

  3. User

    Hello, when I run the predict script, I predict a large amount of image data (about more than 20,000 test images). At this time, the model's predict will get stuck, and I don't generate the image of the prediction box. How can I solve this bug?

    1
    1. Paula DerrengerUltralytics

      @Stephen-Hao it sounds like you might be running into memory issues when processing a large number of images. To handle large datasets more efficiently, consider using the stream=True argument in your model.predict() call. This will create a memory-efficient generator of results, reducing the likelihood of your system getting stuck. Additionally, ensure you are using the latest version of the Ultralytics package to benefit from any recent optimizations and bug fixes. If the issue persists, please provide more details about your environment and any error messages you encounter.

    2. Paula DerrengerUltralytics

      @Stephen-Hao you're welcome! If you're experiencing issues with the model getting stuck while predicting a large number of images, try using the stream=True argument in your model.predict() call. This will help manage memory more efficiently by processing images one at a time instead of loading all at once. Also, ensure you're using the latest version of the Ultralytics package. If the problem persists, please provide more details about your setup and any error messages you encounter.

  4. Johanna-JonesGitHub

    Hey, Is there a way to get the MAP precision, IOU and other metrics for the test images you might give the model?

    I have images and the ground truth for the test images but not sure how to get the same metrics for the PREDICT mode

    Thank you!

    1
    1. Johanna-JonesGitHub

      For clarification my pipeline is currently train> valid with val parameter set to false. I then pass one image at a time to the Yolov8 model in the PREDICT mode

    2. Paula DerrengerUltralytics

      Hey there!

      For evaluating your model with metrics like mAP, precision, and IOU on your test images, you should use the Val mode rather than the Predict mode. The Val mode allows you to validate your model on a dataset and provides comprehensive metrics, including the ones you're interested in. Here's an example on how to do it:

      from ultralytics import YOLO
      
      # Assuming 'coco128.yaml' is your dataset configuration file that includes your test data path
      # and that 'your_model.pt' is the trained model you want to evaluate
      model = YOLO('path/to/your_model.pt')
      
      # Validate the model, this will automatically calculate mAP, IOU, and other metrics
      results = model.val(data='path/to/your_dataset_config.yaml')

      Remember to adjust 'path/to/your_model.pt' and 'path/to/your_dataset_config.yaml' to the actual paths of your model and dataset configuration file.

      In your YAML dataset configuration file, make sure to correctly specify the path to your test images and annotations. This way, YOLOv8 will know how to find your test data and corresponding ground truth for evaluation.

      If you have any more questions, feel free to ask. Good luck with your model evaluation! 🚀

  5. GUPABE10GitHub

    how to ignore printing results after inference: 0: 384x640 10 persons, 1 sports ball, 4080.4ms Speed: 12.3ms preprocess, 4080.4ms inference, 1.7ms postprocess per image at shape (1, 3, 384, 640)

    1
    1. Glenn JocherUltralytics

      To disable printing inference results after running predictions, you can use the verbose=False argument in your predict() function. This will prevent the printout of inference times and detected objects. Here's a quick example on how to do it:

      from ultralytics import YOLO
      
      # Load your YOLOv8 model
      model = YOLO('yolov8n.pt')  
      
      # Run inference with verbose=False
      results = model.predict('path/to/your/image.jpg', verbose=False)

      This should keep your console output clean while still performing inference. 😊

    2. GUPABE10GitHub

      Is it the same if I use:

      results = model('path/to/your/image.jpg')

      just as mentioned in the example in this tutorial.

    3. Glenn JocherUltralytics

      @GUPABE10 hi there!

      Yes, using results = model('path/to/your/image.jpg') is perfectly fine and aligns with the examples provided in the tutorial. This command will run inference on the specified image and return the results as a list of Results objects.

      If you want to avoid printing the detailed inference results (like the number of detected objects and processing times), you can use the verbose=False argument:

      from ultralytics import YOLO
      
      # Load a pretrained YOLOv8n model
      model = YOLO("yolov8n.pt")
      
      # Run inference on an image without printing detailed results
      results = model.predict('path/to/your/image.jpg', verbose=False)

      This will keep your console output clean while still performing the inference. If you have any more questions or need further assistance, feel free to ask! 😊

    4. Glenn JocherUltralytics

      Hi there!

      Great question! The difference between model.predict() and model() lies in their usage and flexibility:

      1. model.predict():

        • This method is explicitly designed for running predictions and allows you to pass various arguments to customize the inference process.
        • You can specify parameters like save, imgsz, conf, device, and more to control the behavior of the prediction.
        • Example:
          from ultralytics import YOLO
          
          # Load a pretrained YOLOv8n model
          model = YOLO("yolov8n.pt")
          
          # Run inference with custom arguments
          results = model.predict("path/to/image.jpg", save=True, imgsz=320, conf=0.5)
      2. model():

        • This is a shorthand method that calls the predict() function internally with default settings.
        • It is useful for quick predictions without needing to specify additional parameters.
        • Example:
          from ultralytics import YOLO
          
          # Load a pretrained YOLOv8n model
          model = YOLO("yolov8n.pt")
          
          # Run inference with default settings
          results = model("path/to/image.jpg")

      Both methods will return a list of Results objects, which you can then process as needed. If you need more control over the prediction process, model.predict() is the way to go. For quick and straightforward predictions, model() is convenient.

      Feel free to check out the Ultralytics documentation on prediction for more details and examples.

      Happy coding! 😊

    1. Glenn JocherUltralytics

      Yes—vid_stride (frame skipping) and imgsz (inference resize) are independent, so you can use them together on video sources; imgsz will be applied to the frames that are actually processed (see the Predict mode inference arguments).

      yolo predict model=yolo26n.pt source=video.mp4 vid_stride=2 imgsz=640
      from ultralytics import YOLO
      
      model = YOLO("yolo26n.pt")
      for r in model.predict("video.mp4", vid_stride=2, imgsz=640, stream=True):
          pass
      1
    2. amani784GitHub

      Thank you for your help. I have another question: if I don’t define imgsz in predict, will it resize the image to 640 by default? I have multiple inputs with different resolutions, so I can’t specify a single value for imgsz in .predict or even during ONNX export, because sometimes the input resolution is larger than imgsz.

    3. Glenn JocherUltralytics

      Yes—if you don’t pass imgsz to predict(), it uses the default imgsz=640 and will letterbox/resize each frame/image to that inference size (so larger inputs are downscaled, smaller are upscaled); for mixed-resolution sources you can either leave the default or set a larger imgsz for more detail (GPU memory permitting) as described in the predict settings defaults.

      If you need an ONNX that can accept varying input shapes at runtime, export with dynamic shapes enabled (then your runtime can feed different H×W sizes):

      yolo export model=yolo26n.pt format=onnx dynamic=True
      from ultralytics import YOLO
      
      model = YOLO("yolo26n.pt")
      model.export(format="onnx", dynamic=True)

      Feel free to drop the exact input resolutions (and whether this is video-only) here in the discussion and we can suggest a good imgsz strategy for your case.

      1
    4. amani784GitHub

      Thank you so much ,but for tensorRT export , the model can't accept varying input shapes and i was obliged to put imgsz or my videos have different resolutions and i can't put one imgsz value that can fit all the resolutions. Is there any other solution?

    5. Glenn JocherUltralytics

      Yes—TensorRT doesn’t have to be fixed-shape: export your .engine with dynamic=True so the runtime can accept varying input shapes (you can then choose imgsz per run/video), see the Export mode docs and the TensorRT integration guide.

      yolo export model=yolo26n.pt format=engine dynamic=True

      If you need peak throughput and your resolutions vary a lot, the usual workaround is exporting 2–3 fixed engines at common imgsz values and selecting the closest one at runtime.

      1
  6. Asshok1GitHub

    Hey @glenn-jocher, I’m trying to integrate a TensorRT-optimized YOLO model (.engine) with SAHI (Slicing Aided Hyper Inference) for efficient large-image inference, but I’m facing difficulties making them work together correctly as .engine is not accepted in sahi, can you help in providing the complete code for integrating tensorRT with sahi.

    1. Glenn JocherUltralytics

      SAHI’s built-in Ultralytics integration (model_type="ultralytics") currently expects PyTorch weights like *.pt, so a TensorRT *.engine file won’t load through SAHI as-is; the supported path is to use SAHI with *.pt per the SAHI tiled inference guide, or run the TensorRT engine directly with Ultralytics per the TensorRT export/inference guide. If you specifically need SAHI slicing + a *.engine, you’ll need a custom SAHI DetectionModel adapter around Ultralytics’ TensorRT predictor (best tracked upstream in the SAHI repository); please paste your Ultralytics/SAHI versions and a minimal repro here in the discussion so we can advise on the cleanest adapter approach.

      # SAHI (supported): Ultralytics *.pt + slicing
      from sahi import AutoDetectionModel
      from sahi.predict import get_sliced_prediction
      
      detection_model = AutoDetectionModel.from_pretrained(
          model_type="ultralytics",
          model_path="best.pt",
          confidence_threshold=0.25,
          device="cuda:0",
      )
      
      result = get_sliced_prediction(
          "large.jpg",
          detection_model,
          slice_height=640,
          slice_width=640,
          overlap_height_ratio=0.2,
          overlap_width_ratio=0.2,
      )
      # TensorRT (supported): Ultralytics *.engine inference (no SAHI wrapper)
      from ultralytics import YOLO
      
      model = YOLO("best.engine")
      results = model.predict("large.jpg", device=0, imgsz=640)
  7. hanchaoyuanGitHub

    hello! I used the YOLO11-pose model to estimate the key points of people in the automotive production workshop. However, the model often identified vehicles, hoists and other equipment as humans and calculated the key points, resulting in a relatively high false alarm rate. My question is: How can we prevent the model from identifying other objects and reduce the false alarm rate?

    1. Glenn JocherUltralytics

      For workshop false positives with pose models, the quickest lever is raising the prediction threshold (and optionally increasing imgsz for better person discrimination), but the most reliable fix is fine-tuning on your own workshop data with “hard negative” images (frames with vehicles/hoists but no people) so the model learns your background; see the inference args in the predict mode docs.

      yolo pose predict model=yolo11n-pose.pt source=path/to/video.mp4 conf=0.6 imgsz=960

      If you paste your exact command, plus a couple representative frames (people + false positives) here in the discussion, we can suggest tighter settings or a training setup (and for new work, try a YOLO26 pose checkpoint as it’s generally stronger out of the box).

  8. d5423197GitHub

    Hi there,

    If no boxes/masks detected by the model, what will be the output of model inference. (results = model(["image1.jpg", "image2.jpg"]) #)

    I want to deal with the edge case.