开始使用

导出 YOLO26 模型为 ONNX 格式

ONNX(开放神经网络交换格式)是一种开放模型格式,大多数推理运行时都能加载。使用 format="onnx" 导出 Ultralytics YOLO26 模型时,会生成一个 .onnx 文件,可通过 ONNX Runtime 在 CPU、NVIDIA 和 AMD GPU、Apple 芯片以及 Windows 设备上运行。

概览#

属性详情
format 参数onnx
输出yolo26n.onnx,单个文件,其中将类名、任务和图像尺寸存储为元数据;经过校准的 quantize=8 导出使用 yolo26n_int8.onnx
运行平台CPU、NVIDIA GPU(CUDA)、AMD GPU(MIGraphX)、Apple 芯片(Core ML 执行提供程序)和 Windows ML 设备
运行时ONNX Runtime,或使用 dnn=True 的 OpenCV DNN
精确率FP32、FP16、INT8。YOLO26n 的 FP32 文件为 9.9 MB,FP16 文件为 5.0 MB,INT8 文件为 3.1 MB
导出主机Linux、macOS 或 Windows,可配备 GPU,也可不配备 GPU
在云端导出

Ultralytics Platform 可以帮你将训练好的模型导出为 ONNX,因此你无需配置本地导出环境。

快速入门#

安装 Ultralytics 包。首次导出时,如果缺少 onnx、onnxslim 和 onnxruntime,系统会安装它们(在 NVIDIA GPU 上使用 device=0 导出时,还会安装 onnxruntime-gpu)。

pip install ultralytics

其他安装方法请参阅安装指南。然后导出模型,并加载导出的文件以运行推理或验证准确率。

导出
from ultralytics import YOLO

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

# 将模型导出为 ONNX 格式
model.export(format="onnx")  # 创建 'yolo26n.onnx'

# 使用校准数据导出 INT8 量化的 ONNX 模型
model.export(format="onnx", quantize=8, data="coco8.yaml")  # 创建 'yolo26n_int8.onnx'
预测
from ultralytics import YOLO

# 加载导出的 ONNX 模型
model = YOLO("yolo26n.onnx")

# 运行推理
results = model("https://ultralytics.com/images/bus.jpg")
验证
from ultralytics import YOLO

# 加载导出的 ONNX 模型
model = YOLO("yolo26n.onnx")

# 在 COCO8 数据集上验证准确率
metrics = model.val(data="coco8.yaml")

支持的任务#

ONNX 导出支持 YOLOv8、YOLO11 和 YOLO26 模型的全部七种 Ultralytics 任务:检测、实例分割、语义分割、深度估计、分类、姿态估计 和 OBB。语义分割和深度估计仅适用于 YOLO26,因为只有 YOLO26 系列提供这两种任务头。

导出参数#

参数类型默认值说明
formatstr'onnx'导出模型的目标格式,用于定义与各种部署环境的兼容性。
imgszint 或 tuple640模型输入的图像尺寸:正方形图像使用整数,指定尺寸使用元组 (height, width)。如果未传入,导出时会使用检查点训练时的尺寸。官方 YOLO26 检查点中,检测、实例分割、姿态估计模型以及基于 ADE20K 预训练的语义模型使用 640,OBB 模型和基于 Cityscapes 预训练的语义模型使用 1024,深度模型使用 768,分类模型使用 224。
quantizeint 或 strNone量化精度:16(FP16;CPU 导出保留 FP32 输入和输出,GPU 导出则将输入和输出也设为 FP16),或 8(使用 ONNX Runtime 和来自 data 的校准图像进行 INT8 静态量化,生成 _int8.onnx 模型);32/未设置表示 FP32。使用 quantize=8 训练的检查点,在 quantize 未设置或设为 8 时会导出为 INT8(其他值会报错),根据检查点中包含的范围生成 Q/DQ 节点,无需校准,且使用普通的 .onnx 名称。此参数取代已弃用的 half/int8 标志。
datastrNone用于 INT8 校准的数据集 YAML;分类任务则使用数据集目录或内置数据集名称。若使用 quantize=8 时未提供此参数,Ultralytics 会为该模型任务选择默认校准数据集;使用 quantize=8 训练的检查点则不需要校准数据集。
fractionfloat、int 或 list1.0校准子集,可按比例、图像数量或 [train, val, test] 比例/数量指定。包含两个项目的列表会让 test 保持完整,而 0 会跳过它。
dynamicboolFalse将输入的批次、高度和宽度设为动态轴,因此一个文件可以接受不同的批次大小(最大为使用 nms=True 时导出的 batch)和不同的图像尺寸。请参阅动态导出。
simplifyboolTrue使用 onnxslim 简化模型图。
opsetintNone指定 ONNX opset 版本,以兼容不同的 ONNX 解析器和运行时。如果未设置,则使用 opset 18(PyTorch < 2.4 时会使用更低版本),且不会超过已安装的 onnx 版本。请参阅最低 opset 版本。
nmsbool,可选None选择原始输出(None,默认)、嵌入式 NMS(True)或无 NMS 头(False)。请参阅输出格式。
batchint1导出模型的批次大小。静态导出会在输入形状中固定此批次大小。使用 dynamic=True 和 nms=True 时,请将其设为你计划运行的最大批次大小。
devicestrNone导出所用设备:cpu(默认,即使机器配备 GPU 也使用此项)、0(CUDA GPU)或 mps(Apple 芯片)。它仅会影响 quantize=16 的结果,请参阅 FP16 输入。

