YOLO26モデルのONNXエクスポート
ONNX(Open Neural Network Exchange)は、ほとんどの推論ランタイムで読み込めるオープンなモデル形式です。Ultralytics YOLO26モデルを format="onnx" でエクスポートすると、単一の .onnx ファイルが作成され、CPU、NVIDIAおよびAMDのGPU、Appleシリコン、Windowsデバイス上でONNX Runtimeを使用して実行できます。
概要#
| プロパティ | 詳細 |
|---|---|
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です |
| エクスポートホスト | GPUの有無を問わず、Linux、macOS、またはWindows |
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の7つすべてのタスクに対応しています。物体検出、インスタンスセグメンテーション、セマンティックセグメンテーション、深度推定、分類、姿勢推定、OBBに対応しています。セマンティックセグメンテーションと深度推定は、これらのヘッドを搭載する唯一のファミリーであるYOLO26でのみ利用できます。
エクスポート引数#
| 引数 | 種類 | デフォルト | 説明 |
|---|---|---|---|
format | str | 'onnx' | エクスポートしたモデルのターゲットフォーマットです。さまざまなデプロイ環境との互換性を定義します。 |
imgsz | intまたはtuple | 640 | モデル入力の画像サイズです。正方形の画像には整数を、タプルには (height, width) を指定します。指定しない場合、エクスポートではチェックポイントの学習時に使用されたサイズが使われます。公式YOLO26チェックポイントでは、検出、セグメンテーション、姿勢推定、およびADE20Kで事前学習したセマンティックモデルには 640、OBBおよびCityscapesで事前学習したセマンティックモデルには 1024、深度推定には 768、分類には 224 が使用されます。 |
quantize | intまたはstr | None | 量子化精度です。16(FP16。CPUエクスポートでは入出力をFP32のまま維持し、GPUエクスポートでは入出力もFP16にします)、または 8(data のキャリブレーション画像を使用したONNX RuntimeによるINT8静的量子化で、_int8.onnx モデルを生成します)を指定します。32 または未指定の場合はFP32です。quantize=8 で学習したチェックポイントは、quantize を未指定にするか 8 にするとINT8でエクスポートされます(その他の値ではエラーになります)。チェックポイントに含まれる範囲からQ/DQノードを生成するため、キャリブレーションは不要で、通常の .onnx という名前が使用されます。非推奨の half/int8 フラグを置き換える引数です。 |
data | str | None | INT8キャリブレーションに使用するデータセットYAMLです。分類タスクでは、代わりにデータセットディレクトリまたは組み込みデータセット名を指定します。quantize=8を指定せず、quantize=8でトレーニングしたチェックポイントを使用する場合、Ultralyticsはモデルのタスクに応じたデフォルトのキャリブレーションデータセットを選択します。チェックポイントにはキャリブレーションデータセットは不要です。 |
fraction | float、int、またはlist | 1.0 | キャリブレーション用サブセットを、比率、画像数、または[train, val, test]の比率/件数として指定します。2項目のリストではtestがすべて含まれ、0では除外されます。 |
dynamic | bool | False | 入力のバッチ、高さ、幅を動的軸にするため、1つのファイルで異なるバッチサイズ(エクスポート時の batch まで。nms=True と併用)と画像サイズを受け付けます。動的エクスポートを参照してください。 |
simplify | bool | True | onnxslim を使用してモデルグラフを簡略化します。 |
opset | int | None | 異なるONNXパーサーおよびランタイムとの互換性を確保するため、ONNX opsetバージョンを指定します。指定しない場合は、opset 18(PyTorch < 2.4ではそれより低い値)が使用され、インストール済みの onnx バージョンが上限になります。最小opsetを参照してください。 |
nms | bool、省略可 | None | raw出力(None、デフォルト)、NMSを組み込んだ出力(True)、またはNMS-freeヘッド(False)を選択します。出力形式を参照してください。 |
batch | int | 1 | エクスポートするモデルのバッチサイズです。静的エクスポートでは、入力形状のバッチサイズが固定されます。dynamic=True と nms=True を使用する場合は、実行予定の最大バッチサイズを設定してください。 |
device | str | None | エクスポートに使用するデバイスです。cpu(デフォルト。GPU搭載マシンでも同様)、CUDA GPUの場合は 0、Appleシリコンの場合は mps を指定します。結果が変わるのは quantize=16 の場合のみです。FP16入力を参照してください。 |
すべての形式に共通する引数については、エクスポートモードのドキュメントを参照してください。
INT8量子化#
量子化を考慮した学習で学習されていないチェックポイントの場合、quantize=8は、ONNX Runtimeの静的量子化をConv、Gemm、MatMulノードにのみ適用します。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、0~1の範囲の float32 が使用されます。
INT8モデルはFP32モデルの入力型と出力型を維持するため、FP32モデル向けに書かれた推論コードを変更せずに実行できます。INT8ではファイルサイズがFP32の3分の1から4分の1になりますが、ベンチマークでは、GPUとCPUのどちらでもONNX Runtimeでの実行速度がFP32より遅くなりました。精度を選択する前に、対象ハードウェアでレイテンシを測定してください。
出力形式#
エクスポートしたモデルは、images という名前の入力を1つ受け取り、形状は (batch, 3, height, width)、RGB形式で0~1にスケーリングされています。入力型は float32 ですが、quantize=16 を使用してGPU向けにエクスポートした場合は float16 になります。nms 引数で output0 のレイアウトを設定します。以下の形状は、80クラス、imgsz=640 でエクスポートしたYOLO26n検出モデルのものです。
nms | output0 の形状 | 内容 |
|---|---|---|
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-freeヘッドです。各行は x1, y1, x2, y2, score, class で、NMS処理はありません。スコアに基づく行のフィルタリングは自分で行ってください。 |
その他のタスクでは、同じ入力と以下の出力が使用されます。以下の形状は、セマンティックセグメンテーション用のCityscapesチェックポイント yolo26n-sem.pt を含む、公式YOLO26nチェックポイントのデフォルトのエクスポートサイズに基づいています。
| タスク | デフォルトの imgsz | nms=None を使用した出力 | nms=False または nms=True を使用した出力 |
|---|---|---|---|
| Detect | 640 | output0 (1, 84, 8400) | output0 (1, 300, 6) |
| Segment | 640 | output0 (1, 116, 8400), output1 (1, 32, 160, 160) | output0 (1, 300, 38), output1 (1, 32, 160, 160) |
| セマンティック | 1024 | output0 (1, 1024, 1024)。各ピクセルのクラスインデックスを示す uint8 | nms=Noneと同じ |
| 深度 | 768 | output0 (1, 1, 768, 768)。深度マップ | nms=Noneと同じ |
| 分類 | 224 | output0 (1, 1000)。softmax適用後のクラス確率 | nms=False では nms=None と同じです。nms=True ではエラーが発生します |
| 姿勢推定 | 640 | output0 (1, 56, 8400) | output0 (1, 300, 57):ボックス値6個に続いて、キーポイント17個の各x 3 |
| OBB | 1024 | output0 (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 | 実行プロバイダー |
|---|---|
cpu | CPUExecutionProvider |
NVIDIA GPU上の 0 | CUDAExecutionProvider。初回使用時にインストールされる onnxruntime-gpu パッケージから利用できます |
AMD ROCm GPU上の 0 | MIGraphXExecutionProvider。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のスレッド数を、プロセスで利用可能な物理CPUコア数が8未満の場合はその数に、それ以外の場合は8つのintra-opスレッドに制限します。別の数を使用するには、
ORT_INTRA_OP_NUM_THREADS環境変数を設定してください。
dnn=True を predict または val に渡すと、ONNX Runtimeの代わりにOpenCV DNNを使用してCPU上でモデルを実行できます。OpenCV DNNが対応するエクスポートオプションは少ないため、制限事項とトラブルシューティングを参照してください。
Ultralyticsパッケージ以外でモデルを実行するには、以下のリソースを参照してください。
- ONNX Runtime Python API:PythonでONNXモデルを読み込んで実行します。
- ONNX Runtime実行プロバイダー:CUDA、TensorRT、OpenVINO、Core ML、DirectMLなどのハードウェアバックエンドです。
- Ultralyticsのサンプル:Python、C++、RustでのONNX Runtime推論、およびPythonでのOpenCV DNN推論です。
- Triton Inference Server:NVIDIA Tritonを使用して、ONNXモデルをHTTPまたはgRPC経由でサービングします。
- エッジデバイスへのデプロイ:IoTおよびエッジハードウェア向けのONNX Runtimeチュートリアルです。
Windows MLによる推論#
Python 3.10以降を使用し、Windows 11 24H2(ビルド 26100)以降であれば、別の環境にonnxruntime-windowsmlをインストールして、ハードウェアに適したWindows MLの実行プロバイダーを選択できます。他のONNX Runtimeビルドの代わりにこれをインストールし、同じエクスポート済みの.onnxモデルをYOLO("model.onnx")で使用してください。このバックエンドは、PyTorchのスレッド数と、明示的なプロバイダーポリシーを含む指定済みのセッションオプションを保持します。ポリシーを指定しない場合、PyTorchのデバイスがcpuであっても、Windows MLは最大のパフォーマンスが得られるハードウェアを選択します。このランタイムを選択する前に、使用するデバイスで予測レイテンシを測定してください。このランタイムはオプションであり、デフォルトではインストールされません。
CPUと電力を共有する内蔵GPUでは、前処理と後処理で待機中のPyTorchスレッドにより、Windows MLの推論が遅くなる場合があります。推論の前にtorch.set_num_threads(1)を呼び出すと、これを軽減できます。この設定はプロセス全体に適用されるため、そのプロセス内の他のPyTorchモデルも1スレッドで実行されます。
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実行プロバイダーを通じて、エクスポート済みONNXモデルをAMD GPU上で実行できます。x86-64上でPython 3.11以降を使用するROCm(HIP)システムでは、初回使用時に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入力と出力を維持し、グラフ内で変換します。GPUとCPUの両方で、YOLO()は適切な入力型を渡します。 - 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-freeヘッド:
nms=Falseには、YOLO26やYOLOv10など、NMS-freeヘッドを持つモデルが必要です。YOLO11などのその他のモデルでは、エクスポート時にThis model has no one-to-one head; using one-to-many outputsの警告が表示され、rawの(1, 84, 8400)出力が書き込まれます。 - GPUが使用されない:ログに
CUDA requested but CUDAExecutionProvider not available. Using CPU...と表示される場合、インストール済みのONNX Runtimeビルドには、正常に動作するCUDAプロバイダーがありません。onnxruntimeの代わりにonnxruntime-gpuをインストールし、その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 Runtimeリリースでもファイルを読み込めるように、エクスポーターはONNX IRバージョンを10以下に制限します。opset 18でのデフォルトエクスポートでは、IRバージョンは8です。
その他のエラーについては、よくある問題のガイドを参照してください。
ベンチマーク#
YOLO26nは、CPU(Intel Xeon CPU @ 2.00 GHz)上でONNX Runtimeを使用した場合、YOLO11nより最大43%高速に動作します。YOLO26モデルページには、セマンティックセグメンテーションを除くすべてのタスクについて、各モデルのCPUでのONNX速度が掲載されています。
視聴: Ultralytics YOLO26とUltralytics YOLO11のONNX推論テスト | YOLO26で推論を約43%高速化 🚀
ONNX RuntimeでのFP32、FP16、INT8#
以下の表では、ONNX Runtime CUDAExecutionProvider で実行した、すべてのYOLO26検出モデルのPyTorchとFP32、FP16、INT8のONNXモデルを比較しています。すべてのGPU値は、NVIDIA RTX PRO 6000 Blackwell Server Edition GPU 1台で測定しました。
画像1枚あたりのミリ秒数です。値が小さいほど高速です。各モデルで最速の形式を太字で示しています。
| モデル | imgsz | PyTorch | ONNX FP32 | ONNX FP16 | ONNX INT8 |
|---|---|---|---|---|---|
| YOLO26n | 640 | 2.85 | 1.96 | 1.88 | 3.73 |
| YOLO26s | 640 | 2.98 | 2.14 | 1.73 | 4.31 |
| YOLO26m | 640 | 3.29 | 3.01 | 2.14 | 5.37 |
| YOLO26l | 640 | 4.70 | 4.09 | 3.08 | 7.51 |
| YOLO26x | 640 | 5.93 | 5.56 | 3.90 | 9.38 |
CPU上のYOLO26n(AMD EPYC 9655、PyTorchとONNX Runtimeはいずれも8スレッド。YOLO26モデルの表で使用したものとは異なるCPUです):
| 指標 | PyTorch | ONNX FP32 | ONNX FP16 | ONNX INT8 |
|---|---|---|---|---|
| レイテンシ(ms/画像) | 13.2 | 13.4 | 13.2 | 56.5 |
| mAPval 50-95 | 40.8 | 40.9 | 40.9 | 38.7 |
- FP16ではファイルサイズが半分になり、FP32とのmAP差は0.1以内で、GPUではFP32より最大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などの組織とともに開発されています。ONNXは機械学習モデル向けに、共通の演算子セットとファイル形式を定義しているため、PyTorchなどの1つのフレームワークで学習したモデルを、さまざまなランタイムやハードウェアプラットフォームで実行できます。
ONNX Runtimeは、ONNXモデル向けのクロスプラットフォーム推論エンジンです。実行プロバイダーはハードウェア固有のライブラリを使用し、CPU、GPU、専用アクセラレーターでモデルを実行します。
ONNXは、TensorRTなど、ほかのUltralyticsエクスポート形式への中間形式でもあり、Huawei Ascend、Qualcomm QNN、Rockchip RKNNなど、ベンダーのNPUツールチェーンへの入力にもなります。仕様については、ONNXドキュメントをご覧ください。
よくある質問#
ランタイムで特定のバージョンが必要な場合を除き、
opsetは未設定のままにしてください。エクスポーターは、PyTorch 2.4以降ではopset18、PyTorch 1.13~2.3ではopset17を使用し、それより古いPyTorchバージョンではより低いopsetを使用します。また、インストール済みのonnxパッケージがサポートする値を超えることはありません。既定値は18で止まります。これは、ONNX RuntimeのCUDAプロバイダーが、opset 19以降の一部の演算子(Resizeなど)をCPUで実行するためです。古いランタイムやコンバーターで既定値が拒否される場合は、たとえば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は(batch, 84, anchors)の形状のoutput0となるため、推論時に同じファイルで異なるバッチサイズと画像サイズを扱えます。nms=Trueを指定すると、バッチサイズはエクスポート時に使用したbatchの値に制限されます。高さと幅は、モデルのストライドの倍数である必要があります。公式YOLO26チェックポイントでは、分類モデルを除き32です。動的モデルはCUDAでIOバインディングを使用せず、OpenCV DNNでは読み込めないため、入力サイズが固定の場合は既定の静的エクスポートを使用してください。動的エクスポートfrom ultralytics import YOLO model = YOLO("yolo26n.pt") model.export(format="onnx", dynamic=True)異なるハードウェアで1つのファイルを実行する必要がある場合や、エクスポートに使用したマシンとは別のマシンにデプロイする場合は、ONNXを使用してください。特定のNVIDIA GPUで最小のレイテンシーを実現するには、TensorRTを使用してください。TensorRTエンジンは特定のGPUアーキテクチャとTensorRTバージョン向けにビルドされるため、移植できません。ほかのターゲットについては、モデルデプロイオプションガイドをご覧ください。
コメント77
質問したり、結果を共有したり、ほかの人をサポートしたりできます。
dopeggguy
The parameter "half" bost apperence in train and export, what’s difference. when we using this parameter what should we need attention.
Glenn JocherUltralytics(編集済み)@dopeggguy Good question—summary: training uses mixed precision via
amp=True(weights stay FP32; compute is FP16 where safe), while export usesquantize=16(the formerhalf=True, now deprecated) to write an FP16 model for runtimes that support FP16. During training preferamp; 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 thequantizeoption 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)dopeggguy
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.
Glenn JocherUltralytics(編集済み)@dopeggguy
half=Trueis deprecated in favor ofquantize=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
onnxPython API to confirm the weights arefloat16; 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.
bastinj98
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 ?
NgZiming
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?
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 函数参考.1NgZiming
thanks
Glenn JocherUltralyticsGlad it helped—if you later need a C++ reference for segmentation mask decoding and preprocessing alignment, the step-by-step overview is in the Segmentation task docs.
UserI 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?
denni281
You should keep the same preprocess way between python-inference and cpp-inference.
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 desiredIf 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.
UserThank you very much!
Glenn JocherUltralyticsGlad 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);
denni281(編集済み)
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)denni281(編集済み)
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
Glenn JocherUltralytics(編集済み)@DennisJcy thanks for the update. On older releases
half=Truehad no effect on CPU ONNX exports, so the file stayed FP32. Current Ultralytics usesquantize=16(replacing the deprecatedhalf) 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.
ShuaibZyx
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)的输出格式是正确的嘛? 期待您的帮助!感谢!
xiaoqiang-l
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
ShuaibZyx
感谢您的指导!
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).
UltralyticsAssistantUltralytics
👋 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
ultralyticspackage 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 ultralyticsEnvironments
YOLO can be run in these up-to-date verified environments, with all dependencies including CUDA/CUDNN, Python, and PyTorch preinstalled:
- Notebooks with free GPU:
- Google Cloud Deep Learning VM. See GCP Quickstart Guide
- Amazon Deep Learning AMI. See AWS Quickstart Guide
- Docker Image. See Docker Quickstart Guide
Status
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!
Glenn JocherUltralyticsHello! 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=Truefor FP16 precision,dynamic=Truefor variable input sizes, oropsetto 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!
- Notebooks with free GPU:
UltralyticsAssistantUltralytics
👋 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
ultralyticspackage, 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 ultralyticsEnvironments
YOLO can be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):
- Notebooks with free GPU:
- Google Cloud Deep Learning VM. See GCP Quickstart Guide
- Amazon Deep Learning AMI. See AWS Quickstart Guide
- Docker Image. See Docker Quickstart Guide
Status
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!
Glenn JocherUltralyticsYes, you can adjust the batch size dynamically when exporting to ONNX format by using the
dynamic=Trueparameter 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.
- Notebooks with free GPU:
skyceeee
First of all, thank you for everything. Can we adjust the batch size dynamically when exporting the model as onnx?
xiaoqiang-l
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
Glenn JocherUltralytics@xiaoqiang-l to resolve the ONNX IR version compatibility issue, you can specify an older
opsetversion during export. Try addingopset=13to 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.
