はじめる

Ultralytics YOLO11向けSony IMX500エクスポート

このガイドでは、Sony IMX500センサーを搭載したRaspberry Pi AI CameraへのUltralytics YOLOv8nおよびYOLO11nモデルのエクスポートとデプロイについて説明します。

Raspberry Pi AI Cameraのような計算能力に制約のあるデバイスにコンピュータービジョンモデルをデプロイするのは、難しい場合があります。より高速なパフォーマンスに最適化されたモデル形式を使用すると、大きな違いが生まれます。

IMX500モデル形式は、ニューラルネットワークで高速なパフォーマンスを実現しながら、消費電力を最小限に抑えるように設計されています。Ultralytics YOLO11モデルを最適化し、高速かつ低消費電力で推論できます。このガイドでは、モデルをIMX500形式にエクスポートしてRaspberry Pi AI Cameraにデプロイする手順を説明します。

Raspberry Pi AI Camera with Sony IMX500 sensor

IMX500にエクスポートする理由#

SonyのIMX500インテリジェントビジョンセンサーは、センサー自体でAI処理を実行します。Sonyは、これをインテリジェントビジョンセンサーとして世界初と説明しています。データ処理のボトルネック、プライバシーへの懸念、性能上の制約など、一般的なエッジAIの課題の解決に役立ちます。 従来のセンサーが画像やフレームを送信するだけなのに対し、IMX500は撮影した内容を解釈できるため、デバイスはリアルタイムでインサイトを生成できます。

YOLO11モデル向けSony IMX500エクスポート#

IMX500は、処理のためにデータをクラウドへ送信せず、センサー上で直接処理するように設計されています。

IMX500は量子化モデルに対応しています。量子化により、精度を大きく損なうことなくモデルを小型化し、高速化できます。エッジコンピューティングの限られたリソースに適しており、レイテンシを削減し、クラウドに依存せずローカルで迅速にデータを処理することで、アプリケーションの応答性を高めます。ローカル処理ではユーザーデータをリモートサーバーへ送信しないため、プライバシーとセキュリティも確保できます。

IMX500の主な特長:

  • メタデータ出力: IMX500は画像だけでなく、画像とメタデータ(推論結果)の両方を出力できます。また、データサイズ、帯域幅、コストを削減するために、メタデータのみを出力することもできます。
  • プライバシーの懸念に対応: デバイス上でデータを処理するIMX500は、プライバシーに関する懸念に対応できるため、人数カウントや在席状況の追跡など、人を中心とするアプリケーションに適しています。
  • リアルタイム処理: センサー上での高速処理により、自律システムなどのエッジAIアプリケーションでリアルタイムの意思決定を支援します。

始める前に: 最適な結果を得るには、モデルのトレーニングガイド、データセットの概要、ハイパーパラメーターのチューニングガイドに従って、YOLO11モデルをエクスポート用に適切に準備してください。

対応タスク#

IMX500エクスポートは、7つあるUltralyticsタスクのうち4つに対応しており、対象はYOLOv8nとYOLO11nのみです。それ以外のモデルファミリー、スケール、アーキテクチャはサポートされていません。また、セマンティックセグメンテーション、OBB、深度推定モデルをエクスポートするとエラーが発生します。

タスクYOLOv8YOLO11YOLO26
検出✅✅❌
セグメンテーション✅✅❌
セマンティック❌❌❌
深度❌❌❌
分類✅✅❌
姿勢推定✅✅❌
OBB❌❌❌

使用例#

Ultralytics YOLO11モデルをIMX500形式にエクスポートし、エクスポートしたモデルで推論を実行します。

IMX500形式は、エクスポート、予測、検証の各モードをサポートしています。Ultralyticsの推論と検証では、エクスポートされた model_imx.onnx をホストCPU上で実行します。

注

ここでの推論は、Raspberry Pi AI Cameraへのデプロイ前に、エクスポートしたモデルが想定どおりに動作することを確認するためだけに行います。

物体検出
from ultralytics import YOLO

# YOLO11n PyTorchモデルを読み込みます
model = YOLO("yolo11n.pt")

# モデルをエクスポートする
model.export(format="imx", data="coco8.yaml")  # デフォルトでPTQ量子化を使ってエクスポートします

# エクスポートしたモデルを読み込みます
imx_model = YOLO("yolo11n_imx_model")

# 推論を実行
results = imx_model("https://ultralytics.com/images/bus.jpg")
姿勢推定
from ultralytics import YOLO

# YOLO11n-pose PyTorchモデルを読み込みます
model = YOLO("yolo11n-pose.pt")

# モデルをエクスポートする
model.export(format="imx", data="coco8-pose.yaml")  # デフォルトでPTQ量子化を使ってエクスポートします

# エクスポートしたモデルを読み込みます
imx_model = YOLO("yolo11n-pose_imx_model")

# 推論を実行
results = imx_model("https://ultralytics.com/images/bus.jpg")
分類
from ultralytics import YOLO

# YOLO11n-cls PyTorchモデルを読み込みます
model = YOLO("yolo11n-cls.pt")

# モデルをエクスポートする
model.export(format="imx", data="imagenet10")  # デフォルトでPTQ量子化を使ってエクスポートします