所有格式共有的参数请参阅导出模式文档。

INT8 量化#

对于未通过量化感知训练训练的检查点,quantize=8 仅对 Conv、Gemm 和 MatMul 节点应用 ONNX Runtime 静态量化。所有其他节点均保持浮点格式,包括用于组装 output0 的运算:框坐标(像素)和类别分数(0 到 1)共用该张量,因此若对它使用单一 INT8 缩放因子,所有类别分数都会被舍入为零。opset 13 及更高版本按通道量化权重。如果你要在导出的 FP32 模型上自行运行 quantize_static,请排除相同的节点并设置 per_channel=True:

import onnx
from onnxruntime.quantization import quantize_static

model = "yolo26n.onnx"
exclude = [n.name for n in onnx.load(model).graph.node if n.op_type not in {"Conv", "Gemm", "MatMul"}]
quantize_static(model, "yolo26n_int8.onnx", calibration_reader, nodes_to_exclude=exclude, per_channel=True)

此处,calibration_reader 是一个 onnxruntime.quantization.CalibrationDataReader,会生成 {"images": array},其批次大小与模型相同,并按推理流程进行预处理:填充调整至导出尺寸(分类任务则调整尺寸并从中心裁剪)、RGB、NCHW,且 float32 的取值范围为 0-1。

INT8 模型保留 FP32 模型的输入和输出类型,因此为 FP32 模型编写的推理代码无需修改即可运行 INT8 模型。INT8 文件比 FP32 文件小三到四倍,但在基准测试中,使用 ONNX Runtime 时,INT8 在 GPU 和 CPU 上的运行速度都比 FP32 慢。在选择精度前,请在目标硬件上测量延迟。

输出格式#

导出的模型接收一个名为 images 的输入,其形状为 (batch, 3, height, width),采用 RGB 格式,数值缩放至 0-1。输入类型为 float32,但使用 quantize=16 导出的 GPU 模型除外,这类模型要求输入为 float16。nms 参数设置 output0 的布局。以下形状适用于在 imgsz=640 导出的 YOLO26n 检测模型(含 80 个类别):

nmsoutput0 形状内容
None(默认)(1, 84, 8400)对于 8400 个锚点中的每一个,依次为边界框中心 x、中心 y、宽度、高度(单位为输入像素),然后是 80 个类别分数。请自行应用 NMS。
True(1, 300, 6)模型内部会运行 NMS。每一行的格式为 x1, y1, x2, y2, score, class;最后一个检测结果之后的行均为零。
False(1, 300, 6)无 NMS 头。每一行的格式为 x1, y1, x2, y2, score, class,不包含 NMS 步骤。请自行按分数筛选行。

其他任务使用相同的输入和以下输出。形状适用于采用默认导出尺寸的官方 YOLO26n 检查点,其中语义分割的 Cityscapes 检查点为 yolo26n-sem.pt:

任务默认 imgsz使用 nms=None 时的输出使用 nms=False 或 nms=True 时的输出
检测640output0 (1, 84, 8400)output0 (1, 300, 6)
分割640output0 (1, 116, 8400), output1 (1, 32, 160, 160)output0 (1, 300, 38), output1 (1, 32, 160, 160)
语义1024output0 (1, 1024, 1024),每个像素对应的类别索引为 uint8与 nms=None 相同
深度768output0 (1, 1, 768, 768),深度图与 nms=None 相同
分类224output0 (1, 1000),softmax 后的类别概率对于 nms=False,与 nms=None 相同;nms=True 会报错
姿态640output0 (1, 56, 8400)output0 (1, 300, 57):6 个边界框值,然后是 17 个关键点,每个关键点 3 个值
OBB1024output0 (1, 20, 21504)output0 (1, 300, 7):center x, center y, width, height, score, class, angle(弧度)

分割输出行在边界框值后包含 32 个掩码系数,output1 则存储掩码原型。在 FP32 和 INT8 模型中,除语义类别图外,所有输出均为 float32。

使用 nms=True 时,置信度阈值 conf(默认值为 0.25)、IoU 阈值 iou(默认值为 0.5)、agnostic_nms 和 max_det(默认值为 300)都会在导出时固定到计算图中。预测时设置较低的 conf 无法恢复已被计算图移除的检测结果,因此要更改这些值,请重新导出。max_det 和 agnostic_nms 同样适用于 nms=False:max_det=100 会生成形状为 (1, 100, 6) 的 output0。

YOLO("yolo26n.onnx") 会从文件元数据中读取布局,因此只有在自己的代码中运行模型时才需要这些形状。你的代码也可以将元数据作为字符串读取:names、task、imgsz、stride、batch、end2end 和 args。

