Skip to main content

visloc_objects/
yolox_onnx.rs

1//! YOLOX inference with ONNX Runtime.
2//!
3//! With the `onnx-inference` feature, [`YoloxOnnxDetector`] wraps an
4//! `ort` session on the CPU and runs an official YOLOX ONNX model (see
5//! [`yolox`](crate::yolox) for the contract). Without it, every method returns
6//! [`YoloxOnnxError::FeatureDisabled`], so callers compile without `ort`.
7//!
8//! The models are not bundled. The official ones are on the YOLOX releases
9//! page (`yolox_nano.onnx` … `yolox_x.onnx`). `ort` loads the ONNX Runtime
10//! library at run time, from `ORT_DYLIB_PATH` or the system library path,
11//! as for the other ONNX models in this repository.
12
13use std::fmt;
14use std::path::Path;
15
16use crate::bbox::Detection;
17use crate::detector::ObjectDetector;
18use crate::image::RgbImage;
19use crate::yolox::{YoloxConfig, YoloxOutputError};
20
21/// A YOLOX ONNX model behind the [`ObjectDetector`] trait.
22pub struct YoloxOnnxDetector {
23    config: YoloxConfig,
24    #[cfg(feature = "onnx-inference")]
25    session: ort::session::Session,
26}
27
28impl fmt::Debug for YoloxOnnxDetector {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        f.debug_struct("YoloxOnnxDetector")
31            .field("config", &self.config)
32            .field("onnx_inference_feature", &cfg!(feature = "onnx-inference"))
33            .finish()
34    }
35}
36
37/// Errors of [`YoloxOnnxDetector`].
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum YoloxOnnxError {
40    /// The `onnx-inference` feature was not compiled in.
41    FeatureDisabled,
42    /// The image has zero width or height.
43    EmptyImage,
44    /// The model output is missing or does not fit the configured input size.
45    Output(String),
46    /// An ONNX Runtime error, for example an input size the model rejects.
47    OnnxRuntime(String),
48}
49
50impl fmt::Display for YoloxOnnxError {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Self::FeatureDisabled => write!(
54                f,
55                "YOLOX ONNX inference needs the `onnx-inference` feature of visloc-objects"
56            ),
57            Self::EmptyImage => write!(f, "the image has zero width or height"),
58            Self::Output(message) => write!(f, "unexpected YOLOX output: {message}"),
59            Self::OnnxRuntime(message) => write!(f, "ONNX Runtime error: {message}"),
60        }
61    }
62}
63
64impl std::error::Error for YoloxOnnxError {}
65
66#[cfg(feature = "onnx-inference")]
67fn runtime_error<E: fmt::Display>(error: E) -> YoloxOnnxError {
68    YoloxOnnxError::OnnxRuntime(error.to_string())
69}
70
71impl From<YoloxOutputError> for YoloxOnnxError {
72    fn from(error: YoloxOutputError) -> Self {
73        Self::Output(error.to_string())
74    }
75}
76
77impl YoloxOnnxDetector {
78    pub fn config(&self) -> &YoloxConfig {
79        &self.config
80    }
81
82    /// Change the thresholds; the input size must stay the model's.
83    pub fn config_mut(&mut self) -> &mut YoloxConfig {
84        &mut self.config
85    }
86}
87
88#[cfg(not(feature = "onnx-inference"))]
89impl YoloxOnnxDetector {
90    /// Load a YOLOX ONNX model. `config` must have the model's input size
91    /// (416 × 416 for nano and tiny, 640 × 640 for the others).
92    ///
93    /// **Stub:** without the `onnx-inference` feature this always fails.
94    pub fn load_from_path<P: AsRef<Path>>(
95        _path: P,
96        _config: YoloxConfig,
97    ) -> Result<Self, YoloxOnnxError> {
98        Err(YoloxOnnxError::FeatureDisabled)
99    }
100}
101
102#[cfg(feature = "onnx-inference")]
103impl YoloxOnnxDetector {
104    /// Load a YOLOX ONNX model. `config` must have the model's input size
105    /// (416 × 416 for nano and tiny, 640 × 640 for the others).
106    pub fn load_from_path<P: AsRef<Path>>(
107        path: P,
108        config: YoloxConfig,
109    ) -> Result<Self, YoloxOnnxError> {
110        let session = ort::session::Session::builder()
111            .map_err(runtime_error)?
112            // `All` rather than `Level3`, which ONNX Runtime 1.22 rejects (see
113            // visloc-vision's SuperPoint session).
114            .with_optimization_level(ort::session::builder::GraphOptimizationLevel::All)
115            .map_err(runtime_error)?
116            .commit_from_file(path.as_ref())
117            .map_err(runtime_error)?;
118        Ok(Self { config, session })
119    }
120
121    fn run(&mut self, image: &RgbImage) -> Result<Vec<Detection>, YoloxOnnxError> {
122        if image.width() == 0 || image.height() == 0 {
123            return Err(YoloxOnnxError::EmptyImage);
124        }
125        let (width, height) = (self.config.input_width, self.config.input_height);
126        let input = crate::yolox::letterbox(image, width, height);
127        let tensor = ort::value::Tensor::from_array((
128            [1usize, 3, height, width],
129            input.tensor.into_boxed_slice(),
130        ))
131        .map_err(runtime_error)?;
132        let outputs = self
133            .session
134            .run(ort::inputs![tensor])
135            .map_err(runtime_error)?;
136        if outputs.len() == 0 {
137            return Err(YoloxOnnxError::Output(
138                "the model has no outputs".to_string(),
139            ));
140        }
141        let (_, values) = outputs[0]
142            .try_extract_tensor::<f32>()
143            .map_err(runtime_error)?;
144        Ok(crate::yolox::decode(values, &self.config, input.scale)?)
145    }
146}
147
148impl ObjectDetector for YoloxOnnxDetector {
149    type Error = YoloxOnnxError;
150
151    /// Detections in `image` pixels, sorted by score.
152    fn detect(&mut self, image: &RgbImage) -> Result<Vec<Detection>, Self::Error> {
153        #[cfg(feature = "onnx-inference")]
154        {
155            self.run(image)
156        }
157        #[cfg(not(feature = "onnx-inference"))]
158        {
159            let _ = image;
160            Err(YoloxOnnxError::FeatureDisabled)
161        }
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    #[cfg(not(feature = "onnx-inference"))]
168    #[test]
169    fn without_the_feature_loading_fails_cleanly() {
170        let error = super::YoloxOnnxDetector::load_from_path("missing.onnx", Default::default())
171            .unwrap_err();
172        assert_eq!(error, super::YoloxOnnxError::FeatureDisabled);
173        assert!(error.to_string().contains("onnx-inference"));
174    }
175}