use super::GrayscaleImage;
use std::fmt;
use std::path::Path;
#[cfg(feature = "onnx-inference")]
use std::sync::{Arc, Mutex};
#[cfg(feature = "onnx-inference")]
pub use super::superpoint_onnx::OnnxBackend;
#[derive(Clone)]
pub struct GlobalDescriptorOnnxExtractor {
#[cfg(feature = "onnx-inference")]
session: Arc<Mutex<ort::session::Session>>,
#[cfg(not(feature = "onnx-inference"))]
_private: (),
}
impl fmt::Debug for GlobalDescriptorOnnxExtractor {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("GlobalDescriptorOnnxExtractor")
.field("onnx_inference_feature", &cfg!(feature = "onnx-inference"))
.finish()
}
}
#[cfg(not(feature = "onnx-inference"))]
impl GlobalDescriptorOnnxExtractor {
pub fn load_from_path<P: AsRef<Path>>(_path: P) -> Result<Self, GlobalDescriptorOnnxError> {
Err(GlobalDescriptorOnnxError::FeatureDisabled {
requested: "load_from_path",
})
}
pub const fn extract_global(
&self,
_image: &GrayscaleImage,
) -> Result<Vec<f32>, GlobalDescriptorOnnxError> {
Err(GlobalDescriptorOnnxError::FeatureDisabled {
requested: "extract_global",
})
}
}
#[cfg(feature = "onnx-inference")]
impl GlobalDescriptorOnnxExtractor {
pub fn load_from_path<P: AsRef<Path>>(path: P) -> Result<Self, GlobalDescriptorOnnxError> {
Self::load_from_path_with_backend(path, OnnxBackend::default())
}
pub fn load_from_path_with_backend<P: AsRef<Path>>(
path: P,
backend: OnnxBackend,
) -> Result<Self, GlobalDescriptorOnnxError> {
let providers = super::superpoint_onnx::execution_providers(backend)
.map_err(GlobalDescriptorOnnxError::from_ort)?;
let session = ort::session::Session::builder()
.map_err(GlobalDescriptorOnnxError::from_ort)?
.with_optimization_level(ort::session::builder::GraphOptimizationLevel::All)
.map_err(GlobalDescriptorOnnxError::from_ort)?
.with_execution_providers(providers)
.map_err(GlobalDescriptorOnnxError::from_ort)?
.commit_from_file(path.as_ref())
.map_err(GlobalDescriptorOnnxError::from_ort)?;
Ok(Self {
session: Arc::new(Mutex::new(session)),
})
}
pub fn extract_global(
&self,
image: &GrayscaleImage,
) -> Result<Vec<f32>, GlobalDescriptorOnnxError> {
let width = image.width();
let height = image.height();
if width == 0 || height == 0 {
return Err(GlobalDescriptorOnnxError::EmptyImage);
}
let plane = image.pixels();
let mut chw = Vec::with_capacity(3 * plane.len());
for _ in 0..3 {
chw.extend_from_slice(plane);
}
let input = ndarray::Array4::<f32>::from_shape_vec((1, 3, height, width), chw).map_err(
|error| GlobalDescriptorOnnxError::PreprocessShape {
width,
height,
message: error.to_string(),
},
)?;
let input_value =
ort::value::Tensor::from_array(input).map_err(GlobalDescriptorOnnxError::from_ort)?;
let mut session = self
.session
.lock()
.map_err(|error| GlobalDescriptorOnnxError::OnnxRuntime(error.to_string()))?;
let mut outputs = session
.run(ort::inputs![input_value])
.map_err(GlobalDescriptorOnnxError::from_ort)?;
let value = outputs.remove("descriptor").ok_or_else(|| {
GlobalDescriptorOnnxError::OutputShapeMismatch {
expected: "output named `descriptor`",
actual: "missing".to_string(),
}
})?;
let array: ndarray::ArrayD<f32> = value
.try_extract_array::<f32>()
.map_err(GlobalDescriptorOnnxError::from_ort)?
.into_owned();
let shape = array.shape().to_vec();
let descriptor: Vec<f32> = match shape.as_slice() {
[1, _d] => array.iter().copied().collect(),
[_d] => array.iter().copied().collect(),
_ => {
return Err(GlobalDescriptorOnnxError::OutputShapeMismatch {
expected: "(1, D) or (D,) descriptor",
actual: format!("{shape:?}"),
})
}
};
Ok(descriptor)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GlobalDescriptorOnnxError {
FeatureDisabled { requested: &'static str },
EmptyImage,
PreprocessShape {
width: usize,
height: usize,
message: String,
},
OutputShapeMismatch {
expected: &'static str,
actual: String,
},
OnnxRuntime(String),
}
#[cfg(feature = "onnx-inference")]
impl GlobalDescriptorOnnxError {
fn from_ort<E: std::fmt::Display>(error: E) -> Self {
GlobalDescriptorOnnxError::OnnxRuntime(error.to_string())
}
}
impl fmt::Display for GlobalDescriptorOnnxError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GlobalDescriptorOnnxError::FeatureDisabled { requested } => write!(
formatter,
"global-descriptor ONNX runtime unavailable: `{requested}` requires the \
`onnx-inference` feature"
),
GlobalDescriptorOnnxError::EmptyImage => {
write!(formatter, "input image has zero width or height")
}
GlobalDescriptorOnnxError::PreprocessShape {
width,
height,
message,
} => write!(
formatter,
"failed to build (1, 3, {height}, {width}) input tensor: {message}"
),
GlobalDescriptorOnnxError::OutputShapeMismatch { expected, actual } => {
write!(
formatter,
"unexpected model output: expected {expected}, got {actual}"
)
}
GlobalDescriptorOnnxError::OnnxRuntime(message) => {
write!(formatter, "ONNX Runtime error: {message}")
}
}
}
}
impl std::error::Error for GlobalDescriptorOnnxError {}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(feature = "onnx-inference"))]
#[test]
fn load_without_feature_reports_disabled() {
let result = GlobalDescriptorOnnxExtractor::load_from_path("/nonexistent.onnx");
assert_eq!(
result.err(),
Some(GlobalDescriptorOnnxError::FeatureDisabled {
requested: "load_from_path"
})
);
}
#[test]
fn error_display_is_descriptive() {
let error = GlobalDescriptorOnnxError::OutputShapeMismatch {
expected: "(1, D) or (D,) descriptor",
actual: "[2, 3, 4]".to_string(),
};
let text = error.to_string();
assert!(text.contains("unexpected model output"));
assert!(text.contains("(1, D)"));
}
}