import ast

import onnxruntime as ort

meta = ort.InferenceSession("yolo26n.onnx").get_modelmeta().custom_metadata_map
names = ast.literal_eval(meta["names"])  # {0: 'person', 1: 'bicycle', ...}
imgsz = ast.literal_eval(meta["imgsz"])  # [640, 640]

部署#

YOLO("yolo26n.onnx") 使用 ONNX Runtime 运行模型,并根据 device 参数选择执行提供程序。在配备 CUDA GPU 的机器上,如果未设置 device,则会使用 GPU。

device执行提供程序
cpuCPUExecutionProvider
NVIDIA GPU 上的 0CUDAExecutionProvider,来自首次使用时安装的 onnxruntime-gpu 包
AMD ROCm GPU 上的 0MIGraphXExecutionProvider,请参阅 使用 MIGraphX 在 AMD GPU 上进行推理
Apple 芯片上的 mps静态形状节点使用 CoreMLExecutionProvider;动态形状节点则使用 CPUExecutionProvider

日志行 Using ONNX Runtime 1.31.1 with CUDAExecutionProvider 会显示当前使用的提供程序。推理时的行为取决于模型的导出方式:

  • 静态导出(默认):模型始终以导出时的 imgsz 和 batch 运行,Ultralytics 会从文件元数据中读取这两个值。传给 predict 的 imgsz 会被忽略。较大的批次会拆分为多个导出批次大小的块,较小的批次则会填充,因此任意数量的图像都可以运行。
  • 动态导出(dynamic=True):predict 接受任何为模型步幅倍数的 imgsz。批次大小可以变化,但使用 nms=True 时,批次大小不能超过导出时设置的 batch 值,因此请将其设为计划运行的最大批次大小。
  • GPU 内存:使用 CUDAExecutionProvider 时,静态模型会使用 ONNX Runtime IO 绑定,将输入和输出张量保留在 GPU 上。动态模型则会在每次调用时通过 CPU 内存复制这些张量。
  • CPU 线程:Ultralytics 将 ONNX Runtime 的 intra-op 线程数限制为 8;如果进程可用的物理 CPU 核心数更少,则以核心数为限。设置 ORT_INTRA_OP_NUM_THREADS 环境变量即可使用其他线程数。

将 dnn=True 传给 predict 或 val,即可使用 OpenCV DNN 在 CPU 上运行模型,替代 ONNX Runtime。OpenCV DNN 支持的导出选项较少,请参阅限制和故障排查。

要在 Ultralytics 包之外运行模型,请参阅以下资源:

Windows ML 推理#

在 Windows 11 24H2(build 26100)或更高版本且 Python 3.10+ 的环境中,你可以在独立环境中安装 onnxruntime-windowsml,让 Windows ML 为你的硬件选择执行提供程序。安装它,而不要安装其他 ONNX Runtime 构建版本,然后将同一个导出的 .onnx 模型与 YOLO("model.onnx") 搭配使用。此后端会保留 PyTorch 线程数和提供的会话选项,包括显式指定的提供程序策略。如果未提供策略,Windows ML 会选择硬件以获得最高性能,即使 PyTorch 设备是 cpu 也一样。选择此运行时之前,请在你的设备上测量预测延迟;此运行时是可选的,默认不会安装。

在与 CPU 共享功耗的集成 GPU 上,预处理和后处理阶段处于空闲状态的 PyTorch 线程可能会拖慢 Windows ML 推理。预测前调用 torch.set_num_threads(1) 可以减少这种影响。此设置作用于整个进程,因此该进程中的其他 PyTorch 模型也会以单线程运行。

import torch

from ultralytics import YOLO

torch.set_num_threads(1)  # 可选,请在你的设备上测量
results = YOLO("yolo26n.onnx")("https://ultralytics.com/images/bus.jpg")

使用 MIGraphX 在 AMD GPU 上进行推理#

Ultralytics 通过 ONNX Runtime 的 MIGraphX 执行提供程序在 AMD GPU 上运行导出的 ONNX 模型。在运行 ROCm (HIP) 的 x86-64 系统上,如果 Python 版本为 3.11 或更高,ONNX 后端会在首次使用时安装 onnxruntime-ep-migraphx 插件,并自动选择 MIGraphXExecutionProvider,无需更改代码;所有 YOLO26 任务均受支持。有关前置要求、安装、使用、基准测试和编译程序缓存,请参阅 AMD GPU 推理指南。

