I have a small detection service in Python: read a frame from an RTSP camera, run a YOLO model with ONNX Runtime, publish detections to MQTT. It works. But the Python environment with OpenCV, NumPy and ONNX Runtime is large, and I wanted a single binary that I can copy to a machine. So I tried the same inference in Rust with the ort crate.
ort wraps the official ONNX Runtime C library. Version 2.0 has been in release candidate state for a while. I used 2.0.0-rc.9 (November 2024). The API changed between release candidates, so pin the exact version. The code below is for rc.9.
Export the model
YOLO11 from Ultralytics came out in September 2024. Export the nano model with the ultralytics Python package. This is the only Python step.
pip install ultralytics
yolo export model=yolo11n.pt format=onnx imgsz=640
This writes yolo11n.onnx. The input is named images with shape [1, 3, 640, 640], and the output output0 has shape [1, 84, 8400]: for each of 8400 candidate boxes, 4 box values (center x, center y, width, height in input pixels) and 80 class scores. You can check the names in Netron if your export is different.
Cargo.toml
[package]
name = "detect"
version = "0.1.0"
edition = "2021"
[dependencies]
ort = "=2.0.0-rc.9"
ndarray = "0.16"
image = "0.25"
anyhow = "1"
By default ort downloads a prebuilt ONNX Runtime library at build time (the download-binaries feature). That worked on my x86_64 Linux laptop without any setup. If there is no prebuilt binary for your platform, or you want to use a specific ONNX Runtime build, use the load-dynamic feature and point ORT_DYLIB_PATH to the .so file at runtime.
The ndarray version must match the one ort uses (0.16 for rc.9). With a different version, you get confusing trait errors when you pass arrays to the session.
The code
use anyhow::Result;
use image::imageops::FilterType;
use ndarray::{s, Array4, Ix2};
use ort::session::{builder::GraphOptimizationLevel, Session};
const SIZE: u32 = 640;
const CONF: f32 = 0.4;
const IOU: f32 = 0.5;
#[derive(Debug, Clone, Copy)]
struct Det {
x1: f32,
y1: f32,
x2: f32,
y2: f32,
class: usize,
score: f32,
}
fn iou(a: &Det, b: &Det) -> f32 {
let w = (a.x2.min(b.x2) - a.x1.max(b.x1)).max(0.0);
let h = (a.y2.min(b.y2) - a.y1.max(b.y1)).max(0.0);
let inter = w * h;
let area_a = (a.x2 - a.x1) * (a.y2 - a.y1);
let area_b = (b.x2 - b.x1) * (b.y2 - b.y1);
inter / (area_a + area_b - inter)
}
fn main() -> Result<()> {
let session = Session::builder()?
.with_optimization_level(GraphOptimizationLevel::Level3)?
.with_intra_threads(4)?
.commit_from_file("yolo11n.onnx")?;
// 1. Preprocess: resize to 640x640, RGB, CHW, 0..1
let img = image::open("frame.jpg")?;
let (orig_w, orig_h) = (img.width() as f32, img.height() as f32);
let rgb = img.resize_exact(SIZE, SIZE, FilterType::Triangle).to_rgb8();
let mut input = Array4::<f32>::zeros((1, 3, SIZE as usize, SIZE as usize));
for (x, y, px) in rgb.enumerate_pixels() {
for c in 0..3 {
input[[0, c, y as usize, x as usize]] = px[c] as f32 / 255.0;
}
}
// 2. Run
let outputs = session.run(ort::inputs!["images" => input.view()]?)?;
let raw = outputs["output0"].try_extract_tensor::<f32>()?; // [1, 84, 8400]
let pred = raw.slice(s![0, .., ..]).into_dimensionality::<Ix2>()?; // [84, 8400]
// 3. Decode candidates
let sx = orig_w / SIZE as f32;
let sy = orig_h / SIZE as f32;
let mut dets = Vec::new();
for i in 0..pred.shape()[1] {
let col = pred.column(i);
let (class, score) = col
.iter()
.skip(4)
.copied()
.enumerate()
.fold((0, f32::MIN), |best, (c, s)| if s > best.1 { (c, s) } else { best });
if score < CONF {
continue;
}
let (cx, cy, w, h) = (col[0], col[1], col[2], col[3]);
dets.push(Det {
x1: (cx - w / 2.0) * sx,
y1: (cy - h / 2.0) * sy,
x2: (cx + w / 2.0) * sx,
y2: (cy + h / 2.0) * sy,
class,
score,
});
}
// 4. Non-maximum suppression, per class
dets.sort_by(|a, b| b.score.total_cmp(&a.score));
let mut keep: Vec<Det> = Vec::new();
for d in dets {
if keep.iter().all(|k| k.class != d.class || iou(k, &d) < IOU) {
keep.push(d);
}
}
for d in &keep {
println!(
"class={} score={:.2} box=({:.0},{:.0})-({:.0},{:.0})",
d.class, d.score, d.x1, d.y1, d.x2, d.y2
);
}
Ok(())
}
Class 0 is person in the COCO label list. I keep the 80 labels in a separate file and look them up by index.
Things that cost me time
Resize method and letterboxing. resize_exact stretches the image. Ultralytics uses letterboxing (keep the aspect ratio, pad with gray) during its own inference. Stretching works for a quick test, and the box scaling above matches it. But for a 16:9 camera, objects get squeezed, and small objects are detected a bit worse. For the real service, I letterbox and then subtract the padding when I scale the boxes back. I left it out here to keep the example readable.
Wrong channel order. If you load frames from OpenCV bindings instead of the image crate, they are BGR. The model wants RGB. The model still returns boxes with BGR input, just worse ones, so this error is easy to miss.
The pixel loop is slow in debug builds. Always test speed with cargo run --release. In a debug build, the preprocessing loop can take longer than the inference itself, because the inference runs in the optimized C++ library and the loop does not.
try_extract_tensor returns a view tied to outputs. You cannot return it from a function after outputs is dropped. Copy what you need (to_owned()) or decode inside the same scope.
Was it worth it
The release binary plus the ONNX Runtime shared library is much smaller than my Python environment, and startup is fast. The code is longer than the Python version, mostly because NumPy makes the decoding a few lines. For a service that runs for months on a small machine, I prefer the Rust version. For experiments with new models, I still use Python first.
For a Raspberry Pi (aarch64), check first whether the prebuilt download works there. If it does not, the load-dynamic feature with an ONNX Runtime build for ARM is the fallback.
ort 2.0 is still a release candidate, and the API changed between candidates, so pin the exact version in Cargo.toml.