1use std::fmt;
22
23use crate::bbox::{BBox, Detection};
24use crate::image::RgbImage;
25
26pub const COCO_CLASSES: [&str; 80] = [
28 "person",
29 "bicycle",
30 "car",
31 "motorcycle",
32 "airplane",
33 "bus",
34 "train",
35 "truck",
36 "boat",
37 "traffic light",
38 "fire hydrant",
39 "stop sign",
40 "parking meter",
41 "bench",
42 "bird",
43 "cat",
44 "dog",
45 "horse",
46 "sheep",
47 "cow",
48 "elephant",
49 "bear",
50 "zebra",
51 "giraffe",
52 "backpack",
53 "umbrella",
54 "handbag",
55 "tie",
56 "suitcase",
57 "frisbee",
58 "skis",
59 "snowboard",
60 "sports ball",
61 "kite",
62 "baseball bat",
63 "baseball glove",
64 "skateboard",
65 "surfboard",
66 "tennis racket",
67 "bottle",
68 "wine glass",
69 "cup",
70 "fork",
71 "knife",
72 "spoon",
73 "bowl",
74 "banana",
75 "apple",
76 "sandwich",
77 "orange",
78 "broccoli",
79 "carrot",
80 "hot dog",
81 "pizza",
82 "donut",
83 "cake",
84 "chair",
85 "couch",
86 "potted plant",
87 "bed",
88 "dining table",
89 "toilet",
90 "tv",
91 "laptop",
92 "mouse",
93 "remote",
94 "keyboard",
95 "cell phone",
96 "microwave",
97 "oven",
98 "toaster",
99 "sink",
100 "refrigerator",
101 "book",
102 "clock",
103 "vase",
104 "scissors",
105 "teddy bear",
106 "hair drier",
107 "toothbrush",
108];
109
110pub const MOVABLE_COCO_CLASSES: [u32; 18] = [
114 0, 1, 2, 3, 4, 5, 6, 7,
115 8, 14, 15, 16, 17, 18, 19, 20, 21,
117 22, ];
119
120#[derive(Debug, Clone, PartialEq)]
122pub struct YoloxConfig {
123 pub input_width: usize,
124 pub input_height: usize,
125 pub strides: Vec<usize>,
127 pub score_threshold: f64,
129 pub nms_threshold: f64,
132}
133
134impl Default for YoloxConfig {
135 fn default() -> Self {
136 Self {
137 input_width: 640,
138 input_height: 640,
139 strides: vec![8, 16, 32],
140 score_threshold: 0.1,
141 nms_threshold: 0.45,
142 }
143 }
144}
145
146impl YoloxConfig {
147 pub fn anchor_count(&self) -> usize {
149 self.strides
150 .iter()
151 .map(|s| (self.input_width / s) * (self.input_height / s))
152 .sum()
153 }
154}
155
156#[derive(Debug, Clone, PartialEq)]
158pub struct Letterbox {
159 pub tensor: Vec<f32>,
161 pub scale: f64,
163}
164
165pub fn letterbox(image: &RgbImage, input_width: usize, input_height: usize) -> Letterbox {
170 let (width, height) = (image.width(), image.height());
171 let plane = input_width * input_height;
172 let mut tensor = vec![114.0f32; 3 * plane];
173 if width == 0 || height == 0 || plane == 0 {
174 return Letterbox { tensor, scale: 1.0 };
175 }
176 let scale = (input_height as f64 / height as f64).min(input_width as f64 / width as f64);
177 let resized_width = ((width as f64 * scale) as usize).min(input_width);
178 let resized_height = ((height as f64 * scale) as usize).min(input_height);
179 let xs = sample_positions(resized_width, width);
180 let ys = sample_positions(resized_height, height);
181 let data = image.data();
182 for (y, &(y0, y1, fy)) in ys.iter().enumerate() {
183 for (x, &(x0, x1, fx)) in xs.iter().enumerate() {
184 for (bgr, rgb) in [2usize, 1, 0].into_iter().enumerate() {
185 let at = |row: usize, col: usize| data[3 * (row * width + col) + rgb] as f32;
186 let top = at(y0, x0) * (1.0 - fx) + at(y0, x1) * fx;
187 let bottom = at(y1, x0) * (1.0 - fx) + at(y1, x1) * fx;
188 tensor[bgr * plane + y * input_width + x] = top * (1.0 - fy) + bottom * fy;
189 }
190 }
191 }
192 Letterbox { tensor, scale }
193}
194
195fn sample_positions(output: usize, input: usize) -> Vec<(usize, usize, f32)> {
197 let ratio = input as f64 / output as f64;
198 (0..output)
199 .map(|i| {
200 let position = ((i as f64 + 0.5) * ratio - 0.5).clamp(0.0, (input - 1) as f64);
201 let first = position.floor() as usize;
202 let second = (first + 1).min(input - 1);
203 (first, second, (position - first as f64) as f32)
204 })
205 .collect()
206}
207
208#[derive(Debug, Clone, PartialEq, Eq)]
210pub struct YoloxOutputError {
211 pub expected_anchors: usize,
212 pub len: usize,
213}
214
215impl fmt::Display for YoloxOutputError {
216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 write!(
218 f,
219 "YOLOX output of {} values is not {} anchors × (5 + classes)",
220 self.len, self.expected_anchors
221 )
222 }
223}
224
225impl std::error::Error for YoloxOutputError {}
226
227pub fn decode(
230 output: &[f32],
231 config: &YoloxConfig,
232 scale: f64,
233) -> Result<Vec<Detection>, YoloxOutputError> {
234 let anchors = config.anchor_count();
235 let error = YoloxOutputError {
236 expected_anchors: anchors,
237 len: output.len(),
238 };
239 if anchors == 0 || !output.len().is_multiple_of(anchors) || output.len() / anchors <= 5 {
240 return Err(error);
241 }
242 let columns = output.len() / anchors;
243 let mut candidates: Vec<Vec<Detection>> = vec![Vec::new(); columns - 5];
244 let mut rows = output.chunks_exact(columns);
245 for &stride in &config.strides {
246 let grid_width = config.input_width / stride;
247 let grid_height = config.input_height / stride;
248 let s = stride as f32;
249 for gy in 0..grid_height {
250 for gx in 0..grid_width {
251 let row = rows.next().ok_or_else(|| error.clone())?;
252 let cx = (row[0] + gx as f32) * s;
253 let cy = (row[1] + gy as f32) * s;
254 let w = row[2].exp() * s;
255 let h = row[3].exp() * s;
256 let objectness = row[4];
257 for (class, &probability) in row[5..].iter().enumerate() {
258 let score = objectness * probability;
259 if f64::from(score) <= config.score_threshold {
260 continue;
261 }
262 let bbox = BBox::new(
263 f64::from(cx - 0.5 * w) / scale,
264 f64::from(cy - 0.5 * h) / scale,
265 f64::from(cx + 0.5 * w) / scale,
266 f64::from(cy + 0.5 * h) / scale,
267 );
268 candidates[class].push(Detection::new(bbox, f64::from(score), class as u32));
269 }
270 }
271 }
272 }
273 let mut detections: Vec<Detection> = candidates
274 .into_iter()
275 .flat_map(|boxes| non_maximum_suppression(boxes, config.nms_threshold))
276 .collect();
277 detections.sort_by(|a, b| b.score.total_cmp(&a.score));
278 Ok(detections)
279}
280
281pub fn non_maximum_suppression(mut boxes: Vec<Detection>, iou_threshold: f64) -> Vec<Detection> {
284 boxes.sort_by(|a, b| b.score.total_cmp(&a.score));
285 let mut kept: Vec<Detection> = Vec::new();
286 for candidate in boxes {
287 if kept
288 .iter()
289 .all(|k| k.bbox.iou(&candidate.bbox) <= iou_threshold)
290 {
291 kept.push(candidate);
292 }
293 }
294 kept
295}
296
297#[cfg(test)]
298mod tests {
299 use super::*;
300
301 #[test]
302 fn letterbox_keeps_the_aspect_ratio_and_pads_with_114() {
303 let mut data = Vec::new();
305 for _ in 0..2 {
306 for x in 0..4 {
307 data.extend_from_slice(if x < 2 { &[255, 0, 0] } else { &[0, 0, 255] });
308 }
309 }
310 let image = RgbImage::new(4, 2, data).unwrap();
311 let input = letterbox(&image, 8, 8);
312 assert_eq!(input.scale, 2.0);
313 let at = |c: usize, y: usize, x: usize| input.tensor[c * 64 + y * 8 + x];
314 assert_eq!((at(0, 0, 0), at(2, 0, 0)), (0.0, 255.0));
316 assert_eq!((at(0, 3, 7), at(2, 3, 7)), (255.0, 0.0));
317 assert!(at(2, 1, 4) > 0.0 && at(2, 1, 4) < 255.0);
319 assert!((0..3).all(|c| at(c, 4, 0) == 114.0 && at(c, 7, 7) == 114.0));
321 }
322
323 #[test]
324 fn decode_places_a_box_from_its_grid_cell_and_stride() {
325 let config = YoloxConfig {
326 input_width: 64,
327 input_height: 64,
328 score_threshold: 0.3,
329 ..YoloxConfig::default()
330 };
331 assert_eq!(config.anchor_count(), 84);
333 let mut output = vec![0.0f32; 84 * 7];
334 let row = &mut output[73 * 7..74 * 7];
336 row.copy_from_slice(&[0.5, 0.25, 2.0f32.ln(), 1.0f32.ln(), 0.9, 0.2, 0.8]);
337 let detections = decode(&output, &config, 2.0).unwrap();
338 assert_eq!(detections.len(), 1, "{detections:?}");
339 let d = detections[0];
340 assert_eq!(d.class_id, 1);
341 assert!((d.score - 0.72).abs() < 1e-6);
342 let expected = BBox::new(4.0, 14.0, 20.0, 22.0);
344 for (a, b) in [
345 (d.bbox.x_min, expected.x_min),
346 (d.bbox.y_min, expected.y_min),
347 (d.bbox.x_max, expected.x_max),
348 (d.bbox.y_max, expected.y_max),
349 ] {
350 assert!((a - b).abs() < 1e-4, "{:?}", d.bbox);
351 }
352 }
353
354 #[test]
355 fn decode_rejects_an_output_of_the_wrong_size() {
356 let config = YoloxConfig::default();
357 assert!(decode(&[0.0; 100], &config, 1.0).is_err());
358 assert!(decode(&vec![0.0; config.anchor_count() * 5], &config, 1.0).is_err());
359 }
360
361 #[test]
362 fn suppression_is_per_class_and_keeps_the_best_box() {
363 let b = |x: f64| BBox::from_xywh(x, 0.0, 10.0, 10.0);
364 let boxes = vec![
365 Detection::new(b(1.0), 0.6, 0),
366 Detection::new(b(0.0), 0.9, 0),
367 Detection::new(b(30.0), 0.5, 0),
368 ];
369 let kept = non_maximum_suppression(boxes, 0.45);
370 assert_eq!(kept.len(), 2);
371 assert_eq!(kept[0].score, 0.9);
372 let config = YoloxConfig {
374 input_width: 32,
375 input_height: 32,
376 strides: vec![32],
377 score_threshold: 0.1,
378 nms_threshold: 0.45,
379 };
380 let output = [0.5, 0.5, 0.0, 0.0, 1.0, 0.9, 0.8];
381 let detections = decode(&output, &config, 1.0).unwrap();
382 assert_eq!(
383 detections.iter().map(|d| d.class_id).collect::<Vec<_>>(),
384 vec![0, 1]
385 );
386 }
387}