# エクスポートしたモデルを読み込みます
imx_model = YOLO("yolo11n-cls_imx_model")

# 推論を実行
results = imx_model("https://ultralytics.com/images/bus.jpg", imgsz=224)
インスタンスセグメンテーション
from ultralytics import YOLO

# YOLO11n-seg PyTorchモデルを読み込みます
model = YOLO("yolo11n-seg.pt")

# モデルをエクスポートする
model.export(format="imx", data="coco8-seg.yaml")  # デフォルトでPTQ量子化を使ってエクスポートします

# エクスポートしたモデルを読み込みます
imx_model = YOLO("yolo11n-seg_imx_model")

# 推論を実行
results = imx_model("https://ultralytics.com/images/bus.jpg")
検証
from ultralytics import YOLO

# エクスポートしたIMX500モデルを読み込みます
model = YOLO("yolo11n_imx_model")

# COCO8データセットで精度を検証します
metrics = model.val(data="coco8.yaml")
警告

IMXのエクスポートは、Python 3.10~3.12を使用するLinuxでのみサポートされており、Java 17以降が必要です。Ultralyticsパッケージは、実行時にエクスポート用の追加依存関係をインストールします。エクスポートコマンドを初めて実行したときは、正しく動作するようにコンソールを再起動する必要がある場合があります。

エクスポート引数#

引数種類デフォルト説明
formatstr'imx'エクスポートしたモデルのターゲットフォーマットです。さまざまなデプロイ環境との互換性を定義します。
imgszintまたはtuple640モデル入力の画像サイズです。正方形画像の場合は整数、特定のサイズの場合はタプル(height, width)を指定できます。
quantizeintまたはstr8/自動量子化の精度。IMX500では8(INT8/PTQ)が必須で、自動的に有効になります。FP32のみ、またはFP16のみのエクスポートには対応していません。非推奨のhalf/int8フラグに代わるものです。
datastrNone量子化に必須となるデータセットのYAMLファイルへのパスです。分類の場合は、データセットディレクトリまたは組み込みデータセット名を指定します。省略すると、Ultralyticsはモデルのタスクに応じたデフォルトのキャリブレーションデータセットを選択します。
fractionfloat、int、またはlist1.0キャリブレーション用サブセットを、比率、画像数、または[train, val, test]の比率/件数として指定します。2項目のリストではtestがすべて含まれ、0では除外されます。
nmsbool、省略可None生の出力(デフォルトのNone)、NMS組み込み(True)、またはNMSフリーヘッド(False)を選択します。IMXではdetect、segment、poseにnms=Trueが必要で、自動的に選択されます。
devicestrNoneエクスポートに使用するデバイスを指定します。GPU(device=0)またはCPU(device=cpu)を指定できます。

エクスポートプロセスの詳細については、Ultralyticsのエクスポートに関するドキュメントページをご覧ください。

エクスポート処理では、<model-name>_imx_modelという名前のディレクトリが作成されます。このディレクトリには、量子化の検証に使用するmodel_imx.onnxと、IMX500ハードウェアへのデプロイ用にモデルをパッケージ化するために必要なpackerOut.zipファイルが含まれます。また、<model-name>_imx_modelフォルダーには、モデルに関連付けられたすべてのラベルを記載したテキストファイル(labels.txt)が含まれます。

フォルダー構成
yolo11n_imx_model
├── dnnParams.xml
├── labels.txt
├── packerOut.zip
├── model_imx.onnx
├── model_imx_MemoryReport.json
└── model_imx.pbtxt

デプロイでのIMX500エクスポートの使用#

Ultralytics YOLO11nモデルをIMX500形式にエクスポートした後、推論用にRaspberry Pi AI Cameraへデプロイできます。

ハードウェアの前提条件#

次のハードウェアがあることを確認してください。

  1. Raspberry Pi 5またはRaspberry Pi 4 Model B
  2. Raspberry Pi AI Camera

Raspberry Pi AI CameraをRaspberry Piの15ピンMIPI CSIコネクターに接続し、Raspberry Piの電源を入れます。

ソフトウェアの前提条件#

注

このガイドは、Raspberry Pi 5上で動作するRaspberry Pi OS Bookwormを使用してテストされています。

手順1: ターミナルウィンドウを開き、次のコマンドを実行してRaspberry Piのソフトウェアを最新バージョンに更新します。

sudo apt update && sudo apt full-upgrade

手順2: IMX500センサーの動作に必要なIMX500ファームウェアをインストールします。

sudo apt install imx500-all

ステップ3: Raspberry Piを再起動して、変更を適用します。

sudo reboot

ステップ4: AITRIOS Raspberry Piアプリケーションモジュールライブラリをインストールします。

pip install git+https://github.com/SonySemiconductorSolutions/aitrios-rpi-application-module-library.git

ステップ5: aitrios-rpi-application-module-libraryのサンプルで利用できる次のスクリプトを使用して、YOLO11による物体検出、ポーズ推定、分類、セグメンテーションを実行します。

注

これらのスクリプトを実行する前に、環境に合わせてmodel_fileディレクトリとlabels.txtディレクトリを置き換えてください。

Pythonスクリプト
import numpy as np
from modlib.apps import Annotator
from modlib.devices import AiCamera
from modlib.models import COLOR_FORMAT, MODEL_TYPE, Model
from modlib.models.post_processors import pp_od_yolo_ultralytics