限制和故障排查#

  • 最低 opset 版本:如果 opset 版本太低,无法支持模型,导出会因 ONNX export requires opset>=N 而失败。分类任务的最低版本为 7;检测、实例分割、语义分割、姿态估计和 OBB 的最低版本为 9;深度估计任务,以及使用 nms=True 导出的检测、实例分割、姿态估计和 OBB 模型,最低版本为 11;RT-DETR 的最低版本为 16。
  • FP16 输入:在 GPU 上导出的 FP16 模型(quantize=16 device=0)要求你在自己的代码中提供 FP16 输入张量。在 CPU 上导出的 FP16 模型会保留 FP32 输入和输出,并在计算图内部进行转换。YOLO() 会在 GPU 和 CPU 上为两种模型提供正确类型的输入。
  • INT8 文件名:quantize=8 会写入 yolo26n_int8.onnx 并移除中间 FP32 文件,因此推理时请加载 _int8 文件。使用 quantize=8 训练的检查点是例外:其导出会将 Q/DQ 节点写入 yolo26n.onnx,并跳过校准。
  • INT8 校准尺寸:对于未使用 quantize=8 训练的检查点,如果校准数据集划分少于 300 张图像,导出时会发出警告。默认使用 val 数据集划分进行校准,而 coco8.yaml 只有 4 张验证图像,因此计划部署模型时请使用自己的数据集。
  • 嵌入式 NMS:nms=True 要求 PyTorch 1.13 或更高版本。分类任务会触发 'nms=True' is not valid for classification models;语义分割、深度估计和 RT-DETR 模型则会忽略此项并发出警告。
  • 无 NMS 头:nms=False 需要使用带有无 NMS 头的模型,例如 YOLO26 或 YOLOv10。对于其他模型(例如 YOLO11),导出时会发出 This model has no one-to-one head; using one-to-many outputs 警告,并写入原始 (1, 84, 8400) 输出。
  • 未使用 GPU:如果日志显示 CUDA requested but CUDAExecutionProvider not available. Using CPU...,说明已安装的 ONNX Runtime 构建版本没有可用的 CUDA 提供程序。请安装 onnxruntime-gpu,替代 onnxruntime,并确认其 CUDA 和 cuDNN 版本与你的系统匹配。
  • OpenCV DNN:在 OpenCV 4.14.0 中,dnn=True 可运行默认模型、nms=False、INT8 模型以及在 GPU 上导出的 FP16 模型。它无法加载使用 nms=True 导出的模型、使用 dynamic=True 导出的模型,或在 CPU 上使用 quantize=16 导出的模型。
  • 带 NMS 的动态形状:将 dynamic=True 与 nms=True 结合使用时,还要将 batch 设为计划运行的最大批次大小。如果 batch 保持为 1,导出时会发出警告。
  • 计算图简化:如果 onnxslim 失败,导出过程会记录警告,并保存未简化的模型。
  • IR 版本:导出程序会将 ONNX IR 版本限制在 10,以便较旧版本的 ONNX Runtime 也能加载该文件。默认导出且 opset 为 18 时,IR 版本为 8。

其他错误请参阅常见问题指南。

基准测试#

在 CPU(Intel Xeon CPU @ 2.00 GHz)上使用 ONNX Runtime 时,YOLO26n 的运行速度最高比 YOLO11n 快 43%。YOLO26 模型页面列出了除语义分割外所有任务中每个模型的 CPU ONNX 速度。



观看: Ultralytics YOLO26 与 Ultralytics YOLO11 ONNX 推理测试 | YOLO26 推理速度快约 43% 🚀

使用 ONNX Runtime 的 FP32、FP16 和 INT8#

下表比较了 PyTorch 与所有 YOLO26 检测模型的 FP32、FP16 和 INT8 ONNX 模型,运行时使用 ONNX Runtime CUDAExecutionProvider。所有 GPU 数据均在一块 NVIDIA RTX PRO 6000 Blackwell Server Edition GPU 上测得。

每张图像的毫秒数,越低越好。每个模型最快的格式以粗体显示。

模型imgszPyTorchONNX FP32ONNX FP16ONNX INT8
YOLO26n6402.851.961.883.73
YOLO26s6402.982.141.734.31
YOLO26m6403.293.012.145.37
YOLO26l6404.704.093.087.51
YOLO26x6405.935.563.909.38

CPU 上的 YOLO26n(AMD EPYC 9655,PyTorch 和 ONNX Runtime 均使用 8 个线程;使用的 CPU 与 YOLO26 模型表中的 CPU 不同):

指标PyTorchONNX FP32ONNX FP16ONNX INT8
延迟(毫秒/图像)13.213.413.256.5
mAPval 50-9540.840.940.938.7
  • FP16 将文件大小减半,精度比 FP32 低不到 0.1 mAP;在 GPU 上速度最高提升 1.4 倍,在 CPU 上则没有加速。
  • INT8 文件最小,但 mAP 下降了 2.2 至 3.0,且在 GPU 和 CPU 上都比 FP32 慢。

测量结果于 2026 年 11 月 13 日在 batch=1 使用 ultralytics 8.4.211、ONNX Runtime 1.30.0、PyTorch 2.15.0 和 CUDA 13.2 得出。延迟是 val 报告的推理阶段耗时,不包括预处理或后处理。

关于 ONNX#

ONNX 是由 Facebook 和 Microsoft 发起的社区项目,目前由 IBM、Amazon 和 Google 等组织共同开发。它定义了一组通用运算符和一种文件格式,用于机器学习模型,因此,在一种框架(例如 PyTorch)中训练的模型可以在多种运行时和硬件平台上运行。

