visloc_objects/
yolox_onnx.rs1use 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
21pub 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#[derive(Debug, Clone, PartialEq, Eq)]
39pub enum YoloxOnnxError {
40 FeatureDisabled,
42 EmptyImage,
44 Output(String),
46 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 pub fn config_mut(&mut self) -> &mut YoloxConfig {
84 &mut self.config
85 }
86}
87
88#[cfg(not(feature = "onnx-inference"))]
89impl YoloxOnnxDetector {
90 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 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 .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 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}