class YOLO(Model):
    """YOLO model for IMX500 deployment."""

    def __init__(self):
        """Initialize the YOLO model for IMX500 deployment."""
        super().__init__(
            model_file="yolo11n_imx_model/packerOut.zip",  # replace with proper directory
            model_type=MODEL_TYPE.CONVERTED,
            color_format=COLOR_FORMAT.RGB,
            preserve_aspect_ratio=False,
        )

        self.labels = np.genfromtxt(
            "yolo11n_imx_model/labels.txt",  # replace with proper directory
            dtype=str,
            delimiter="\n",
        )

    def post_process(self, output_tensors):
        """Post-process the output tensors for object detection."""
        return pp_od_yolo_ultralytics(output_tensors)

device = AiCamera(frame_rate=16)  # Optimal frame rate for maximum FPS of the YOLO model running on the AI Camera
model = YOLO()
device.deploy(model)

annotator = Annotator()

with device as stream:
    for frame in stream:
        detections = frame.detections[frame.detections.confidence > 0.55]
        labels = [f"{model.labels[class_id]}: {score:0.2f}" for _, score, class_id, _ in detections]

        annotator.annotate_boxes(frame, detections, labels=labels, alpha=0.3, corner_radius=10)
        frame.display()

ベンチマーク#

以下のYOLOv8n、YOLO11n、YOLOv8n-pose、YOLO11n-pose、YOLOv8n-cls、YOLO11n-clsのベンチマークは、速度と精度を測定するため、UltralyticsチームがRaspberry Pi AI Camera上でimxモデル形式を使用して実施しました。

モデル形式サイズ(ピクセル)packerOut.zipのサイズ(MB)mAP50-95(B)推論時間(ms/im)
YOLOv8nimx6402.10.47058.79
YOLO11nimx6402.20.51758.82
YOLOv8n-poseimx6402.00.68758.79
YOLO11n-poseimx6402.10.78862.50
モデル形式サイズ(ピクセル)packerOut.zipのサイズ(MB)精度(top1)精度(top5)推論時間(ms/im)
YOLOv8n-clsimx2242.30.250.533.31
YOLO11n-clsimx2242.30.250.41733.31
注

上記のベンチマークの検証には、検出モデルにCOCO128データセット、ポーズ推定モデルにCOCO8-Poseデータセット、分類モデルにImageNet10を使用しました。

内部の仕組み#

Sony IMX500 YOLO model deployment workflow

Sonyモデル圧縮ツールキット(MCT)#

SonyのModel Compression Toolkit (MCT)は、量子化とプルーニングによってディープラーニングモデルを最適化するツールキットです。さまざまな量子化手法に対応し、精度を大きく損なうことなくモデルサイズと計算の複雑さを削減する高度なアルゴリズムを提供します。MCTは、リソースに制約のあるデバイスへのモデルのデプロイに特に有用であり、効率的な推論とレイテンシの削減を実現します。

MCTがサポートする機能#

SonyのMCTは、ニューラルネットワークモデルを最適化するために設計されたさまざまな機能を提供します。

  1. グラフの最適化: バッチ正規化などのレイヤーを前のレイヤーに統合し、モデルをより効率的な形式に変換します。
  2. 量子化パラメーターの探索: 平均二乗誤差、クリッピングなし、平均絶対誤差などの指標を使用して、量子化ノイズを最小限に抑えます。
  3. 高度な量子化アルゴリズム:
    • 負の値のシフト補正: 対称活性化量子化による性能上の問題に対処します。
    • 外れ値のフィルタリング: zスコアを使用して外れ値を検出し、除去します。
    • クラスタリング: 非一様量子化グリッドを使用して、分布の一致度を高めます。
    • 混合精度探索: 感度に基づいて、レイヤーごとに異なる量子化ビット幅を割り当てます。
  4. 可視化: TensorBoardを使用して、モデル性能に関する情報、量子化フェーズ、ビット幅の設定を確認します。

量子化#

MCTは、モデルサイズを縮小して推論速度を向上させるため、複数の量子化手法に対応しています。

  1. 学習後量子化(PTQ):
    • KerasおよびPyTorch APIから利用できます。
    • 複雑さ: 低
    • 計算コスト: 低(CPUで数分)
  2. 勾配ベースの学習後量子化(GPTQ):
    • KerasおよびPyTorch APIから利用できます。
    • 複雑さ: 中
    • 計算コスト: 中程度(GPUで2~3時間)
  3. 量子化対応トレーニング (QAT):
    • 複雑さ: 高
    • 計算コスト: 高(GPUで12~36時間)

MCTは、重みと活性化に対するさまざまな量子化方式にも対応しています。

  1. 2のべき乗(ハードウェアに適した形式)
  2. 対称
  3. 一様

構造化プルーニング#

MCTは、特定のハードウェアアーキテクチャ向けに設計された、構造化されたハードウェア対応のモデルプルーニングを導入しています。この手法では、SIMDグループをプルーニングすることで、ターゲットプラットフォームのSingle Instruction, Multiple Data (SIMD)機能を活用します。これにより、モデルサイズと複雑さを削減しながら、チャネルの利用効率を最適化し、重みのメモリ使用量を対象リソースに合わせてSIMDアーキテクチャに適合させます。KerasおよびPyTorch APIから利用できます。