ONNX model portability across deep learning frameworks

ONNX Runtime 是适用于 ONNX 模型的跨平台推理引擎。它的执行提供程序使用特定于硬件的库,在 CPU、GPU 和专用加速器上运行模型。

ONNX Runtime cross-platform inference acceleration

ONNX 也是其他 Ultralytics 导出格式的中间步骤,包括 TensorRT,并且是厂商 NPU 工具链的输入格式,例如 Huawei Ascend、Qualcomm QNN 和 Rockchip RKNN。有关规范,请参阅 ONNX 文档。

常见问题#

  • 除非你的运行时需要特定版本,否则不要设置 opset。导出器随后会在 PyTorch 2.4 及更高版本上使用 opset 18,在 PyTorch 1.13 到 2.3 上使用 opset 17,在更旧的 PyTorch 版本上使用更低的 opset,并且绝不会高于已安装的 onnx 软件包所支持的版本。默认值最高为 18,因为 ONNX Runtime CUDA 提供程序会在 CPU 上运行部分 opset 19 及更高版本的运算符,例如 Resize。当较旧的运行时或转换器不接受默认值时,可以设置较低的值,例如 opset=12。该值不能低于模型的最低 opset。

  • 这取决于你导出时使用的 nms 参数。默认导出会返回原始预测结果,需要进行置信度筛选和 NMS。使用 nms=False 或 nms=True 导出时,每张图像最多返回 max_det(默认 300)个最终检测结果,格式为输入图像像素坐标中的 x1, y1, x2, y2, score, class,因此你只需按分数筛选并将边界框缩放回原始图像。OBB 行会用 center x, center y, width, height 代替角点,并包含角度。有关张量形状,请参阅输出格式。

    使用 ONNX Runtime 读取无 NMS 输出
    # 先导出:yolo export model=yolo26n.pt format=onnx nms=False
    import numpy as np
    import onnxruntime as ort
    
    session = ort.InferenceSession("yolo26n.onnx")  # 使用 nms=False 导出
    image = np.zeros((1, 3, 640, 640), dtype=np.float32)  # 你预处理后的图像
    detections = session.run(None, {"images": image})[0][0]  # shape (300, 6)
    detections = detections[detections[:, 4] > 0.25]  # 保留置信度高于阈值的行
  • 设置 dynamic=True。此时,images 输入的形状为 (batch, 3, height, width),批次、图像高度和宽度均为动态;默认的 (nms=None) 检测 output0 的形状为 (batch, 84, anchors),因此同一个文件在推理时可接受不同的批次大小和图像尺寸。使用 nms=True 时,批次大小受限于导出时使用的 batch 值。除分类任务外,官方 YOLO26 检查点的高度和宽度必须是模型步幅的倍数,即 32。动态模型不支持在 CUDA 上使用 IO binding,也无法在 OpenCV DNN 中加载;如果输入尺寸固定,请继续使用默认的静态导出。

    动态导出
    from ultralytics import YOLO
    
    model = YOLO("yolo26n.pt")
    model.export(format="onnx", dynamic=True)
  • 如果一个文件需要在不同硬件上运行,或者部署机器不是导出模型的机器,请使用 ONNX。如果你想在特定 NVIDIA GPU 上获得最低延迟,请使用 TensorRT:TensorRT 引擎针对单一 GPU 架构和 TensorRT 版本构建,无法移植到其他环境。关于其他目标平台,请参阅模型部署选项指南。

  • 可以。ONNX Runtime 提供 web 和 mobile 版本,可加载同一个 .onnx 文件。使用 nms=False 导出,可避免在应用程序代码中进行后处理。对于手机,iOS 上的 Core ML 和 Android 上的 LiteRT 是原生格式。

