Upload 39 files
Browse filesFiles changed (40)
- .gitattributes+23
- README.mdAdded+153
- asserts/bus.jpgAdded
- asserts/ssd_car.jpgAdded
- asserts/ssd_car_depth_heatmap_ax.pngAdded
- asserts/ssd_car_depth_heatmap_onnx.pngAdded
- ax615/config.jsonAdded+56
- ax615/yolo26l-depth_w8a8_mix.axmodelAdded+3
- ax615/yolo26m-depth_w8a8_mix.axmodelAdded+3
- ax615/yolo26n-depth_w8a8_mix.axmodelAdded+3
- ax615/yolo26s-depth_w8a8_mix.axmodelAdded+3
- ax615/yolo26x-depth_w8a8_mix.axmodelAdded+3
- ax630c/config.jsonAdded+45
- ax630c/yolo26l-depth_w8a8_mix.axmodelAdded+3
- ax630c/yolo26m-depth_w8a8_mix.axmodelAdded+3
- ax630c/yolo26n-depth_w8a8_mix.axmodelAdded+3
- ax630c/yolo26s-depth_w8a8_mix.axmodelAdded+3
- ax630c/yolo26x-depth_w8a8_mix.axmodelAdded+3
- ax637/config.jsonAdded+56
- ax637/yolo26l-depth_w8a8_mix.axmodelAdded+3
- ax637/yolo26m-depth_w8a8_mix.axmodelAdded+3
- ax637/yolo26n-depth_w8a8_mix.axmodelAdded+3
- ax637/yolo26s-depth_w8a8_mix.axmodelAdded+3
- ax637/yolo26x-depth_w8a8_mix.axmodelAdded+3
- ax8850n/config.jsonAdded+56
- ax8850n/yolo26l-depth_w8a8_mix.axmodelAdded+3
- ax8850n/yolo26m-depth_w8a8_mix.axmodelAdded+3
- ax8850n/yolo26n-depth_w8a8_mix.axmodelAdded+3
- ax8850n/yolo26s-depth_w8a8_mix.axmodelAdded+3
- ax8850n/yolo26x-depth_w8a8_mix.axmodelAdded+3
- axengine-0.1.3-py3-none-any.whlAdded
- calib_data.zipAdded+3
- fold_depth_log.pyAdded+93
- infer_depth.pyAdded+228
- onnx/yolo26l-depth.onnxAdded+3
- onnx/yolo26m-depth.onnxAdded+3
- onnx/yolo26n-depth.onnxAdded+3
- onnx/yolo26s-depth.onnxAdded+3
- onnx/yolo26x-depth.onnxAdded+3
- requirements.txtAdded+6
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363738394041424344454647484950515253545556575832 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textasserts/bus.jpg filter=lfs diff=lfs merge=lfs -textasserts/ssd_car_depth_heatmap_ax.png filter=lfs diff=lfs merge=lfs -textasserts/ssd_car_depth_heatmap_onnx.png filter=lfs diff=lfs merge=lfs -textax615/yolo26l-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax615/yolo26m-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax615/yolo26n-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax615/yolo26s-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax615/yolo26x-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax630c/yolo26l-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax630c/yolo26m-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax630c/yolo26n-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax630c/yolo26s-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax630c/yolo26x-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax637/yolo26l-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax637/yolo26m-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax637/yolo26n-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax637/yolo26s-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax637/yolo26x-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax8850n/yolo26l-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax8850n/yolo26m-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax8850n/yolo26n-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax8850n/yolo26s-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -textax8850n/yolo26x-depth_w8a8_mix.axmodel filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153---
license: agpl-3.0
language:
- en
base_model:
- YOLO26
pipeline_tag: depth-estimation
tags:
- Axera
- YOLO26
- NPU
- Ultralytics
---
# YOLO26-Depth
This repository provides an Axera NPU inference deployment example for the Ultralytics YOLO26-Depth depth-estimation model, including model conversion and AX8850N Python inference examples.
This version of YOLO26-Depth has been converted to run on the Axera NPU using mixed U8/U16 quantization for improved performance.
## Convert tools links:
For those who are interested in model conversion, you can try to export axmodel through
- [Pulsar2 Link, How to Convert ONNX to axmodel](https://pulsar2-docs.readthedocs.io/en/latest/pulsar2/introduction.html)
## Support Platform
- AX8850N/AX8850
- [M4N-Dock(爱芯派Pro)](https://wiki.sipeed.com/hardware/zh/maixIV/m4ndock/m4ndock.html)
- [M.2 Accelerator card](https://docs.m5stack.com/en/ai_hardware/LLM-8850_Card)
- AX8910
- AX630C
- [爱芯派2](https://axera-pi-2-docs-cn.readthedocs.io/zh-cn/latest/index.html)
- [Module-LLM](https://docs.m5stack.com/zh_CN/module/Module-LLM)
- [LLM630 Compute Kit](https://docs.m5stack.com/zh_CN/core/LLM630%20Compute%20Kit)
- AX615
### Performance Statistics
AX8850N (NPU3 mode)
| 模型 | 分辨率 | 耗时(ms) | CMM(MiB) |
|---|---:|---:|---:|
| yolo26n-depth | 768x768 | 5.83 | 7.97 |
| yolo26s-depth | 768x768 | 8.33 | 14.90 |
| yolo26m-depth | 768x768 | 16.37 | 36.36 |
| yolo26l-depth | 768x768 | 20.74 | 41.12 |
| yolo26x-depth | 768x768 | 39.19 | 93.37 |
AX8910
| 模型 | 分辨率 | 耗时(ms) | CMM(MiB) |
|---|---:|---:|---:|
| yolo26n-depth | 768x768 | 20.42 | 16.38 |
| yolo26s-depth | 768x768 | 29.24 | 25.27 |
| yolo26m-depth | 768x768 | 52.34 | 48.02 |
| yolo26l-depth | 768x768 | 66.61 | 45.65 |
| yolo26x-depth | 768x768 | 120.21 | 83.85 |
AX630C (NPU2 mode)
| 模型 | 分辨率 | 耗时(ms) | CMM(MiB) |
|---|---:|---:|---:|
| yolo26n-depth | 768x768 | 27.67 | 15.65 |
| yolo26s-depth | 768x768 | 41.68 | 22.75 |
| yolo26m-depth | 768x768 | 74.02 | 47.10 |
| yolo26l-depth | 768x768 | 94.04 | 44.77 |
| yolo26x-depth | 768x768 | 169.09 | 84.50 |
AX615 (NPU2 mode)
| 模型 | 分辨率 | 耗时(ms) | CMM(MiB) |
|---|---:|---:|---:|
| yolo26n-depth | 768x768 | 82.17 | 14.21 |
| yolo26s-depth | 768x768 | 109.03 | 23.44 |
| yolo26m-depth | 768x768 | 170.99 | 47.75 |
| yolo26l-depth | 768x768 | 201.56 | 45.57 |
## How to use
Download all files from this repository to the device
```shell
root@ax650:~/root/yolo26-depth# tree -L 2
.
├── asserts
│ ├── bus.jpg
│ ├── ssd_car_depth_heatmap_ax.png
│ ├── ssd_car_depth_heatmap_onnx.png
│ └── ssd_car.jpg
├── ax615
│ ├── config.json
│ ├── yolo26l-depth_w8a8_mix.axmodel
│ ├── yolo26m-depth_w8a8_mix.axmodel
│ ├── yolo26n-depth_w8a8_mix.axmodel
│ ├── yolo26s-depth_w8a8_mix.axmodel
│ └── yolo26x-depth_w8a8_mix.axmodel
├── ax630c
│ ├── config.json
│ ├── yolo26l-depth_w8a8_mix.axmodel
│ ├── yolo26m-depth_w8a8_mix.axmodel
│ ├── yolo26n-depth_w8a8_mix.axmodel
│ ├── yolo26s-depth_w8a8_mix.axmodel
│ └── yolo26x-depth_w8a8_mix.axmodel
├── ax637
│ ├── config.json
│ ├── yolo26l-depth_w8a8_mix.axmodel
│ ├── yolo26m-depth_w8a8_mix.axmodel
│ ├── yolo26n-depth_w8a8_mix.axmodel
│ ├── yolo26s-depth_w8a8_mix.axmodel
│ └── yolo26x-depth_w8a8_mix.axmodel
├── ax8850n
│ ├── config.json
│ ├── yolo26l-depth_w8a8_mix.axmodel
│ ├── yolo26m-depth_w8a8_mix.axmodel
│ ├── yolo26n-depth_w8a8_mix.axmodel
│ ├── yolo26s-depth_w8a8_mix.axmodel
│ └── yolo26x-depth_w8a8_mix.axmodel
├── axengine-0.1.3-py3-none-any.whl
├── calib_data.zip
├── fold_depth_log.py
├── infer_depth.py
├── onnx
│ ├── yolo26l-depth.onnx
│ ├── yolo26m-depth.onnx
│ ├── yolo26n-depth.onnx
│ ├── yolo26s-depth.onnx
│ └── yolo26x-depth.onnx
├── README.md
└── requirements.txt
6 directories, 39 files
```
Inference with AX650 Host, such as M4N-Dock(爱芯派Pro)
```shell
cd /root/yolo26-depth
pip3 install -r requirements.txt
pip3 install axengine-0.1.3-py3-none-any.whl
# axera npu infer
python3 infer_depth.py --model ./ax8850n/yolo26n-depth_w8a8_mix.axmodel --source ./asserts/ssd_car.jpg
# onnxtuntime cpu infer
python3 infer_depth.py --model ./onnx/yolo26n-depth.onnx --source ./asserts/ssd_car.jpg
```
axera npu output:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556{ "input": "../onnx_model/yolo26x-depth.onnx", "output_dir": "./output", "output_name": "yolo26x-depth_w8a8_mix.axmodel", "model_type": "ONNX", "target_hardware": "AX620L", "npu_mode": "NPU2", "onnx_opt": { "disable_onnx_optimization": false, "enable_onnxsim": true }, "quant": { "input_configs": [ { "tensor_name": "images", "calibration_dataset": "../calib_data.zip", "calibration_size": -1, "calibration_mean": [0, 0, 0], "calibration_std": [255, 255, 255] } ], "layer_configs": [ { "start_tensor_names": ["DEFAULT"], "end_tensor_names": ["DEFAULT"], "data_type": "U8" }, { "layer_names": [ "/model.10/m/m.0/attn/Softmax", "/model.10/m/m.0/attn/Transpose_1", "/model.10/m/m.0/attn/MatMul_1", "/model.22/m.0/m.0.1/attn/Softmax", "/model.22/m.0/m.0.1/attn/Transpose_1", "/model.22/m.0/m.0.1/attn/MatMul_1" ], "data_type": "U16" } ], "calibration_method": "MinMax", "precision_analysis": false, "precision_analysis_method": "EndToEnd", "precision_analysis_mode": "Reference" }, "input_processors": [ { "tensor_name": "images", "tensor_layout": "NCHW", "src_dtype": "U8", "src_layout": "NHWC" } ], "compiler": { "check": 0 }}123version https://git-lfs.github.com/spec/v1oid sha256:d6d65011f5c0671cd4b1ae509e607149cdf9348ff61e37e76eef8744a84bc292size 28909733123version https://git-lfs.github.com/spec/v1oid sha256:e3aa79d60615c4887d22a4eeaf7267bc4d648011fb2342b616d0140bc1ad584asize 24119193123version https://git-lfs.github.com/spec/v1oid sha256:ab88d74eaf85f87e718976726d8597a9958ba7832f7aef83bd212918eb027266size 6648721123version https://git-lfs.github.com/spec/v1oid sha256:c294232952114e78f013cf10baff40455fbd188b95aa5e859128770ca73caccesize 13670865123version https://git-lfs.github.com/spec/v1oid sha256:a2c748620c859aafb5c0c3757ee7333c8427d769acde0f5c4fea4e3b8a940746size 60099337123456789101112131415161718192021222324252627282930313233343536373839404142434445{ "input": "../onnx_model/yolo26x-depth.onnx", "output_dir": "./output", "output_name": "yolo26x-depth_w8a8.axmodel", "model_type": "ONNX", "target_hardware": "AX620E", "npu_mode": "NPU2", "onnx_opt": { "disable_onnx_optimization": false, "enable_onnxsim": true }, "quant": { "input_configs": [ { "tensor_name": "images", "calibration_dataset": "../calib_data.zip", "calibration_size": -1, "calibration_mean": [0, 0, 0], "calibration_std": [255, 255, 255] } ], "layer_configs": [ { "start_tensor_names": ["DEFAULT"], "end_tensor_names": ["DEFAULT"], "data_type": "U8" } ], "calibration_method": "MinMax", "precision_analysis": true, "precision_analysis_method": "EndToEnd", "precision_analysis_mode": "Reference" }, "input_processors": [ { "tensor_name": "images", "tensor_layout": "NCHW", "src_dtype": "U8", "src_layout": "NHWC" } ], "compiler": { "check": 0 }}123version https://git-lfs.github.com/spec/v1oid sha256:733153585d26b222c2a09e1949a030cb1283ee519df9dfbbdcc066c47a77f8a9size 28076593123version https://git-lfs.github.com/spec/v1oid sha256:973e938964e8173da1f881c56a3539deffa7de0063c4f1b600bcc177cca890a2size 23446339123version https://git-lfs.github.com/spec/v1oid sha256:dcb0036f5905e8034b337b89f980bc62c1d958fd9360622e74ef05f2f79deaf6size 5799519123version https://git-lfs.github.com/spec/v1oid sha256:27178691d62ecba76146cdfb2c19eb7413d76051dbfe94524793a88466230e83size 12949927123version https://git-lfs.github.com/spec/v1oid sha256:31712b17851e31d88a6f029e9c7af34ff117297671c4f5146cabd5851dbffc14size 591158691234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556{ "input": "../onnx_model/yolo26x-depth.onnx", "output_dir": "./output", "output_name": "yolo26x-depth_w8a8_mix.axmodel", "model_type": "ONNX", "target_hardware": "AX637", "npu_mode": "NPU1", "onnx_opt": { "disable_onnx_optimization": false, "enable_onnxsim": true }, "quant": { "input_configs": [ { "tensor_name": "images", "calibration_dataset": "../calib_data.zip", "calibration_size": -1, "calibration_mean": [0, 0, 0], "calibration_std": [255, 255, 255] } ], "layer_configs": [ { "start_tensor_names": ["DEFAULT"], "end_tensor_names": ["DEFAULT"], "data_type": "U8" }, { "layer_names": [ "/model.10/m/m.0/attn/Softmax", "/model.10/m/m.0/attn/Transpose_1", "/model.10/m/m.0/attn/MatMul_1", "/model.22/m.0/m.0.1/attn/Softmax", "/model.22/m.0/m.0.1/attn/Transpose_1", "/model.22/m.0/m.0.1/attn/MatMul_1" ], "data_type": "U16" } ], "calibration_method": "MinMax", "precision_analysis": false, "precision_analysis_method": "EndToEnd", "precision_analysis_mode": "Reference" }, "input_processors": [ { "tensor_name": "images", "tensor_layout": "NCHW", "src_dtype": "U8", "src_layout": "NHWC" } ], "compiler": { "check": 0 }}123version https://git-lfs.github.com/spec/v1oid sha256:fb656bd91c66bcf68c684b22fcfd71ce4e3824f36a126f7891053c07bc456442size 28992433123version https://git-lfs.github.com/spec/v1oid sha256:ceaa164c13b22271f1ee7159570cfd4ffd2b3a787f9b10bad37649e7173a2738size 24400021123version https://git-lfs.github.com/spec/v1oid sha256:f8891164a3c842eae39687e3a30dedbe702cee48bffb088c0ae39dc368d329ebsize 6558789123version https://git-lfs.github.com/spec/v1oid sha256:0e4f29c7e71defaf06b6b02cb83b878fc19c9528bfb09cd6ec3f6c8d646c5dbbsize 13521453123version https://git-lfs.github.com/spec/v1oid sha256:9ae8c792b1fb9e121533f99d56f17e7b1f187a11e06039d2541b8d33ce5ea495size 584348011234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556{ "input": "../onnx_model/yolo26x-depth.onnx", "output_dir": "./output", "output_name": "yolo26x-depth_w8a8_mix.axmodel", "model_type": "ONNX", "target_hardware": "AX650", "npu_mode": "NPU3", "onnx_opt": { "disable_onnx_optimization": false, "enable_onnxsim": true }, "quant": { "input_configs": [ { "tensor_name": "images", "calibration_dataset": "../calib_data.zip", "calibration_size": -1, "calibration_mean": [0, 0, 0], "calibration_std": [255, 255, 255] } ], "layer_configs": [ { "start_tensor_names": ["DEFAULT"], "end_tensor_names": ["DEFAULT"], "data_type": "U8" }, { "layer_names": [ "/model.10/m/m.0/attn/Softmax", "/model.10/m/m.0/attn/Transpose_1", "/model.10/m/m.0/attn/MatMul_1", "/model.22/m.0/m.0.1/attn/Softmax", "/model.22/m.0/m.0.1/attn/Transpose_1", "/model.22/m.0/m.0.1/attn/MatMul_1" ], "data_type": "U16" } ], "calibration_method": "MinMax", "precision_analysis": false, "precision_analysis_method": "EndToEnd", "precision_analysis_mode": "Reference" }, "input_processors": [ { "tensor_name": "images", "tensor_layout": "NCHW", "src_dtype": "U8", "src_layout": "NHWC" } ], "compiler": { "check": 0 }}123version https://git-lfs.github.com/spec/v1oid sha256:c4f68a0cf54f3707f3368cf306dcdbb77815b63bf8a9d9683ded67b298f2665dsize 28967943123version https://git-lfs.github.com/spec/v1oid sha256:adab90782082ee8142575dcf564e979aa561e9390699a1ee95070cc04f542a89size 23973765123version https://git-lfs.github.com/spec/v1oid sha256:4f099b20be60f028a575c14f9bd2acab4595600584d4a08898e672be6368ec85size 6003543123version https://git-lfs.github.com/spec/v1oid sha256:23b5aa9455f67c7611f34d5af047d5406cefa62f52191adfe4ed49d089e6e055size 13260663123version https://git-lfs.github.com/spec/v1oid sha256:93f8c1e55f4d2f6e6f8059fa0962fab97b0580dd53a59fa9f5ab53a8883cd263size 58979911123version https://git-lfs.github.com/spec/v1oid sha256:fda94194f47c7c69ca1ea4dc63e2ac88ac973759c20f0737e3c97c3c39a03ebbsize 1039756123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293#!/usr/bin/env python3"""Remove the unsupported Log branch from this YOLO depth ONNX export.
For the depth head exported by this project:
Log(Clip(Exp(Clip(x, lo, hi)), floor, +inf))
is equivalent to Clip(x, max(lo, log(floor)), hi). The generated AX637model then contains no AxQuantizedLog CPU fallback."""
from __future__ import annotations
import argparseimport mathfrom pathlib import Path
import numpy as npimport onnxfrom onnx import numpy_helper
def scalar_initializer(model: onnx.ModelProto, name: str) -> float: """Return a scalar initializer and reject models with a different topology.""" for initializer in model.graph.initializer: if initializer.name == name: value = numpy_helper.to_array(initializer) if value.size != 1: raise ValueError(f"{name} must be scalar, got shape {value.shape}") return float(value.reshape(-1)[0]) raise ValueError(f"missing initializer: {name}")
def fold_depth_log(model: onnx.ModelProto) -> None: """Fold the Clip -> Exp -> Clip -> Log sequence used by the depth head.""" nodes = list(model.graph.node) producers = {output: node for node in nodes for output in node.output if output} log_node = next( (node for node in nodes if node.name == "/model.23/Log" and node.op_type == "Log"), None, ) if log_node is None or len(log_node.input) != 1 or len(log_node.output) != 1: raise ValueError("expected a single-input /model.23/Log node")
outer_clip = producers.get(log_node.input[0]) exp_node = producers.get(outer_clip.input[0]) if outer_clip is not None and outer_clip.input else None inner_clip = producers.get(exp_node.input[0]) if exp_node is not None and exp_node.input else None if ( outer_clip is None or outer_clip.op_type != "Clip" or exp_node is None or exp_node.op_type != "Exp" or inner_clip is None or inner_clip.op_type != "Clip" or len(inner_clip.input) != 3 or len(outer_clip.input) < 2 ): raise ValueError("unexpected depth calibration topology around /model.23/Log")
inner_min = scalar_initializer(model, inner_clip.input[1]) floor = scalar_initializer(model, outer_clip.input[1]) if floor <= 0.0: raise ValueError(f"Clip floor must be positive, got {floor}")
# Do not mutate a potentially shared initializer from elsewhere in the graph. folded_min = max(inner_min, math.log(floor)) min_name = "depth_log_folded_min" model.graph.initializer.append(numpy_helper.from_array(np.array(folded_min, dtype=np.float32), min_name)) inner_clip.input[1] = min_name inner_clip.name = "/model.23/Clip_log_folded" inner_clip.output[0] = log_node.output[0]
remove_ids = {id(outer_clip), id(exp_node), id(log_node)} del model.graph.node[:] model.graph.node.extend(node for node in nodes if id(node) not in remove_ids)
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("input", type=Path, help="source ONNX model") parser.add_argument("output", type=Path, help="rewritten ONNX model") args = parser.parse_args()
model = onnx.load(args.input) fold_depth_log(model) onnx.checker.check_model(model) args.output.parent.mkdir(parents=True, exist_ok=True) onnx.save(model, args.output) print(f"wrote {args.output}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228#!/usr/bin/env python3"""Run YOLO26-depth ONNX models and save depth heatmap visualizations.
Example: python onnx_model/infer_depth_onnx.py \ --model onnx_model/yolo26n-depth.onnx \ --source ax650/depth8/images/kv1_NYUdata_NYU0532.jpg"""
from __future__ import annotations
import argparseimport timefrom pathlib import Path
import cv2import numpy as npimport onnxruntime as ort
def parse_args() -> argparse.Namespace: """Parse command-line arguments.""" root = Path(__file__).resolve().parent parser = argparse.ArgumentParser(description="YOLO26-depth ONNX Runtime inference") parser.add_argument("--model", type=Path, default=root / "yolo26n-depth.onnx", help="Path to an ONNX model") parser.add_argument("--axera", action="store_true", help="Use Axera engine for inference") parser.add_argument("--source", type=Path, required=True, help="Path to one input image") parser.add_argument("--output-dir", type=Path, default=root / "runs", help="Directory for output files") parser.add_argument("--alpha", type=float, default=0.6, help="Heatmap opacity in the overlay, in [0, 1]") parser.add_argument("--cmap", choices=("jet", "inferno"), default="jet", help="OpenCV heatmap color map") parser.add_argument( "--mode", choices=("disparity", "metric"), default="disparity", help="Color normalization: inverse depth or metric depth", ) parser.add_argument( "--postprocess", choices=("default", "predictor"), default="default", help="Depth resize path: direct ONNX output or Ultralytics predictor-compatible geometry", ) args = parser.parse_args() if not 0.0 <= args.alpha <= 1.0: parser.error("--alpha must be in [0, 1]") return args
def model_input_size(session, use_axera: bool) -> tuple[str, tuple[int, int]]: """Return the image input name and static (height, width) required by the ONNX model.""" inputs = session.get_inputs() if len(inputs) != 1: raise ValueError(f"Expected one model input, got {len(inputs)}")
image_input = inputs[0] shape = image_input.shape if not isinstance(shape[2], int) or not isinstance(shape[3], int): raise ValueError(f"Dynamic ONNX input shapes are not supported by this script: {shape}") if use_axera: return image_input.name, (shape[1], shape[2]) else: return image_input.name, (shape[2], shape[3])
def letterbox(image: np.ndarray, new_shape: tuple[int, int]) -> tuple[np.ndarray, tuple[int, int, int, int]]: """Resize and center-pad an image exactly as Ultralytics LetterBox does for a fixed ONNX input.""" height, width = image.shape[:2] target_height, target_width = new_shape gain = min(target_height / height, target_width / width) resized_width, resized_height = round(width * gain), round(height * gain) pad_width, pad_height = target_width - resized_width, target_height - resized_height left, right = round(pad_width / 2 - 0.1), round(pad_width / 2 + 0.1) top, bottom = round(pad_height / 2 - 0.1), round(pad_height / 2 + 0.1)
if (width, height) != (resized_width, resized_height): image = cv2.resize(image, (resized_width, resized_height), interpolation=cv2.INTER_LINEAR) image = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114)) return image, (top, bottom, left, right)
def preprocess(image: np.ndarray, input_size: tuple[int, int], use_axera: bool = False) -> tuple[np.ndarray, tuple[int, int, int, int]]: """Letterbox BGR input, convert it to RGB NCHW float32, and normalize to [0, 1].""" image, padding = letterbox(image, input_size) if use_axera: tensor = image[..., ::-1][None] return np.ascontiguousarray(tensor, dtype=np.uint8), padding else: tensor = image[..., ::-1].transpose(2, 0, 1)[None] return np.ascontiguousarray(tensor, dtype=np.float32) / 255.0, padding
def output_depth_map(output: np.ndarray) -> np.ndarray: """Extract one 2D depth map from a standard ONNX depth output tensor.""" output = np.asarray(output) if output.ndim == 4 and output.shape[:2] == (1, 1): return output[0, 0] elif output.ndim == 3 and output.shape[0] == 1: return output[0] elif output.ndim == 2: return output raise ValueError(f"Expected one depth map with shape (1, 1, H, W), got {output.shape}")
def restore_depth( output: np.ndarray, original_shape: tuple[int, int], padding: tuple[int, int, int, int],) -> np.ndarray: """Remove LetterBox padding and resize the exported ONNX output to the original image size.""" depth = output_depth_map(output)
top, bottom, left, right = padding end_y = depth.shape[0] - bottom if bottom else depth.shape[0] end_x = depth.shape[1] - right if right else depth.shape[1] depth = depth[top:end_y, left:end_x] if depth.size == 0: raise ValueError("LetterBox crop is empty; model output and input geometry are inconsistent") return cv2.resize(depth.astype(np.float32), (original_shape[1], original_shape[0]), interpolation=cv2.INTER_LINEAR)
def restore_depth_predictor_aligned(output: np.ndarray, original_shape: tuple[int, int]) -> np.ndarray: """Match ``DepthPredictor.postprocess`` geometry from an exported 4x-upsampled ONNX output.
The PyTorch model passes its H/4 head map directly to ``ops.scale_masks``. ONNX export upsamples that map by four first, so this function reconstructs the H/4 map and applies the same crop-rounding and bilinear resize sequence. It reduces the otherwise visible interpolation-only difference when comparing ONNX output with ``YOLO.predict()``. """ depth = output_depth_map(output) height, width = depth.shape if height % 4 or width % 4: raise ValueError(f"Expected an exported depth output divisible by 4, got {depth.shape}") head = cv2.resize(depth, (width // 4, height // 4), interpolation=cv2.INTER_LINEAR) original_height, original_width = original_shape gain = min(head.shape[0] / original_height, head.shape[1] / original_width) pad_width = (head.shape[1] - round(original_width * gain)) / 2 pad_height = (head.shape[0] - round(original_height * gain)) / 2 top, left = round(pad_height - 0.1), round(pad_width - 0.1) bottom = head.shape[0] - round(pad_height + 0.1) right = head.shape[1] - round(pad_width + 0.1) head = head[top:bottom, left:right] if head.size == 0: raise ValueError("Predictor-compatible crop is empty; model output and input geometry are inconsistent") return cv2.resize(head.astype(np.float32), (original_width, original_height), interpolation=cv2.INTER_LINEAR)
def colorize_depth(depth: np.ndarray, cmap: str, mode: str) -> np.ndarray: """Create the Ultralytics-style BGR depth heatmap; invalid depths are black.""" depth = np.asarray(depth, dtype=np.float32) valid = np.isfinite(depth) & (depth > 0) values = np.where(valid, 1.0 / np.where(valid, depth, 1.0), 0.0) if mode == "disparity" else depth pool = values[valid] if pool.size: low, high = np.percentile(pool, (2, 98)) if mode == "disparity" else (pool.min(), pool.max()) else: low, high = 0.0, 1.0 high = max(float(high), float(low) + 1e-6) normalized = np.clip((values - low) / (high - low), 0.0, 1.0) color_map = {"jet": cv2.COLORMAP_JET, "inferno": cv2.COLORMAP_INFERNO}[cmap] heatmap = cv2.applyColorMap((normalized * 255).astype(np.uint8), color_map) heatmap[~valid] = 0 return heatmap
def save_results( source: Path, output_dir: Path, image: np.ndarray, depth: np.ndarray, heatmap: np.ndarray, alpha: float,) -> tuple[Path, Path, Path]: """Save metric depth values, a standalone heatmap, and a heatmap overlay.""" output_dir.mkdir(parents=True, exist_ok=True) stem = source.stem depth_path = output_dir / f"{stem}_depth.npy" heatmap_path = output_dir / f"{stem}_depth_heatmap.png" overlay_path = output_dir / f"{stem}_depth_overlay.jpg" image_heatmap = np.hstack((image, heatmap)) np.save(depth_path, depth) if not cv2.imwrite(str(heatmap_path), image_heatmap): raise IOError(f"Failed to write {heatmap_path}") overlay = cv2.addWeighted(image, 1.0 - alpha, heatmap, alpha, 0) if not cv2.imwrite(str(overlay_path), overlay): raise IOError(f"Failed to write {overlay_path}") return depth_path, heatmap_path, overlay_path
def main() -> None: """Run one image through a YOLO26-depth ONNX model.""" args = parse_args() if not args.model.is_file(): raise FileNotFoundError(f"ONNX model not found: {args.model}") image = cv2.imread(str(args.source)) if image is None: raise FileNotFoundError(f"Unable to read image: {args.source}")
if args.axera: import axengine as axe session = axe.InferenceSession(str(args.model)) else: session = ort.InferenceSession(str(args.model)) input_name, input_size = model_input_size(session, args.axera) input_tensor, padding = preprocess(image, input_size, args.axera)
start = time.perf_counter() output = session.run(None, {input_name: input_tensor})[0] inference_ms = (time.perf_counter() - start) * 1000 if args.postprocess == "predictor": depth = restore_depth_predictor_aligned(output, image.shape[:2]) else: depth = restore_depth(output, image.shape[:2], padding) heatmap = colorize_depth(depth, args.cmap, args.mode) depth_path, heatmap_path, overlay_path = save_results( args.source, args.output_dir, image, depth, heatmap, args.alpha )
valid = depth[np.isfinite(depth) & (depth > 0)] print(f"Providers: {session.get_providers()}") print(f"Input: {args.source} ({image.shape[1]}x{image.shape[0]}) -> {input_size[1]}x{input_size[0]}") print(f"Postprocess: {args.postprocess}") print(f"Inference: {inference_ms:.1f} ms") print(f"Depth (m): min={valid.min():.3f}, median={np.median(valid):.3f}, max={valid.max():.3f}") print(f"Saved depth: {depth_path}") print(f"Saved heatmap: {heatmap_path}") print(f"Saved overlay: {overlay_path}")
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:85c2687e25a796b0686668de2f49c9cfce09f62075323bca86acc1acaf086963size 106082163123version https://git-lfs.github.com/spec/v1oid sha256:000d863c9ce93830b80ad33980a68b2f0f2819ea49cdc353e5887505f593bf97size 88431991123version https://git-lfs.github.com/spec/v1oid sha256:6583ec12521a7e75eacb209db63393158c7e0e772cda9fdad8c8c0fe74af2a1esize 20772760123version https://git-lfs.github.com/spec/v1oid sha256:8814f4be36d51f0fdafae8c0528378ecf20ba6a1c671fc9c77f4fe1675189765size 48216222123version https://git-lfs.github.com/spec/v1oid sha256:1ef9864093111f6ff1b1255e83d0c27cf6cdc0baf805d867e5b249ef23e681b6size 223381647123456# CPU inference dependenciesnumpy>=1.23opencv-python>=4.8onnxruntime>=1.16
# For CUDA inference, replace onnxruntime above with onnxruntime-gpu..gitattributes+23
README.mdAdded+153
asserts/bus.jpgAdded

Large File Pointer Details
- SHA256: 33b198a1d2839bb9ac4c65d61f9e852196793cae9a0781360859425f6022b69c
- Pointer size: 131 Bytes
- Size of remote file: 487 kB
asserts/ssd_car.jpgAdded

asserts/ssd_car_depth_heatmap_ax.pngAdded

Large File Pointer Details
- SHA256: a3930f05e613cd1bf21b86a993e95840e183ba0eb93ed9c2a76fb8673e651f72
- Pointer size: 131 Bytes
- Size of remote file: 518 kB
asserts/ssd_car_depth_heatmap_onnx.pngAdded

Large File Pointer Details
- SHA256: f0e9542daf66569ec73fe38631d0d6e27c2cce43d87bd3eed5ee509a7e11d420
- Pointer size: 131 Bytes
- Size of remote file: 488 kB
ax615/config.jsonAdded+56
ax615/yolo26l-depth_w8a8_mix.axmodelAdded+3
ax615/yolo26m-depth_w8a8_mix.axmodelAdded+3
ax615/yolo26n-depth_w8a8_mix.axmodelAdded+3
ax615/yolo26s-depth_w8a8_mix.axmodelAdded+3
ax615/yolo26x-depth_w8a8_mix.axmodelAdded+3
ax630c/config.jsonAdded+45
ax630c/yolo26l-depth_w8a8_mix.axmodelAdded+3
ax630c/yolo26m-depth_w8a8_mix.axmodelAdded+3
ax630c/yolo26n-depth_w8a8_mix.axmodelAdded+3
ax630c/yolo26s-depth_w8a8_mix.axmodelAdded+3
ax630c/yolo26x-depth_w8a8_mix.axmodelAdded+3
ax637/config.jsonAdded+56
ax637/yolo26l-depth_w8a8_mix.axmodelAdded+3
ax637/yolo26m-depth_w8a8_mix.axmodelAdded+3
ax637/yolo26n-depth_w8a8_mix.axmodelAdded+3
ax637/yolo26s-depth_w8a8_mix.axmodelAdded+3
ax637/yolo26x-depth_w8a8_mix.axmodelAdded+3
ax8850n/config.jsonAdded+56
ax8850n/yolo26l-depth_w8a8_mix.axmodelAdded+3
ax8850n/yolo26m-depth_w8a8_mix.axmodelAdded+3
ax8850n/yolo26n-depth_w8a8_mix.axmodelAdded+3
ax8850n/yolo26s-depth_w8a8_mix.axmodelAdded+3
ax8850n/yolo26x-depth_w8a8_mix.axmodelAdded+3
axengine-0.1.3-py3-none-any.whlAdded
calib_data.zipAdded+3
fold_depth_log.pyAdded+93
infer_depth.pyAdded+228
onnx/yolo26l-depth.onnxAdded+3
onnx/yolo26m-depth.onnxAdded+3
onnx/yolo26n-depth.onnxAdded+3
onnx/yolo26s-depth.onnxAdded+3
onnx/yolo26x-depth.onnxAdded+3
requirements.txtAdded+6