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에 배포하는 과정을 안내합니다.
IMX500으로 내보내야 하는 이유#
Sony의 IMX500 지능형 비전 센서는 센서 자체에서 AI 처리를 수행하며, Sony는 이를 지능형 비전 센서 분야의 세계 최초라고 설명합니다. 이 센서는 데이터 처리 병목 현상, 개인정보 보호 우려, 성능 제한 등 일반적인 엣지 AI 문제를 해결하는 데 도움이 됩니다. 기존 센서는 이미지와 프레임만 전달하지만, IMX500은 캡처한 내용을 해석하여 디바이스가 실시간으로 인사이트를 생성할 수 있도록 합니다.
YOLO11 모델용 Sony IMX500 내보내기#
IMX500은 데이터를 클라우드로 보내 처리하지 않고 센서에서 직접 처리하도록 설계되었습니다.
IMX500은 양자화된 모델과 함께 작동합니다. 양자화를 적용하면 정확도를 크게 떨어뜨리지 않으면서 모델의 크기를 줄이고 속도를 높일 수 있습니다. 양자화는 엣지 컴퓨팅의 제한된 리소스에 적합하며, 지연 시간을 줄이고 데이터를 로컬에서 빠르게 처리하여 클라우드에 의존하지 않고 애플리케이션이 신속하게 응답하도록 합니다. 로컬 처리는 사용자 데이터를 원격 서버로 전송하지 않으므로 데이터의 비공개성과 보안도 유지합니다.
IMX500 주요 기능:
- 메타데이터 출력: 이미지만 전송하는 대신 IMX500은 이미지와 메타데이터(추론 결과)를 모두 출력할 수 있으며, 데이터 크기와 대역폭을 줄이고 비용을 절감하기 위해 메타데이터만 출력할 수도 있습니다.
- 개인정보 보호 우려 해결: IMX500은 장치에서 데이터를 처리하여 개인정보 보호 우려를 해소하므로 인원 계수 및 점유 현황 추적과 같은 사람 중심 애플리케이션에 적합합니다.
- 실시간 처리: 빠른 센서 내 처리는 자율 시스템과 같은 엣지 AI 애플리케이션에서 실시간 의사 결정을 지원합니다.
시작하기 전에: 최상의 결과를 얻으려면 모델 학습 가이드, 데이터셋 개요, 하이퍼파라미터 튜닝 가이드를 따라 YOLO11 모델을 내보내기에 적합하게 준비하세요.
지원 작업#
IMX500 내보내기는 Ultralytics 작업 7개 중 4개를 지원하며, YOLOv8n 및 YOLO11n에만 사용할 수 있습니다. 다른 모델 계열, 스케일 및 아키텍처는 지원되지 않으며, 시맨틱 세그멘테이션, OBB 또는 깊이 추정 모델을 내보내면 오류가 발생합니다.
사용 예시#
Ultralytics YOLO11 모델을 IMX500 형식으로 내보내고 내보낸 모델로 추론을 실행합니다.
IMX500 형식은 내보내기, 예측, 검증 모드를 지원합니다. Ultralytics 추론 및 검증은 호스트 CPU에서 내보낸 model_imx.onnx을 실행합니다.
여기서 추론을 수행하는 목적은 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 패키지는 런타임에 내보내기에 필요한 추가 종속성을 설치합니다. 내보내기 명령을 처음 실행할 때 제대로 작동하도록 콘솔을 다시 시작해야 할 수 있습니다.
내보내기 인수#
| 인수 | 유형 | 기본값 | 설명 |
|---|---|---|---|
format | str | 'imx' | 내보낸 모델의 대상 형식으로, 다양한 배포 환경과의 호환성을 정의합니다. |
imgsz | int 또는 tuple | 640 | 모델 입력에 사용할 이미지 크기입니다. 정사각형 이미지에는 정수를 사용하고, 특정 크기에는 튜플 (height, width)을 사용할 수 있습니다. |
quantize | int 또는 str | 8/auto | 양자화 정밀도입니다. IMX500에는 8(INT8/PTQ)이 필요하며 자동으로 활성화됩니다. FP32 및 FP16 전용 내보내기는 지원되지 않습니다. 더 이상 사용되지 않는 half/int8 플래그를 대체합니다. |
data | str | None | 데이터셋 YAML 경로로, 양자화에 필수입니다. 분류 작업에서는 데이터셋 디렉터리 또는 내장 데이터셋 이름을 사용합니다. 생략하면 Ultralytics가 모델 작업에 맞는 기본 보정 데이터셋을 선택합니다. |
fraction | float, int 또는 list | 1.0 | 비율, 이미지 수 또는 [train, val, test] 비율/개수로 지정하는 보정 하위 집합입니다. 항목이 두 개인 목록에서는 test이 전체로 설정되고, 0는 건너뜁니다. |
nms | bool, 선택 사항 | None | 원시 출력(None, 기본값), 내장 NMS(True) 또는 NMS가 없는 헤드(False)를 선택합니다. IMX는 detect, segment, pose 작업에 nms=True이 필요하며 이를 자동으로 선택합니다. |
device | str | None | 내보내기에 사용할 디바이스를 지정합니다. 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에 배포하여 추론을 수행할 수 있습니다.
하드웨어 사전 요구 사항#
다음 하드웨어를 준비하세요:
- Raspberry Pi 5 또는 Raspberry Pi 4 Model B
- 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-upgrade2단계: IMX500 센서를 작동하는 데 필요한 IMX500 펌웨어를 설치합니다.
sudo apt install imx500-all3단계: 변경 사항을 적용하려면 Raspberry Pi를 재부팅하세요.
sudo reboot4단계: AITRIOS Raspberry Pi 애플리케이션 모듈 라이브러리를 설치하세요.
pip install git+https://github.com/SonySemiconductorSolutions/aitrios-rpi-application-module-library.git5단계: aitrios-rpi-application-module-library 예제에서 제공하는 다음 스크립트를 사용하여 YOLO11 객체 감지, 포즈 추정, 분류, 세그멘테이션을 실행하세요.
이 스크립트를 실행하기 전에 환경에 맞게 model_file 및 labels.txt 디렉터리를 바꾸세요.
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/이미지) |
|---|---|---|---|---|---|
| YOLOv8n | imx | 640 | 2.1 | 0.470 | 58.79 |
| YOLO11n | imx | 640 | 2.2 | 0.517 | 58.82 |
| YOLOv8n-pose | imx | 640 | 2.0 | 0.687 | 58.79 |
| YOLO11n-pose | imx | 640 | 2.1 | 0.788 | 62.50 |
| 모델 | 형식 | 크기(픽셀) | packerOut.zip의 크기(MB) | 정확도(top1) | 정확도(top5) | 추론 시간(ms/이미지) |
|---|---|---|---|---|---|---|
| YOLOv8n-cls | imx | 224 | 2.3 | 0.25 | 0.5 | 33.31 |
| YOLO11n-cls | imx | 224 | 2.3 | 0.25 | 0.417 | 33.31 |
위 벤치마크는 감지 모델에 COCO128 데이터셋을, 포즈 추정 모델에 COCO8-Pose 데이터셋을, 분류 모델에 ImageNet10을 사용하여 검증했습니다.
내부 작동 방식#
Sony 모델 압축 툴킷(MCT)#
Sony Model Compression Toolkit (MCT)는 양자화 및 가지치기를 통해 딥러닝 모델을 최적화하는 툴킷입니다. 다양한 양자화 방법을 지원하며, 정확도를 크게 희생하지 않으면서 모델 크기와 연산 복잡도를 줄이는 고급 알고리즘을 제공합니다. MCT는 리소스가 제한된 장치에 모델을 배포할 때 특히 유용하며, 효율적인 추론과 지연 시간 감소를 지원합니다.
MCT에서 지원하는 기능#
Sony의 MCT는 신경망 모델을 최적화하도록 설계된 다양한 기능을 제공합니다:
- 그래프 최적화: 배치 정규화와 같은 계층을 이전 계층에 통합하는 등 모델을 더 효율적인 형태로 변환합니다.
- 양자화 파라미터 검색: 평균 제곱 오차, 클리핑 없음, 평균 절대 오차와 같은 지표를 사용하여 양자화 노이즈를 최소화합니다.
- 고급 양자화 알고리즘:
- 음수 시프트 보정: 대칭 활성화 양자화로 인한 성능 문제를 해결합니다.
- 이상치 필터링: z-score를 사용하여 이상치를 탐지하고 제거합니다.
- 클러스터링: 분포 일치도를 높이기 위해 비균일 양자화 그리드를 사용합니다.
- 혼합 정밀도 검색: 민감도를 기준으로 레이어마다 서로 다른 양자화 비트 폭을 할당합니다.
- 시각화: TensorBoard를 사용하여 모델 성능 인사이트, 양자화 단계 및 비트 폭 구성을 확인합니다.
양자화#
MCT는 모델 크기를 줄이고 추론 속도를 높이기 위해 여러 양자화 방법을 지원합니다.
- 학습 후 양자화(PTQ):
- Keras 및 PyTorch API를 통해 사용할 수 있습니다.
- 복잡도: 낮음
- 계산 비용: 낮음(CPU 기준 수분)
- 그래디언트 기반 학습 후 양자화(GPTQ):
- Keras 및 PyTorch API를 통해 사용할 수 있습니다.
- 복잡도: 중간
- 계산 비용: 보통(GPU 기준 2~3시간)
- 양자화 인식 학습 (QAT):
- 복잡도: 높음
- 계산 비용: 높음(GPU 기준 12~36시간)
MCT는 가중치와 활성화에 대해 다양한 양자화 방식을 지원합니다.
- 2의 거듭제곱(하드웨어 친화적)
- 대칭
- 균일
구조적 가지치기#
MCT는 특정 하드웨어 아키텍처에 맞춰 설계된 구조적 하드웨어 인식 모델 가지치기를 도입합니다. 이 기법은 SIMD 그룹을 가지치기하여 대상 플랫폼의 단일 명령어 다중 데이터(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 모델을 사용하여 더 빠른 처리와 최소한의 지연 시간으로 교통 모니터링 및 안전 분석을 수행합니다.
- 리테일 분석: 판매 시점 관리 시스템이나 스마트 선반에 최적화된 모델을 배포하여 매장 내 모니터링을 향상합니다.
결론#
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은 이미지당 추론 시간 58.82ms를 달성합니다.
- COCO128 데이터셋에서 mAP50-95 0.517
- 양자화 후 모델 크기는 2.2MB에 불과합니다.
이는 IMX500 형식이 엣지 AI 애플리케이션에 적합한 우수한 정확도를 유지하면서 효율적인 실시간 추론을 제공함을 보여줍니다.
댓글86
질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.
Chad Walshwhere 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?
Glenn JocherUltralyticsPlease 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 intermittentNoneresults include a minimal inference script, confidence threshold, and a short reproducible input sample. Note that IMX export uses the calibration dataset specified bydataand defaults to the full dataset, so testing a smallerfractionmay help isolate resource-related failures.
leeprevost
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, > KilledWould 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?
leeprevost
@glenn-jocher am I posting at the right place? Put this in issues on gh?
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 checksoutput (orultralytics.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 withfraction(e.g., 0.25). Example:yolo export model=best.pt format=imx data=your.yaml imgsz=640 fraction=0.25IMX-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.
leeprevost
Thank you. I'll dig into the logs and see if I can add anything before opening new issue.
leeprevost
a few more questions and I will open an issue:
- 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.
- 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?
- 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.
leeprevost
I opened an issue: https://github.com/ultralytics/ultralytics/issues/22512
Just tried the export again with the fraction=0.25 argument and got to "Optimal Solution Found" with objective measure of 0.94, then died with error:
Error x IMX: export failure 12662.7s: No module named 'onnxscript'
leeprevost
https://github.com/pytorch/pytorch/issues/166352 -- adding to my requirements.txt pointed to by Containerfile.
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-converterandmodel-compression-toolkit) itself, so upgrade withpip install -U ultralyticsand re-run the export rather than pinning old versions by hand. Let’s continue the deep-dive in the issue you opened for traceability.leeprevost
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.
Glenn JocherUltralyticsThanks—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
imgszto 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=512For a concise list of export options and behavior, see the Export mode docs at Ultralytics YOLO — Export.
leeprevost
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:
- Start over and try with nano model.
- 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.
leeprevost
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...
bohlebots
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
Teo-treny
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 scalarsI'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.
aytacsekmen
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
HelloCigar
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?
skim-sony
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?
skim-sony
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()?
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
imxformat. 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.skim-sony(수정됨)
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!
Glenn JocherUltralytics(수정됨)@skim-sony that's interesting you're seeing better performance! The discrepancy could be due to several factors:
- Measurement methodology: end-to-end time (pre/post-processing + inference) differs from model-only inference time
- Firmware and converter versions
- Image resolution and resizing
- 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.
fracipriano
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.
Glenn JocherUltralyticsThank 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-helloin the terminal. If the camera works, verify that thelabels.txtpath in your demo command matches the exported file. You can also try inference on a static image first withimx_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.
fracipriano
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:
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?
Glenn JocherUltralyticsThank 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:
- Your
imx500-packagecommand uses the exactpackerOut.zipfromyolov8n_imx_model - 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.
- Your
fracipriano
Hello @glenn-jocher , thank you for your answer.
- Yes, I'm the one specifying the packerOut.zip path when running imx500-package
- 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
Glenn JocherUltralytics(수정됨)Thanks for sharing the details. The
dnnParams.xmlshows 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 thepp_od_yolo_ultralyticspost-processor from the AITRIOS module library for Ultralytics YOLO IMX exports.fracipriano
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.
Glenn JocherUltralytics(수정됨)The raw IMX500 outputs are quantized and need post-processing. Rather than decoding them by hand, use the
pp_od_yolo_ultralyticspost-processor shown in the deployment section of the IMX500 guide.fracipriano
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?
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!
fracipriano
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?
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)fracipriano
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.
Glenn JocherUltralytics(수정됨)Great to hear you resolved it! For the current deployment workflow, including post-processing of the model outputs, see the IMX500 deployment guide. Happy detecting with your Raspberry Pi setup! 🚀