use std::fmt;
use std::path::Path;
use crate::bbox::Detection;
use crate::detector::ObjectDetector;
use crate::image::RgbImage;
use crate::yolox::{YoloxConfig, YoloxOutputError};
pub struct YoloxOnnxDetector {
config: YoloxConfig,
#[cfg(feature = "onnx-inference")]
session: ort::session::Session,
}
impl fmt::Debug for YoloxOnnxDetector {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("YoloxOnnxDetector")
.field("config", &self.config)
.field("onnx_inference_feature", &cfg!(feature = "onnx-inference"))
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum YoloxOnnxError {
FeatureDisabled,
EmptyImage,
Output(String),
OnnxRuntime(String),
}
impl fmt::Display for YoloxOnnxError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::FeatureDisabled => write!(
f,
"YOLOX ONNX inference needs the `onnx-inference` feature of visloc-objects"
),
Self::EmptyImage => write!(f, "the image has zero width or height"),
Self::Output(message) => write!(f, "unexpected YOLOX output: {message}"),
Self::OnnxRuntime(message) => write!(f, "ONNX Runtime error: {message}"),
}
}
}
impl std::error::Error for YoloxOnnxError {}
#[cfg(feature = "onnx-inference")]
fn runtime_error<E: fmt::Display>(error: E) -> YoloxOnnxError {
YoloxOnnxError::OnnxRuntime(error.to_string())
}
impl From<YoloxOutputError> for YoloxOnnxError {
fn from(error: YoloxOutputError) -> Self {
Self::Output(error.to_string())
}
}
impl YoloxOnnxDetector {
pub fn config(&self) -> &YoloxConfig {
&self.config
}
pub fn config_mut(&mut self) -> &mut YoloxConfig {
&mut self.config
}
}
#[cfg(not(feature = "onnx-inference"))]
impl YoloxOnnxDetector {
pub fn load_from_path<P: AsRef<Path>>(
_path: P,
_config: YoloxConfig,
) -> Result<Self, YoloxOnnxError> {
Err(YoloxOnnxError::FeatureDisabled)
}
}
#[cfg(feature = "onnx-inference")]
impl YoloxOnnxDetector {
pub fn load_from_path<P: AsRef<Path>>(
path: P,
config: YoloxConfig,
) -> Result<Self, YoloxOnnxError> {
let session = ort::session::Session::builder()
.map_err(runtime_error)?
.with_optimization_level(ort::session::builder::GraphOptimizationLevel::All)
.map_err(runtime_error)?
.commit_from_file(path.as_ref())
.map_err(runtime_error)?;
Ok(Self { config, session })
}
fn run(&mut self, image: &RgbImage) -> Result<Vec<Detection>, YoloxOnnxError> {
if image.width() == 0 || image.height() == 0 {
return Err(YoloxOnnxError::EmptyImage);
}
let (width, height) = (self.config.input_width, self.config.input_height);
let input = crate::yolox::letterbox(image, width, height);
let tensor = ort::value::Tensor::from_array((
[1usize, 3, height, width],
input.tensor.into_boxed_slice(),
))
.map_err(runtime_error)?;
let outputs = self
.session
.run(ort::inputs![tensor])
.map_err(runtime_error)?;
if outputs.len() == 0 {
return Err(YoloxOnnxError::Output(
"the model has no outputs".to_string(),
));
}
let (_, values) = outputs[0]
.try_extract_tensor::<f32>()
.map_err(runtime_error)?;
Ok(crate::yolox::decode(values, &self.config, input.scale)?)
}
}
impl ObjectDetector for YoloxOnnxDetector {
type Error = YoloxOnnxError;
fn detect(&mut self, image: &RgbImage) -> Result<Vec<Detection>, Self::Error> {
#[cfg(feature = "onnx-inference")]
{
self.run(image)
}
#[cfg(not(feature = "onnx-inference"))]
{
let _ = image;
Err(YoloxOnnxError::FeatureDisabled)
}
}
}
#[cfg(test)]
mod tests {
#[cfg(not(feature = "onnx-inference"))]
#[test]
fn without_the_feature_loading_fails_cleanly() {
let error = super::YoloxOnnxDetector::load_from_path("missing.onnx", Default::default())
.unwrap_err();
assert_eq!(error, super::YoloxOnnxError::FeatureDisabled);
assert!(error.to_string().contains("onnx-inference"));
}
}