IMX500コンバーターツール(コンパイラ)#

IMX500 Converter ToolはIMX500ツールセットに不可欠なコンポーネントで、SonyのIMX500センサー(Raspberry Pi AI Cameraなど)へのデプロイ用にモデルをコンパイルできます。量子化されたUltralytics YOLO11モデルを、ターゲットハードウェア上で効率的に実行できる形式にコンパイルします。量子化後のエクスポートでは、モデルデータとRaspberry Pi AI Cameraへのデプロイに必要なデバイス固有の構成を含むバイナリファイルが生成されます。

実際のユースケース#

IMX500形式へのエクスポートは、さまざまな業界で幅広く活用できます。例をいくつか紹介します。

  • エッジAIとIoT: 低消費電力デバイスでのリアルタイム処理が不可欠なドローンや監視カメラで、物体検出を実現します。
  • ウェアラブルデバイス: 健康状態をモニタリングするウェアラブルデバイスに、小規模なAI処理向けに最適化されたモデルをデプロイします。
  • スマートシティ: IMX500にエクスポートしたYOLO11モデルを交通監視や安全分析に活用し、処理を高速化してレイテンシを最小限に抑えます。
  • 小売分析: POSシステムやスマートシェルフに最適化されたモデルをデプロイし、店舗内のモニタリングを強化します。

結論#

Ultralytics YOLO11モデルをSonyのIMX500形式にエクスポートすると、IMX500ベースのカメラにデプロイして効率的に推論できます。量子化によってモデルサイズが縮小し、精度のわずかな低下にとどめながら推論速度が向上します。

詳細情報と詳しいガイドラインについては、SonyのIMX500ウェブサイトを参照してください。

よくある質問#

  • YOLO11モデルをIMX500形式でエクスポートするには、Python APIまたはCLIコマンドを使用します。

    from ultralytics import YOLO
    
    model = YOLO("yolo11n.pt")
    model.export(format="imx")  # デフォルトではPTQ量子化でエクスポートします

    エクスポート処理により、デプロイに必要なファイル(packerOut.zipなど)を含むディレクトリが作成されます。

  • IMX500形式には、エッジデプロイに役立つ重要な利点がいくつかあります。

    • チップ上でAI処理を行うため、レイテンシと消費電力を削減できます
    • 画像だけでなく、画像とメタデータ(推論結果)を出力します
    • クラウドに依存せずローカルでデータを処理するため、プライバシーが強化されます
    • 時間的制約のあるアプリケーションに適したリアルタイム処理機能を備えています
    • リソースが限られたデバイスへの効率的なモデルデプロイに向けて、量子化が最適化されています
  • IMX500モデルをデプロイするには、次のものが必要です。

    ハードウェア:

    • Raspberry Pi 5またはRaspberry Pi 4 Model B
    • IMX500センサー搭載のRaspberry Pi AI Camera

    ソフトウェア:

    • Raspberry Pi OS Bookworm
    • IMX500のファームウェアとツール(sudo apt install imx500-all)
  • Raspberry Pi AI CameraでのUltralyticsベンチマークに基づく結果は次のとおりです。

    • YOLO11nは、画像1枚あたり58.82msの推論時間を達成します
    • COCO128データセットでmAP50-95が0.517
    • 量子化後のモデルサイズはわずか2.2MBです

    この結果は、IMX500形式がエッジAIアプリケーションに十分な精度を維持しながら、効率的なリアルタイム推論を実現することを示しています。

コメント86