评论77

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

  1. dopeggguyGitHub

    The parameter "half" bost apperence in train and export, what’s difference. when we using this parameter what should we need attention.

    1. Glenn JocherUltralytics(已编辑)

      @dopeggguy Good question—summary: training uses mixed precision via amp=True (weights stay FP32; compute is FP16 where safe), while export uses quantize=16 (the former half=True, now deprecated) to write an FP16 model for runtimes that support FP16. During training prefer amp; use FP16 only at export/inference, and don't combine it with INT8 (quantize=8). See the train overview and AMP notes in the Train mode docs and the quantize option details in Model Export – Arguments and Configuration – Export Settings.

      from ultralytics import YOLO
      
      # Mixed-precision training (recommended)
      YOLO("yolo26n.yaml").train(data="data.yaml", amp=True)
      
      # FP16 export for FP16-capable runtimes (e.g., CUDA/TensorRT/OpenVINO FP16)
      YOLO("best.pt").export(format="onnx", quantize=16)
    2. dopeggguyGitHub

      yoloModel = YOLO(path_dir) yoloModel.export(format='onnx', dynamic=False, half=True, imgsz=(640, 640))

      I'm not sure why. I enabled half=True, but the actual size of the exported model doesn't seem to change at all.

    3. Glenn JocherUltralytics(已编辑)

      @dopeggguy half=True is deprecated in favor of quantize=16. On older releases a CPU-only ONNX export ignored the flag and stayed FP32, so the file size was almost identical. Current releases convert CPU ONNX exports to FP16 too (keeping float32 inputs/outputs), and GPU exports are FP16 natively. If you have a GPU, you can force export on it and re-check:

      from ultralytics import YOLO
      
      YOLO(path_dir).export(format="onnx", imgsz=(640, 640), dynamic=False, quantize=16, device=0)

      You can then open the ONNX in Netron or inspect it with the onnx Python API to confirm the weights are float16; for pure CPU deployments it is often better to keep ONNX as FP32 or use a CPU‑oriented backend (e.g. OpenVINO) for FP16/INT8 optimization instead, with some general ONNX background outlined in the ONNX: Open Neural Network Exchange overview.

  2. bastinj98GitHub

    Hi, I trained d a YOLOV8-segn model to detect and segment a single class (nc=1) and then exported in to onnx (simplify, nms, half are all False) with opset = 17. The output shape is 1x37x8400.

    I am building a C++ pipeline to use this model to run inference. How can I process this output to get the final segmentation mask ?

  3. NgZimingGitHub

    I exported a yolo 11 segment model to onnx format, and used onnx-runtime to infer. It responded two ndarrays of shapes (1, 37, 21504) and (1, 32, 256, 256). (imgsz=1024) So, how can i extract masks from these two arrays?

    1. Glenn JocherUltralytics

      @NgZiming 这两个输出正是分割模型的“检测头 + 原型掩码”:(1, 37, 21504) = 4(xywh) + nc + 32(mask系数),(1, 32, 256, 256) 为32个原型;掩码可由原型与对应检测的32维系数线性组合并裁剪到框内,最小示例(Python/NumPy)如下:

      import numpy as np
      import cv2
      
      def sigmoid(x): return 1 / (1 + np.exp(-x))
      
      def mask_from_outputs(det, proto, img_h, img_w, det_idx):
          # det: (1, C, N) -> (C, N), proto: (1, 32, 256, 256) -> (32, 256, 256)
          det = det[0]; proto = proto[0]
          nm, ph, pw = proto.shape  # 32, 256, 256
          nc = det.shape[0] - 4 - nm
      
          # 1) 取该检测的框、类别分数与32维掩码系数
          cx, cy, w, h = det[0, det_idx], det[1, det_idx], det[2, det_idx], det[3, det_idx]
          coeff = det[4+nc:4+nc+nm, det_idx]  # (32,)
      
          # 2) 原型 × 系数 -> 原始掩码 (ph, pw)
          m = sigmoid((proto.reshape(nm, -1).T @ coeff).reshape(ph, pw))
      
          # 3) 可选:按框在原型分辨率下裁剪(坐标为[0,1]比例)
          x0 = int(max(0, (cx - w/2) * pw)); x1 = int(min(pw, (cx + w/2) * pw))
          y0 = int(max(0, (cy - h/2) * ph)); y1 = int(min(ph, (cy + h/2) * ph))
          crop = np.zeros_like(m); crop[y0:y1, x0:x1] = m[y0:y1, x0:x1]
      
          # 4) 上采样到原图尺寸并二值化
          mask = cv2.resize(crop, (img_w, img_h), interpolation=cv2.INTER_LINEAR)
          return (mask > 0.5).astype(np.uint8)

      要点:确保与推理时的预处理一致(letterbox 缩放与填充、RGB/归一化等),否则框与掩码会错位。关于分割导出产生两个输出(output0 检测+系数,output1 原型)的由来,可见导出实现参考的 export_onnx 说明:export_onnx 函数参考.

      1
  4. User

    I have a question. If it's convenient, please answer it. Thank you! I'm working with cell images, and the image size is 3072*2048. I trained with imagesize=3072, but if I use imagesize=640, I can't detect objects. I can predict with a 3072 imagesize using a pt file, but now I'm trying to switch to C++ and call onnx, and the 3072 inference is very slow. Is this normal?

    1. Glenn JocherUltralytics

      @giter915 Yes—running 3072×2048 through ONNX/C++ will be much slower; inference time grows quickly with input area. Two practical options: use a faster backend or reduce effective input while keeping accuracy. For GPU, prefer TensorRT; for CPU, OpenVINO FP16/INT8 gives the largest gains. Examples:

      from ultralytics import YOLO
      
      # GPU-optimized
      YOLO("best.pt").export(format="engine", imgsz=1536, half=True, dynamic=True)
      
      # CPU-optimized
      YOLO("best.pt").export(format="openvino", imgsz=1536, half=True)  # add int8=True with calibration if desired

      If you must keep 3072, tile the image (e.g., 1024×1024 patches), run ONNX per tile, then merge detections with NMS in C++; this is a common approach for microscopy. Also ensure preprocessing in C++ exactly matches Python (letterbox padding, RGB order, 1/255 scaling)—agree with @DennisJcy here. For backend choices and supported export targets, see the export formats table in Object Detection – Ultralytics YOLO Docs, and for high‑throughput GPU serving consider Triton Inference Server with YOLO11.

    2. Glenn JocherUltralytics

      Glad it helped—one extra tip for ONNX Runtime C++: enable full graph optimizations and tune threads to squeeze more speed from large inputs like 3072×2048.

      #include <onnxruntime_cxx_api.h>
      #include <thread>
      
      Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "yolo");
      Ort::SessionOptions so;
      so.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);
      so.SetIntraOpNumThreads(std::thread::hardware_concurrency());
      so.SetInterOpNumThreads(1);  // often fine to leave at 1
      
      Ort::Session session(env, "best.onnx", so);
  5. denni281GitHub(已编辑)

    Hello, I use ultratics to export YOLO11 half-Precision onnx model, but when I load the .onnx model to eval by onnxruntime, exception shows :Unexpected input data type. Actual: (tensor(float16)) , expected: (tensor(float)). And I compare the Float32 and Float16(half) .onnx model,These two files are exactly the same in size and input type.So the "half" keyword doesn't take effect when exporting ONNX, right? I remember Ultralytics didn't have this issue last year.

    Here is my python script to export half-precision onnx model:

    def main(opt):
        model = YOLO(opt.model)
        model.export(
            format="onnx",
            # opset=12,
            simplify=True,
            dynamic=False,
            imgsz=opt.imgsz,
            half=opt.half,
            batch=opt.batch,
        )
    
    
    if __name__ == "__main__":
        multiprocessing.freeze_support()
        parser = argparse.ArgumentParser()
        parser.add_argument(
            "--model",
            type=str,
            default="/home/ultralytics/runs/detect/SHFY/weights/best.pt",
        )
        parser.add_argument("--imgsz", type=int, default=640)
        parser.add_argument("--half", type=bool, default=True)
        parser.add_argument("--batch", type=int, default=1)
        opt, unparsed = parser.parse_known_args()
        print(opt)
        main(opt)
    
    1. denni281GitHub(已编辑)

      Fine... It's my fault. My docker environment is Python-3.11.9 torch-2.4.1+cu118 CPU (unknown). The error is made by my cpu environment

    2. Glenn JocherUltralytics(已编辑)

      @DennisJcy thanks for the update. On older releases half=True had no effect on CPU ONNX exports, so the file stayed FP32. Current Ultralytics uses quantize=16 (replacing the deprecated half) and also converts CPU ONNX exports to FP16 while keeping float32 inputs/outputs, whereas GPU exports (device=0) are FP16 natively and need an FP16-capable ONNX Runtime provider. For CPU-optimized FP16 you can also export OpenVINO. For example:

      from ultralytics import YOLO
      
      # FP16 ONNX
      YOLO("best.pt").export(format="onnx", quantize=16)
      
      # CPU-optimized FP16 (OpenVINO)
      YOLO("best.pt").export(format="openvino", quantize=16)

      Details on OpenVINO export are in the export_openvino reference.

  6. ShuaibZyxGitHub

    def yolo_to_onnx(model_path, input_shape=(600, 600)): # Load the YOLOv8 model model = YOLO(model_path)

    # Export the model to ONNX format
    model.export(format='onnx', 
                 imgsz=input_shape,
                 dynamic=True,
                 batch=1,
                 device="0")

    Ultralytics YOLOv8.0.220 🚀 Python-3.9.18 torch-2.1.1+cu121 CUDA:0 (Tesla T4, 14931MiB) Model summary (fused): 268 layers, 43610463 parameters, 0 gradients, 164.8 GFLOPs

    PyTorch: starting from 'best.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 9, 8400) (83.6 MB)

    ONNX: starting export with onnx 1.18.0 opset 17... ONNX: export success ✅ 3.3s, saved as 'best.onnx' (166.5 MB) 我的模型在训练时是5个类别的目标检测,导出的模型的输出格式是(1, 9, 8400)。 我想请问您其中9具体代表的是什么呢? 如果是为了预测5个类别(1, 9, 8400)的输出格式是正确的嘛? 期待您的帮助!感谢!

    1. xiaoqiang-lGitHub

      9指的是:[x,y,w,h,class1_scores,class2_scores,class3_scores,class4_scores,class5_scores],即四个坐标及N个类别分数。 8400指的是:640下采样8倍、16倍、32倍特征图的anchor总数,(640/8)(640/8)+(640/16)(640/16)+(640/32)(640/32)=8080+4040+2020=8400

    2. Glenn JocherUltralytics

      @ShuaibZyx you're welcome! @xiaoqiang-l provided an excellent explanation. Just to confirm, the output shape (1, 9, 8400) is indeed correct for your 5-class detection model - the 9 channels represent the 4 bounding box coordinates (x, y, w, h) plus 5 class confidence scores. The 8400 represents all detection anchors across the three feature map scales (80×80 + 40×40 + 20×20 = 8400 total anchors).

  7. UltralyticsAssistantGitHubUltralytics

    👋 Hello, thank you for your interest in Ultralytics 🚀! We recommend a visit to the Docs for new users where you can find many Python and CLI usage examples, as well as detailed guides about exporting YOLO models to ONNX and other formats.

    If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us debug it.

    If you have a custom training ❓ Question or require help with ONNX export, please include as much detail as possible—such as your command, model version, logs, and environment details. Also, check out our Tips for Best Training Results for optimal performance.

    Join the Ultralytics community where it suits you best! For real-time chat, head to Discord 🎧. For in-depth discussions, try Discourse, or join the conversation on our Subreddit.

    Upgrade

    Upgrade to the latest ultralytics package including all requirements in a Python>=3.8 environment with PyTorch>=1.8 to ensure you’re using the most up-to-date features and bug fixes:

    pip install -U ultralytics

    Environments

    YOLO can be run in these up-to-date verified environments, with all dependencies including CUDA/CUDNN, Python, and PyTorch preinstalled:

    Status

    Ultralytics CI

    If this badge is green, all Ultralytics CI tests are currently passing. CI tests verify correct operation of all YOLO Modes and Tasks on macOS, Windows, and Ubuntu every 24 hours and on every commit.

    This is an automated response 🤖. An Ultralytics engineer will review your discussion and assist you soon!

    1. Glenn JocherUltralytics

      Hello! Thanks for your interest in exporting YOLO11 models to ONNX format. This is a great option for deployment across different platforms with performance benefits.

      Exporting to ONNX is straightforward with Ultralytics:

      from ultralytics import YOLO
      
      # Load model
      model = YOLO("yolo11n.pt")  # or your custom trained model
      
      # Export to ONNX with optional parameters
      model.export(format="onnx", dynamic=True, simplify=True)  # creates 'yolo11n.onnx'
      
      # Use the exported model
      onnx_model = YOLO("yolo11n.onnx")
      results = onnx_model("https://ultralytics.com/images/bus.jpg")

      ONNX export can provide up to 3x CPU speedup compared to PyTorch models. You can customize the export with several parameters like half=True for FP16 precision, dynamic=True for variable input sizes, or opset to specify the ONNX version.

      For deployment, you can use ONNX Runtime or integrate with platforms like NVIDIA Triton Inference Server for production-scale serving.

      If you have specific questions about exporting your models or encounter any issues during the process, please let us know!

  8. UltralyticsAssistantGitHubUltralytics

    👋 Hello, thank you for your interest in Ultralytics 🚀! For users exploring ONNX integration and YOLO11, we recommend checking out the Docs where you’ll find dedicated Python and CLI tutorials, as well as specific ONNX integration guidance.

    If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us investigate further.

    For custom deployment or export ❓ questions, please include as many details as possible, such as your export commands, model versions, and error logs. Make sure you review our Tips for Best Training Results for optimal performance.

    Join the Ultralytics community where it suits you best: jump into real-time conversations on Discord 🎧, post or search on Discourse, or connect on our Subreddit.

    Upgrade

    Upgrade to the latest ultralytics package, including all requirements, in a Python>=3.8 environment with PyTorch>=1.8 to ensure you have the latest features and fixes:

    pip install -U ultralytics

    Environments

    YOLO can be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

    Status

    Ultralytics CI

    If this badge is green, all Ultralytics CI tests are currently passing. CI tests verify correct operation of all YOLO Modes and Tasks on macOS, Windows, and Ubuntu every 24 hours and on every commit.

    This is an automated response. An Ultralytics engineer will assist you here soon!

    1. Glenn JocherUltralytics

      Yes, you can adjust the batch size dynamically when exporting to ONNX format by using the dynamic=True parameter in your export call. When this is enabled, the batch dimension becomes dynamic, allowing you to use various batch sizes during inference without reexporting the model.

      Here's a simple example:

      from ultralytics import YOLO
      
      # Load your model
      model = YOLO("yolo11n.pt")
      
      # Export with dynamic input size
      model.export(format="onnx", dynamic=True)

      This creates dynamic dimensions in the exported ONNX model, where the batch dimension (as well as height and width) can vary during inference. The resulting model will be more flexible for production deployments where batch size requirements might change.

  9. skyceeeeGitHub

    First of all, thank you for everything. Can we adjust the batch size dynamically when exporting the model as onnx?

  10. xiaoqiang-lGitHub

    When I export the YOLOV11 onnx model, I use: model.export(format='onnx', imgsz=640, device='cpu'). Then I use onnxruntime (1.14.0) to deploy it on the C++ side, but an error is reported during runtime: onnxruntime::Model::Model Unsupported model IR version: 9, max supported IR version: 8. Is there any parameter or method to set the exported model to support IR version: 8? Because I cannot upgrade onnxruntime to other higher versions locally, I look forward to your help

    1. Glenn JocherUltralytics

      @xiaoqiang-l to resolve the ONNX IR version compatibility issue, you can specify an older opset version during export. Try adding opset=13 to your export command:

      model.export(format='onnx', imgsz=640, device='cpu', opset=13)

      This will generate an ONNX model compatible with IR version 8. For detailed version mapping, see the ONNX operator version matrix in the ONNX documentation.