1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
| use ort::{session::Session, GraphOptimizationLevel, value::Value, Tensor};
use image::{imageops::FilterType, GenericImageView, Pixel};
use ndarray::{s, Array, Array4, Axis};
use std::path::Path;
use std::time::Instant;
// ========== Configuration ==========
const MODEL_PATH: &str = "yolo26n.onnx";
const INPUT_SIZE: usize = 640;
const CONF_THRESH: f32 = 0.25;
const IOU_THRESH: f32 = 0.45;
#[derive(Debug, Clone)]
struct Detection {
x1: f32,
y1: f32,
x2: f32,
y2: f32,
confidence: f32,
class_id: usize,
class_name: &'static str,
}
// COCO 80 class names
const CLASS_NAMES: [&str; 80] = [
"person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat",
"traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat",
"dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack",
"umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball",
"kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket",
"bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
"sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake",
"chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop",
"mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink",
"refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier",
"toothbrush",
];
fn main() -> anyhow::Result<()> {
// 1. Create session
let session = Session::builder()?
.with_optimization_level(GraphOptimizationLevel::Level3)?
.with_intra_threads(8)?
.commit_from_file(MODEL_PATH)?;
println!("✅ YOLO26 Rust inference ready");
// 2. Load and preprocess image
let img_path = "test.jpg";
let img = image::open(img_path)?;
let (orig_w, orig_h) = (img.width() as f32, img.height() as f32);
let start = Instant::now();
// 3. Preprocessing
let input = preprocess(&img);
// 4. Inference
let input_value = Tensor::from_array(input)?;
let outputs = session.run(ort::inputs!["images" => input_value]?)?;
// 5. Post-processing
let output = outputs["output0"].try_extract_tensor::<f32>()?;
let detections = postprocess(output.view(), orig_w, orig_h);
let elapsed = start.elapsed();
// 6. Output results
println!("\n📊 Detection completed, elapsed: {:?}", elapsed);
println!("Total detections: {}\n", detections.len());
for (i, det) in detections.iter().enumerate() {
println!(
"{:2}. {:<15} Confidence: {:.3} Location: [{:.0}, {:.0}, {:.0}, {:.0}]",
i + 1, det.class_name, det.confidence, det.x1, det.y1, det.x2, det.y2
);
}
Ok(())
}
/// Image preprocessing: Resize + normalization + NCHW format
fn preprocess(img: &image::DynamicImage) -> Array4<f32> {
// Resize to 640x640
let resized = img.resize_exact(
INPUT_SIZE as u32,
INPUT_SIZE as u32,
FilterType::CatmullRom,
);
// Create NCHW format array [1, 3, H, W]
let mut input = Array::zeros((1, 3, INPUT_SIZE, INPUT_SIZE));
for y in 0..INPUT_SIZE {
for x in 0..INPUT_SIZE {
let pixel = resized.get_pixel(x as u32, y as u32).to_rgb();
input[[0, 0, y, x]] = pixel[0] as f32 / 255.0;
input[[0, 1, y, x]] = pixel[1] as f32 / 255.0;
input[[0, 2, y, x]] = pixel[2] as f32 / 255.0;
}
}
input
}
/// Post-processing: Parse output + NMS
fn postprocess(
output: ndarray::ArrayView3<'_, f32>,
orig_w: f32,
orig_h: f32,
) -> Vec<Detection> {
let scale_x = orig_w / INPUT_SIZE as f32;
let scale_y = orig_h / INPUT_SIZE as f32;
let mut detections = Vec::new();
// Output shape [1, 84, 8400] -> transpose to [8400, 84]
let output = output.permuted_axes((1, 2, 0)).remove_axis(Axis(2));
for i in 0..8400 {
let row = output.slice(s![i, ..]);
// Find maximum confidence
let (class_id, confidence) = (4..84)
.map(|c| (c - 4, row[c]))
.max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
.unwrap();
if confidence < CONF_THRESH {
continue;
}
// Parse coordinates cx, cy, w, h
let cx = row[0] * scale_x;
let cy = row[1] * scale_y;
let w = row[2] * scale_x;
let h = row[3] * scale_y;
detections.push(Detection {
x1: cx - w / 2.0,
y1: cy - h / 2.0,
x2: cx + w / 2.0,
y2: cy + h / 2.0,
confidence,
class_id,
class_name: CLASS_NAMES[class_id],
});
}
// NMS non-maximum suppression
nms(&mut detections, IOU_THRESH)
}
/// Non-maximum suppression (efficient Rust implementation)
fn nms(detections: &mut Vec<Detection>, iou_thresh: f32) -> Vec<Detection> {
// Sort by confidence descending
detections.sort_by(|a, b| b.confidence.partial_cmp(&a.confidence).unwrap());
let mut keep = Vec::new();
let mut suppressed = vec![false; detections.len()];
for i in 0..detections.len() {
if suppressed[i] {
continue;
}
keep.push(detections[i].clone());
for j in (i + 1)..detections.len() {
if suppressed[j] {
continue;
}
if calculate_iou(&detections[i], &detections[j]) > iou_thresh {
suppressed[j] = true;
}
}
}
keep
}
fn calculate_iou(a: &Detection, b: &Detection) -> f32 {
let x1 = a.x1.max(b.x1);
let y1 = a.y1.max(b.y1);
let x2 = a.x2.min(b.x2);
let y2 = a.y2.min(b.y2);
if x2 <= x1 || y2 <= y1 {
return 0.0;
}
let intersection = (x2 - x1) * (y2 - y1);
let area_a = (a.x2 - a.x1) * (a.y2 - a.y1);
let area_b = (b.x2 - b.x1) * (b.y2 - b.y1);
intersection / (area_a + area_b - intersection)
}
|