質問したり、結果を共有したり、ほかの人をサポートしたりできます。

  1. Chad Walsh

    where is the best place to get support on the IMX500. I am running into multiple issues: i. my first yolo11n model built fine and exported to imx500, no problem, but my second model with a LOT more training images build fine but crashed the imx500 export. ii. the output of the imx500 during inference is giving a lot of none outputs between solid recognitions. it seems like there is something interfering with or disrupting the inference outputs (e.g., good output, none, none, none, none, good output, ...). where is the best place to get help with these issues?

    1. Glenn JocherUltralytics

      Please continue the discussion here so the Ultralytics team can help; for the export crash, share the exact export command, full text traceback, and output from yolo checks, and for intermittent None results include a minimal inference script, confidence threshold, and a short reproducible input sample. Note that IMX export uses the calibration dataset specified by data and defaults to the full dataset, so testing a smaller fraction may help isolate resource-related failures.

  2. leeprevostGitHub

    I've made considerable progress by moving conducting this model compression process with a Container using dtcooper/raspberrypi-os:python3.11 after considerable problems with dependencies. Now getting a container most of the way through the process of compressing my yolov11s model and its trained best.pt weights.

    At the end of the process - I get a simple "killed" after the Calculation of quantization parameters step. I see memory spiking close to 100% on top and think I'm hitting OOM with my pi4 8gb.

    root@a5e132f6b333:/app# yolo export model=./models/yolov11/best.pt data='Billfish-Breeds-1/data.yaml' format=imx verbos>
    Ultralytics 8.3.221 🚀 Python-3.11.14 torch-2.9.0+cpu CPU (aarch64)
    WARNING ⚠️ IMX export requires nms=True, setting nms=True.
    YOLO11s summary (fused): 100 layers, 9,413,187 parameters, 0 gradients, 21.3 GFLOPs
    
    PyTorch: starting from 'models/yolov11/best.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) ((1, 8400, 4>
    IMX: collecting INT8 calibration images from 'data=Billfish-Breeds-1/data.yaml'
    Fast image access ✅ (ping: 0.1±0.0 ms, read: 16.1±2.7 MB/s, size: 16.4 KB)
    Scanning /app/Billfish-Breeds-1/valid/labels.cache... 268 images, 0 backgrounds, 0 corrupt: 100% ━━━━━━━━━━━━ 268/268 1>
    WARNING ⚠️ IMX: >300 images recommended for INT8 calibration, found 268 images.
    
    IMX: starting export with model_compression_toolkit 2.4.4...
    representative_data_gen generates a batch size of 1 which can be slow for optimization: consider increasing the batch s>
    WARNING:Model Compression Toolkit:OperatorSetNames.DEPTHWISE_CONV is not in model.
    Statistics Collection: 268it [1:01:26, 13.76s/it]
    Calculating quantization parameters: 100%|█████████████████████████████████████████████████████| 294/294 [12:44<00:00, >
    Killed

    Would appreciate any suggestion around this but think it probably pushes me over the edge to order my pi5? Or do I try to train on the yolov8 or yolov11n? I've not had very good success with the nano models. I've convinced myself the tradeoffs to the small is well worth it but that may be incompatible with this process?

    1. Glenn JocherUltralytics

      @leeprevost you’re in the right place for discussion, but the OOM during IMX export is a new issue—please open a new issue for visibility. In the issue, include: the exact export command and full log, yolo checks output (or ultralytics.utils.checks.collect_system_info()), Java version (java --version), and the versions of IMX toolchain (pip freeze | grep -E "imx500|model-compression|sony-custom"). As immediate workarounds: export on a Linux x86_64 machine with more RAM, target YOLO11n/YOLOv8n (the IMX path is tuned for “n” models), and reduce calibration load with fraction (e.g., 0.25). Example:

      yolo export model=best.pt format=imx data=your.yaml imgsz=640 fraction=0.25

      IMX-specific knobs are summarized in the IMX500 export arguments here: Sony IMX500 export guide – Export arguments, and the exporter function requirements here: export_imx reference.

    2. leeprevostGitHub

      a few more questions and I will open an issue:

      1. Note that I was using a model trained on yolov11s rather than n as I've seen large degradation in the number of false positives in my model.
      2. I assume by "full log" you mean the output from the yolo export command with verbose at default (true). In other words, what I posted above?
      3. For some reason, I thought I read int he docs that i had to perform the model compression on the target machine. for me, the ultimate target is RpiZero2 but no way the model will export on that footprint . so, I went to the largest pi I have which is a Rpi4 -- that resulted in the OOM. So, am unsure by your guidance pointing me to the larger x86 linux machine. How will the process know the device limits if I perform it on that?

      Trying to read these guides as best I can. I have not spent much time on the Sony site yet. If you'll point me, I don't want to start an issue that isn't an issue.

    3. Glenn JocherUltralytics(編集済み)

      @leeprevost great progress. IMX export/quantization does not need to run on the target; it cross-compiles for IMX500, so doing it on a larger Linux host is recommended. “Full log” means the complete stdout/stderr from the export run.

      The “No module named 'onnxscript'” failure is a missing dependency. Current Ultralytics installs the IMX toolchain (including imx500-converter and model-compression-toolkit) itself, so upgrade with pip install -U ultralytics and re-run the export rather than pinning old versions by hand. Let’s continue the deep-dive in the issue you opened for traceability.

    4. leeprevostGitHub

      Ok -- @glenn-jocher: am moving this to my opened issue. Still trying this on my pi4 but can move to my dev machine with plenty of RAM + Cuda. Got further but still died with a torch error -- will post there.

    5. Glenn JocherUltralytics

      Thanks—let’s continue in the issue for traceability. On the larger Linux host, try GPU-assisted export to reduce RAM pressure and speed up calibration; if needed, temporarily lower imgsz to validate the pipeline:

      yolo export model=path/to/best.pt format=imx data=path/to/data.yaml device=0 imgsz=640
      # if memory is still tight during calibration
      yolo export model=path/to/best.pt format=imx data=path/to/data.yaml device=0 imgsz=512

      For a concise list of export options and behavior, see the Export mode docs at Ultralytics YOLO — Export.

  3. leeprevostGitHub

    Much thanks for posting this guide. Thank you.

    I am having very solid success running the standard detection models right out of the box on the RpiZero 2 which is my target platform. I'm actually amazed at the power draw (ran detection/streaming for about 175 minutes on a 4400mahr battery using about 60% of its capacity). Also, very solid top/htop scores showing less than 1/8 of CPU utilization. Memory is still such a problem on a rpiz2 but not any more so than what is being used with streaming only on the pi. Still have about 50% of memory left over as I recall. I've got screen shots of top screens if needed.

    But, I need to get a trained model working on my RpiZ2 and am running into problems. As the guide seemed to indicate (or perhaps Sony's), I need to do most of the quantization on my target platform. I assumed that meant my zero. I have a very good model trained with yolov11m or large. I've tried to reduce that to a nano but I'm getting too much loss of MAP scores and too much false positive rates. So, am now trying to get a yolov11s to work. On my quantization process (it was not clear how to do this with a custom model) but am first loading the yolov11s.pt and then loading my best.pt on top of that. Ultralytics successfully loads my data, gives me a warning prompt about my 290 images (< 300 not ideal) and then another about processing speed with 1 batch. The program then goes off the rails with no UI messages. I assume I'm running out of memory on the piz2. So, my next steps seem to be either:

    1. Start over and try with nano model.
    2. Do my quantization on a larger pi (i've got a spare pi4).

    I guess another option would be to spend more time understanding Sony's under the hood tools to optimize those settings?

    Would appreciate some guidance here down the right path.

  4. leeprevostGitHub

    One thing that would be very helpful is to show how to do this on something other than the target platform. i'm trying to get a small detection model to run on a rpi zero2 and hate to have to download all of my training data to the zero to do the quantization.

    Idea: Have a step that allows collection of the "target_platform_capabilities" information using Sony's model compression toolkit you are using under the hood, pickle it, and then use that object to drive the model compression on a larger machine.

    I could probably dig in and try to follow your code and follow the "imx" part of your export process...

  5. bohlebotsGitHub

    Wie schaffe ich es, dass das Modell im Speicher des IMX500 bleibt? Die PICAM wurde ja angepriesen mit der Aussage, dass sie selbst an einem Pi zero-2 mit gleicher Geschwindigkeit läuft und in der Tat, das täte sie, aber das Modell muss jedes Mal neu aufgeladen werden, und das dauert beim Pi Zero ewig, ja selbst mit einem Pi5 dauert es Minuten. Grundsätzlich muss die imx500 aber ein Modell auch bei ausgeschaltetem Strom im Speicher halten können, so dass nach dem Anschalten das letzte Modell direkt zur Verfügung steht. Wie bekomme ich das hin?

    Gruß Roland

  6. Teo-trenyGitHub

    Hello ! When running object detection (step 5), I get the following error :

    Exception in thread Thread-2 (_process_requests_func):
    Traceback (most recent call last):
      File "/home/pi/.pyenv/versions/3.11.9/lib/python3.11/threading.py", line 1045, in _bootstrap_inner
        self.run()
      File "/home/pi/.pyenv/versions/3.11.9/lib/python3.11/threading.py", line 982, in run
        self._target(*self._args, **self._kwargs)
      File "/home/pi/Desktop/imx_test/venv/lib/python3.11/site-packages/modlib/devices/ai_camera/ai_camera.py", line 193, in _process_requests_func
        callback()
      File "/home/pi/Desktop/imx_test/venv/lib/python3.11/site-packages/modlib/devices/ai_camera/ai_camera.py", line 207, in _process_requests
        self._parse_request(req)
      File "/home/pi/Desktop/imx_test/venv/lib/python3.11/site-packages/modlib/devices/ai_camera/ai_camera.py", line 256, in _parse_request
        detections = self.model.post_process(outputs)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/pi/Desktop/imx_test/Test_1.py", line 23, in post_process
        return pp_od_yolo_ultralytics(output_tensors)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/home/pi/Desktop/imx_test/venv/lib/python3.11/site-packages/modlib/models/post_processors/post_processors.py", line 129, in pp_od_yolo_ultralytics
        n_detections = int(output_tensors[3])
                       ^^^^^^^^^^^^^^^^^^^^^^
    TypeError: only length-1 arrays can be converted to Python scalars

    I'm running Python 3.11.9 and installed all the dependencies following the guide. My Raspberry PI is a 3B+ model with Bookworm 64 bits and is up to date.

  7. aytacsekmenGitHub

    In the official IMX500 documentation provided by Sony (https://developer.sony.com/tinyml-23/developer-tools/documentation/imx500-evaluation-kit-user-guide?version=2023-11-28&progLang=), they describe the process of generating the network.fpk and network_info.txt files that will be used to deploy the model to IMX500, using the Packager.sh script. However, when I attempt to apply the same procedure to the packerOut.zip file I created by following the tutorial on https://docs.ultralytics.com/integrations/sony-imx500, I am unable to run the model on the IMX500. Also I couldn't run your implementation because it says that some packages are not found which I believe is related to the version of the OS. Currently I use the Pi OS that is provided by SONY for compatibility issues. I could run some other deep learning models following the steps in the (https://developer.sony.com/tinyml-23/developer-tools/documentation/imx500-evaluation-kit-user-guide?version=2023-11-28&progLang=), but I believe, there must be something different related to the creation of packerOut.zip file.

    Could you assist in resolving this issue with the conversion process? @glenn-jocher

  8. HelloCigarGitHub

    Hello, per picamera2 docs, creating apps with "a camera window embedded into the GUI is through Qt", is there no other way to embed the video feed in other GUI frameworks?

  9. skim-sonyGitHub

    Hi, I followed the steps in this page to convert the yolov8n model with imx500 converter and tested it with raspberry ai camera. But I get 29.5 ms for the inference time with 640x640 input tensor size. So I wonder why my inference time is better than your result (58.82ms). Which version of imx500 converter did you use?

    1. skim-sonyGitHub

      Also, how did you measure the inference time? Did you use imx500.get_kpi_info(metadata) or calculate the elapsed time of picam2.capture_metadata()?

    2. Glenn JocherUltralytics(編集済み)

      @skim-sony congratulations on the faster result! Our documented figure (58.82 ms for YOLO11n, see the Benchmarks) was measured by the Ultralytics team on a Raspberry Pi AI Camera with the imx format. Differences can come from the converter version, firmware, hardware (Pi 5 vs Pi 4) or how the time is measured. Would you mind sharing which converter version and Raspberry Pi model you're using? This could help other community members.

    3. skim-sonyGitHub(編集済み)

      Hi, I have used Pi5 and tried both 3.14.3 and 3.16.1 for imx500-converter. And both produces 29.5ms for inference time. It seems like you also use Pi5, so I wonder why our results are different. I'd like to reproduce your results 58.82 ms to learn what improves the inference time. So it would be helpful if you could share some info how to sync with your environment. Thanks!

    4. Glenn JocherUltralytics(編集済み)

      @skim-sony that's interesting you're seeing better performance! The discrepancy could be due to several factors:

      1. Measurement methodology: end-to-end time (pre/post-processing + inference) differs from model-only inference time
      2. Firmware and converter versions
      3. Image resolution and resizing
      4. Test conditions: background processes, temperature, and power settings

      Our published numbers are in the Benchmarks. If you'd like to share more details about your implementation, the community would certainly benefit.

  10. fraciprianoGitHub

    Hello, I'm trying to run the standard YOLOv8n model on a Raspberry Pi AI Camera. I followed the exemple in the documentation

    from ultralytics import YOLO
    
    # Load a YOLOv8n PyTorch model
    model = YOLO("yolov8n.pt")
    
    # Export the model
    model.export(format="imx", data="coco8.yaml")  # exports with PTQ quantization by default
    
    # Load the exported model
    imx_model = YOLO("yolov8n_imx_model")
    
    # Run inference
    results = imx_model("https://ultralytics.com/images/bus.jpg")

    I got a bunch of warnings during the execution (export_log.txt), but the imx_model seemed to work properly in the end.

    I then packaged it via IMX500 Packager and test it using the imx500_object_detection_demo.py. The Network Firmware gets uploaded, the application starts, but I get no detection. I tried to lower the detection threshold, but it didn't help. Any idea on what could be the problem? Any suggestion would be much appreciated.

    1. Glenn JocherUltralytics

      Thank you for the detailed issue. Let's troubleshoot step by step. First, ensure your Raspberry Pi AI Camera is correctly connected and recognized by running libcamera-hello in the terminal. If the camera works, verify that the labels.txt path in your demo command matches the exported file. You can also try inference on a static image first with imx_model.predict("test.jpg") to isolate live feed issues. For further assistance, please share the full export log and a screenshot of your camera output.

      For additional guidance, refer to the Sony IMX500 and AITRIOS integration blog post which demonstrates successful deployment steps.

    2. fraciprianoGitHub

      Hello @glenn-jocher,

      libcamera-hello works fine as does the imx500_object_detection_demo.py when using the default model ("/usr/share/imx500-models/imx500_network_ssd_mobilenetv2_fpnlite_320x320_pp.rpk").

      There seems to be no problem with the labels.txt file as, if a run the imx500_object_detection_demo.py specifying the path to my label.txt, it works fine.

      The imx_model also works fine before the packaging.

      Here a screenshot of the camera output:

      Screenshot 2025-03-12 123143

      You can find the full export log file in my first post. Do you think any of the errors and/or warnings there could cause any problem with the packaging process via the IMX500-Packager?

    3. Glenn JocherUltralytics

      Thank you for sharing these details. The warnings in your export log about "No BN layers to fold" and quantization parameters are normal during IMX conversion and shouldn't affect packaging. Since your camera feed works with the default model but not your custom export, please verify:

      1. Your imx500-package command uses the exact packerOut.zip from yolov8n_imx_model
      2. The input tensor shape in your exported model matches IMX500 expectations (640x640 by default)

      If issues persist, we recommend trying the IMX500 conversion process with our pretrained YOLOv8n model from https://github.com/ultralytics/assets/releases as a validation step.

    4. fraciprianoGitHub

      Hello @glenn-jocher , thank you for your answer.

      1. Yes, I'm the one specifying the packerOut.zip path when running imx500-package
      2. I think so. Here is the content of the dnnParams.xml file generated by the export function
      <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
      <dnnParams>
          <networks>
              <network name="yolov8n_new_imx" ordinal="0" type="">
                  <inputTensors>
                      <inputTensor persistency="0" ordinal="0" name="Placeholder.input.uid1:0" l2Offset="260480" numOfDimensions="3" bitsPerElement="8" shift="0" scale="0.00390625" format="unsigned">
                          <dimensions>
                              <dimension size="3" serializationOrder="2" ordinal="0" padding="0"/>
                              <dimension size="640" serializationOrder="1" ordinal="1" padding="0"/>
                              <dimension size="640" serializationOrder="0" ordinal="2" padding="0"/>
                          </dimensions>
                      </inputTensor>
                  </inputTensors>
                  <outputTensors>
                      <outputTensor ordinal="1" name="transform-83-/MultiClassNMS:0" l2Offset="281984" numOfDimensions="1" bitsPerElement="8" shift="0" scale="0.00390625" format="unsigned">
                          <dimensions>
                              <dimension size="300" serializationOrder="0" ordinal="0" padding="0"/>
                          </dimensions>
                      </outputTensor>
                      <outputTensor ordinal="2" name="transform-84-/MultiClassNMS:0" l2Offset="280960" numOfDimensions="1" bitsPerElement="16" shift="0" scale="1.0" format="signed">
                          <dimensions>
                              <dimension size="300" serializationOrder="0" ordinal="0" padding="0"/>
                          </dimensions>
                      </outputTensor>
                      <outputTensor ordinal="3" name="transform-85-/MultiClassNMS:0" l2Offset="279936" numOfDimensions="1" bitsPerElement="16" shift="0" scale="1.0" format="signed">
                          <dimensions>
                              <dimension size="1" serializationOrder="0" ordinal="0" padding="0"/>
                          </dimensions>
                      </outputTensor>
                      <outputTensor ordinal="0" name="transform-86-/MultiClassNMS:0" l2Offset="260480" numOfDimensions="2" bitsPerElement="16" shift="0" scale="0.03125" format="signed">
                          <dimensions>
                              <dimension size="300" serializationOrder="0" ordinal="0" padding="0"/>
                              <dimension size="4" serializationOrder="1" ordinal="1" padding="0"/>
                          </dimensions>
                      </outputTensor>
                  </outputTensors>
              </network>
          </networks>
          <l2memory totalSize="8388480" coefficientsSize="2604544" reservedMemorySize="1024" networksRuntimeSize="5523456"/>
      </dnnParams>
      

      I downloaded the yolov8n.pt file from the Sep 29, 2024 Release and repeated the process from the beginning. Same result.

      I'm adding here the terminal outputs I get when running the imx500-package: imx500-package_log.txt

    5. Glenn JocherUltralytics(編集済み)

      Thanks for sharing the details. The dnnParams.xml shows correct 640x640 input dimensions. Since the default Mobilenet model works but your YOLOv8 export doesn't, please verify that your output tensor dimensions and ordering match the demo's expectations. YOLO IMX exports have a different output layout from Mobilenet, so the demo's post-processing must match. The deployment section of the IMX500 guide uses the pp_od_yolo_ultralytics post-processor from the AITRIOS module library for Ultralytics YOLO IMX exports.

    6. fraciprianoGitHub

      Okay. So the problem was actually related to the output. The ordering is fine, as the scores and the classes. The problem are the bboxes. The values that I obtain are completely out of scale.

      Example:

      detection label: cup (0.56)
      detection box: (396100, 107520, 0, 0)

      whereas I would expect something like this:

      detection label: cup (0.56)
      detection box: (39, 459, 440, 177)

      I'm not sure how to interpret this results. Is (396100, 107520, 0, 0) supposed to be the raw output of YOLOv8n? Also, in the dnnParams.xml posted above, I see that there is a scale="0.00390625" associated with the component of the output tensor relative to the bboxes. Should I renormalize my output using this factor?

      Thank you for any insight you can provide.

    7. Glenn JocherUltralytics(編集済み)

      The raw IMX500 outputs are quantized and need post-processing. Rather than decoding them by hand, use the pp_od_yolo_ultralytics post-processor shown in the deployment section of the IMX500 guide.

    8. fraciprianoGitHub

      Hello @glenn-jocher, a code snippet would be much appreciated for double-checking. Also, I can't find the documentation you mentioned—could you link it to me, please?

    9. Glenn JocherUltralytics(編集済み)

      The IMX500 outputs are decoded for you by the AITRIOS module library, as shown in the deployment section of the IMX500 guide:

      from modlib.models.post_processors import pp_od_yolo_ultralytics
      
      
      def post_process(self, output_tensors):
          return pp_od_yolo_ultralytics(output_tensors)

      Let us know if this resolves the coordinate scaling issue!

    10. fraciprianoGitHub

      I think there’s been a misunderstanding. I thought there were other changes to be made besides rescaling. Scaling alone cannot be the solution since (396100, 107520, 0, 0) cannot become (39, 459, 440, 177) just by a scalar multiplication.

      Also, I cannot find the "What's Under the Hood?" section anywhere here https://developer.sony.com/imx500. Could you be more precise about where I should look?

    11. Glenn JocherUltralytics(編集済み)

      The "What's Under the Hood?" section refers to our Ultralytics IMX500 documentation, not Sony's site, but it describes the quantization and conversion toolchain, not output decoding. For box decoding use the post-processor from the deployment section:

      from modlib.models.post_processors import pp_od_yolo_ultralytics
      
      
      def post_process(self, output_tensors):
          return pp_od_yolo_ultralytics(output_tensors)
    12. fraciprianoGitHub

      Hi @glenn-jocher , thank you very much for all the support. It finally works! There was no need to rescale the boxes by 0.03125. I was missing the --bbox-normalization flag when launching the script.

      Once I added the flag, everything worked fine.