use super::deep::{DeepFeatureExtractor, DeepFeatureSet, DeepFeatureSetError};
use super::GrayscaleImage;
#[cfg(feature = "onnx-inference")]
use nalgebra::Point2;
use std::fmt;
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
#[cfg(feature = "onnx-inference")]
use std::sync::Mutex;
#[derive(Debug, Clone, PartialEq)]
pub struct SuperPointOnnxConfig {
pub nms_radius_pixels: u32,
pub min_score: f32,
pub max_keypoints: usize,
}
impl Default for SuperPointOnnxConfig {
fn default() -> Self {
Self {
nms_radius_pixels: 4,
min_score: 0.005,
max_keypoints: 1500,
}
}
}
#[derive(Clone)]
pub struct SuperPointOnnxExtractor {
config: SuperPointOnnxConfig,
runtime_max_keypoints: Arc<AtomicUsize>,
#[cfg(feature = "onnx-inference")]
session: Arc<Mutex<ort::session::Session>>,
}
impl fmt::Debug for SuperPointOnnxExtractor {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("SuperPointOnnxExtractor")
.field("config", &self.config)
.field("onnx_inference_feature", &cfg!(feature = "onnx-inference"))
.finish()
}
}
impl SuperPointOnnxExtractor {
pub const fn config(&self) -> &SuperPointOnnxConfig {
&self.config
}
pub fn set_runtime_max_keypoints(&self, max_keypoints: usize) {
self.runtime_max_keypoints
.store(max_keypoints, Ordering::Relaxed);
}
pub fn effective_max_keypoints(&self) -> usize {
match self.runtime_max_keypoints.load(Ordering::Relaxed) {
0 => self.config.max_keypoints,
override_value => override_value,
}
}
}
#[cfg(not(feature = "onnx-inference"))]
impl SuperPointOnnxExtractor {
pub fn load_from_path<P: AsRef<Path>>(
_path: P,
config: SuperPointOnnxConfig,
) -> Result<Self, SuperPointOnnxError> {
Err(SuperPointOnnxError::FeatureDisabled {
requested: "load_from_path",
config,
})
}
}
#[cfg(not(feature = "onnx-inference"))]
impl DeepFeatureExtractor for SuperPointOnnxExtractor {
type Image = GrayscaleImage;
type Error = SuperPointOnnxError;
fn extract_deep(&self, _image: &Self::Image) -> Result<DeepFeatureSet, Self::Error> {
Err(SuperPointOnnxError::FeatureDisabled {
requested: "extract_deep",
config: self.config.clone(),
})
}
}
#[cfg(feature = "onnx-inference")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OnnxBackend {
#[default]
CudaThenCpu,
Cuda,
Cpu,
}
#[cfg(feature = "onnx-inference")]
pub(crate) fn execution_providers(
backend: OnnxBackend,
) -> Result<Vec<ort::ep::ExecutionProviderDispatch>, String> {
use ort::ep::CPU;
match backend {
#[cfg(feature = "onnx-cuda")]
OnnxBackend::CudaThenCpu => Ok(vec![
ort::ep::CUDA::default().build(),
CPU::default().build(),
]),
#[cfg(not(feature = "onnx-cuda"))]
OnnxBackend::CudaThenCpu => Ok(vec![CPU::default().build()]),
#[cfg(feature = "onnx-cuda")]
OnnxBackend::Cuda => Ok(vec![ort::ep::CUDA::default().build().error_on_failure()]),
#[cfg(not(feature = "onnx-cuda"))]
OnnxBackend::Cuda => {
Err("the CUDA execution provider needs the `onnx-cuda` feature".to_string())
}
OnnxBackend::Cpu => Ok(vec![CPU::default().build()]),
}
}
#[cfg(feature = "onnx-inference")]
impl SuperPointOnnxExtractor {
pub fn load_from_path<P: AsRef<Path>>(
path: P,
config: SuperPointOnnxConfig,
) -> Result<Self, SuperPointOnnxError> {
Self::load_from_path_with_backend(path, config, OnnxBackend::default())
}
pub fn load_from_path_with_backend<P: AsRef<Path>>(
path: P,
config: SuperPointOnnxConfig,
backend: OnnxBackend,
) -> Result<Self, SuperPointOnnxError> {
let providers = execution_providers(backend).map_err(SuperPointOnnxError::from_ort)?;
let session = ort::session::Session::builder()
.map_err(SuperPointOnnxError::from_ort)?
.with_optimization_level(ort::session::builder::GraphOptimizationLevel::All)
.map_err(SuperPointOnnxError::from_ort)?
.with_execution_providers(providers)
.map_err(SuperPointOnnxError::from_ort)?
.commit_from_file(path.as_ref())
.map_err(SuperPointOnnxError::from_ort)?;
Ok(Self {
config,
runtime_max_keypoints: Arc::new(AtomicUsize::new(0)),
session: Arc::new(Mutex::new(session)),
})
}
}
#[cfg(feature = "onnx-inference")]
impl DeepFeatureExtractor for SuperPointOnnxExtractor {
type Image = GrayscaleImage;
type Error = SuperPointOnnxError;
fn extract_deep(&self, image: &Self::Image) -> Result<DeepFeatureSet, Self::Error> {
let width = image.width();
let height = image.height();
if width == 0 || height == 0 {
return Err(SuperPointOnnxError::EmptyImage);
}
let input =
ndarray::Array4::<f32>::from_shape_vec((1, 1, height, width), image.pixels().to_vec())
.map_err(|error| SuperPointOnnxError::PreprocessShape {
width,
height,
message: error.to_string(),
})?;
let input_value =
ort::value::Tensor::from_array(input).map_err(SuperPointOnnxError::from_ort)?;
let mut session = self
.session
.lock()
.map_err(|error| SuperPointOnnxError::OnnxRuntime(error.to_string()))?;
let mut outputs = session
.run(ort::inputs![input_value])
.map_err(SuperPointOnnxError::from_ort)?;
let (keypoints_array, scores_array, descriptors_array) =
extract_named_outputs(&mut outputs)?;
let triples = postprocess_with_cap(
keypoints_array.view(),
scores_array.view(),
descriptors_array.view(),
&self.config,
self.effective_max_keypoints(),
)?;
let (keypoints, scores, descriptors) = unzip_triples(triples);
DeepFeatureSet::new(keypoints, scores, descriptors).map_err(SuperPointOnnxError::from)
}
}
#[cfg(feature = "onnx-inference")]
type NamedOutputs = (
ndarray::Array2<i64>,
ndarray::Array1<f32>,
ndarray::Array2<f32>,
);
#[cfg(feature = "onnx-inference")]
type DecodedKeypoints = Vec<(Point2<f64>, f32, Vec<f32>)>;
#[cfg(feature = "onnx-inference")]
fn extract_named_outputs(
outputs: &mut ort::session::SessionOutputs<'_>,
) -> Result<NamedOutputs, SuperPointOnnxError> {
let kp_value =
outputs
.remove("keypoints")
.ok_or_else(|| SuperPointOnnxError::OutputShapeMismatch {
expected: "output named `keypoints`",
actual: "missing".to_string(),
})?;
let score_value =
outputs
.remove("scores")
.ok_or_else(|| SuperPointOnnxError::OutputShapeMismatch {
expected: "output named `scores`",
actual: "missing".to_string(),
})?;
let desc_value =
outputs
.remove("descriptors")
.ok_or_else(|| SuperPointOnnxError::OutputShapeMismatch {
expected: "output named `descriptors`",
actual: "missing".to_string(),
})?;
let kp_array: ndarray::ArrayD<i64> = kp_value
.try_extract_array::<i64>()
.map_err(SuperPointOnnxError::from_ort)?
.into_owned();
let score_array: ndarray::ArrayD<f32> = score_value
.try_extract_array::<f32>()
.map_err(SuperPointOnnxError::from_ort)?
.into_owned();
let desc_array: ndarray::ArrayD<f32> = desc_value
.try_extract_array::<f32>()
.map_err(SuperPointOnnxError::from_ort)?
.into_owned();
Ok((
normalise_keypoints(kp_array)?,
normalise_scores(score_array)?,
normalise_descriptors(desc_array)?,
))
}
#[cfg(feature = "onnx-inference")]
fn normalise_keypoints(
array: ndarray::ArrayD<i64>,
) -> Result<ndarray::Array2<i64>, SuperPointOnnxError> {
let shape = array.shape().to_vec();
let view = if shape.len() == 3 && shape[0] == 1 && shape[2] == 2 {
array.into_shape_with_order((shape[1], 2)).map_err(|e| {
SuperPointOnnxError::OutputShapeMismatch {
expected: "(N, 2) or (1, N, 2) keypoints",
actual: format!("{shape:?}: {e}"),
}
})?
} else if shape.len() == 2 && shape[1] == 2 {
array.into_dimensionality::<ndarray::Ix2>().map_err(|e| {
SuperPointOnnxError::OutputShapeMismatch {
expected: "(N, 2) keypoints",
actual: format!("{shape:?}: {e}"),
}
})?
} else {
return Err(SuperPointOnnxError::OutputShapeMismatch {
expected: "(N, 2) or (1, N, 2) keypoints",
actual: format!("{shape:?}"),
});
};
Ok(view)
}
#[cfg(feature = "onnx-inference")]
fn normalise_scores(
array: ndarray::ArrayD<f32>,
) -> Result<ndarray::Array1<f32>, SuperPointOnnxError> {
let shape = array.shape().to_vec();
let view = if shape.len() == 2 && shape[0] == 1 {
array.into_shape_with_order((shape[1],)).map_err(|e| {
SuperPointOnnxError::OutputShapeMismatch {
expected: "(N,) or (1, N) scores",
actual: format!("{shape:?}: {e}"),
}
})?
} else if shape.len() == 1 {
array.into_dimensionality::<ndarray::Ix1>().map_err(|e| {
SuperPointOnnxError::OutputShapeMismatch {
expected: "(N,) scores",
actual: format!("{shape:?}: {e}"),
}
})?
} else {
return Err(SuperPointOnnxError::OutputShapeMismatch {
expected: "(N,) or (1, N) scores",
actual: format!("{shape:?}"),
});
};
Ok(view)
}
#[cfg(feature = "onnx-inference")]
fn normalise_descriptors(
array: ndarray::ArrayD<f32>,
) -> Result<ndarray::Array2<f32>, SuperPointOnnxError> {
const DIM: usize = 256;
let shape = array.shape().to_vec();
let two_d = match shape.as_slice() {
[n, d] if *d == DIM => array.into_shape_with_order((*n, DIM)).map_err(|e| {
SuperPointOnnxError::OutputShapeMismatch {
expected: "(N, 256) descriptors",
actual: format!("{shape:?}: {e}"),
}
})?,
[d, n] if *d == DIM => {
let arr = array.into_shape_with_order((DIM, *n)).map_err(|e| {
SuperPointOnnxError::OutputShapeMismatch {
expected: "(256, N) descriptors",
actual: format!("{shape:?}: {e}"),
}
})?;
arr.t().to_owned()
}
[1, n, d] if *d == DIM => array.into_shape_with_order((*n, DIM)).map_err(|e| {
SuperPointOnnxError::OutputShapeMismatch {
expected: "(1, N, 256) descriptors",
actual: format!("{shape:?}: {e}"),
}
})?,
[1, d, n] if *d == DIM => {
let arr = array.into_shape_with_order((DIM, *n)).map_err(|e| {
SuperPointOnnxError::OutputShapeMismatch {
expected: "(1, 256, N) descriptors",
actual: format!("{shape:?}: {e}"),
}
})?;
arr.t().to_owned()
}
_ => {
return Err(SuperPointOnnxError::OutputShapeMismatch {
expected: "(N, 256), (256, N), (1, N, 256), or (1, 256, N) descriptors",
actual: format!("{shape:?}"),
});
}
};
Ok(two_d)
}
#[cfg(feature = "onnx-inference")]
#[cfg(test)]
#[cfg(feature = "onnx-inference")]
fn postprocess(
keypoints: ndarray::ArrayView2<'_, i64>,
scores: ndarray::ArrayView1<'_, f32>,
descriptors: ndarray::ArrayView2<'_, f32>,
config: &SuperPointOnnxConfig,
) -> Result<DecodedKeypoints, SuperPointOnnxError> {
postprocess_with_cap(keypoints, scores, descriptors, config, config.max_keypoints)
}
#[cfg(feature = "onnx-inference")]
fn postprocess_with_cap(
keypoints: ndarray::ArrayView2<'_, i64>,
scores: ndarray::ArrayView1<'_, f32>,
descriptors: ndarray::ArrayView2<'_, f32>,
config: &SuperPointOnnxConfig,
max_keypoints: usize,
) -> Result<DecodedKeypoints, SuperPointOnnxError> {
let n_kp = keypoints.shape()[0];
let n_score = scores.shape()[0];
let n_desc = descriptors.shape()[0];
if n_kp != n_score || n_kp != n_desc {
return Err(SuperPointOnnxError::OutputShapeMismatch {
expected: "keypoints / scores / descriptors agree on N",
actual: format!("N_keypoints={n_kp} N_scores={n_score} N_descriptors={n_desc}"),
});
}
let descriptor_dim = descriptors.shape()[1];
let mut triples: Vec<(Point2<f64>, f32, Vec<f32>)> = Vec::with_capacity(n_kp);
for i in 0..n_kp {
let score = scores[i];
if !score.is_finite() || score < config.min_score {
continue;
}
let x = keypoints[(i, 0)] as f64;
let y = keypoints[(i, 1)] as f64;
let mut descriptor = vec![0.0_f32; descriptor_dim];
for d in 0..descriptor_dim {
descriptor[d] = descriptors[(i, d)];
}
let norm = descriptor.iter().map(|v| v * v).sum::<f32>().sqrt();
if norm > 0.0 {
for v in descriptor.iter_mut() {
*v /= norm;
}
}
triples.push((Point2::new(x, y), score, descriptor));
}
triples.sort_by(|left, right| right.1.total_cmp(&left.1));
if triples.len() > max_keypoints {
triples.truncate(max_keypoints);
}
Ok(triples)
}
#[cfg(feature = "onnx-inference")]
fn unzip_triples(
triples: Vec<(Point2<f64>, f32, Vec<f32>)>,
) -> (Vec<Point2<f64>>, Vec<f32>, Vec<Vec<f32>>) {
let mut keypoints = Vec::with_capacity(triples.len());
let mut scores = Vec::with_capacity(triples.len());
let mut descriptors = Vec::with_capacity(triples.len());
for (kp, score, desc) in triples {
keypoints.push(kp);
scores.push(score);
descriptors.push(desc);
}
(keypoints, scores, descriptors)
}
#[derive(Debug, Clone, PartialEq)]
pub enum SuperPointOnnxError {
FeatureDisabled {
requested: &'static str,
config: SuperPointOnnxConfig,
},
EmptyImage,
PreprocessShape {
width: usize,
height: usize,
message: String,
},
OutputShapeMismatch {
expected: &'static str,
actual: String,
},
OnnxRuntime(String),
DeepFeatureSet(DeepFeatureSetError),
}
impl SuperPointOnnxError {
#[cfg(feature = "onnx-inference")]
fn from_ort<E: std::fmt::Display>(error: E) -> Self {
Self::OnnxRuntime(error.to_string())
}
}
impl fmt::Display for SuperPointOnnxError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::FeatureDisabled { requested, .. } => write!(
formatter,
"SuperPointOnnxExtractor::{requested}: in-Rust ONNX inference is gated behind \
the `onnx-inference` feature; rebuild with `--features onnx-inference` and \
supply a SuperPoint ONNX model path (see docs/superpoint_onnx_runtime_plan.md)"
),
Self::EmptyImage => write!(formatter, "SuperPoint ONNX input image is empty"),
Self::PreprocessShape {
width,
height,
message,
} => write!(
formatter,
"SuperPoint ONNX preprocess failed: image {width}x{height} cannot be reshaped \
into (1, 1, H, W): {message}"
),
Self::OutputShapeMismatch { expected, actual } => write!(
formatter,
"SuperPoint ONNX output shape mismatch: expected {expected}, got {actual}"
),
Self::OnnxRuntime(message) => write!(formatter, "ONNX Runtime error: {message}"),
Self::DeepFeatureSet(error) => write!(formatter, "{error}"),
}
}
}
impl std::error::Error for SuperPointOnnxError {}
impl From<DeepFeatureSetError> for SuperPointOnnxError {
fn from(error: DeepFeatureSetError) -> Self {
Self::DeepFeatureSet(error)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(feature = "onnx-inference"))]
#[test]
fn skeleton_extractor_load_returns_feature_disabled() {
let result = SuperPointOnnxExtractor::load_from_path(
"/nonexistent",
SuperPointOnnxConfig::default(),
);
match result {
Err(SuperPointOnnxError::FeatureDisabled { requested, .. }) => {
assert_eq!(requested, "load_from_path");
}
other => panic!("expected FeatureDisabled, got {other:?}"),
}
}
#[test]
fn default_config_matches_phase26_pre_export_settings() {
let config = SuperPointOnnxConfig::default();
assert_eq!(config.max_keypoints, 1500);
assert_eq!(config.nms_radius_pixels, 4);
assert!((config.min_score - 0.005).abs() < 1.0e-9);
}
#[cfg(feature = "onnx-inference")]
#[test]
fn postprocess_filters_by_min_score_and_truncates_to_max_keypoints() {
let keypoints = ndarray::array![[1_i64, 2], [3, 4], [5, 6], [7, 8]];
let scores = ndarray::array![0.9_f32, 0.7, 0.5, 0.001];
let descriptors = ndarray::array![
[1.0_f32, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
let config = SuperPointOnnxConfig {
min_score: 0.01,
max_keypoints: 2,
nms_radius_pixels: 4,
};
let result =
postprocess(keypoints.view(), scores.view(), descriptors.view(), &config).unwrap();
assert_eq!(result.len(), 2);
assert_eq!(result[0].0, Point2::new(1.0, 2.0));
assert!((result[0].1 - 0.9).abs() < 1.0e-6);
assert_eq!(result[1].0, Point2::new(3.0, 4.0));
assert!((result[1].1 - 0.7).abs() < 1.0e-6);
}
#[cfg(feature = "onnx-inference")]
#[test]
fn runtime_keypoint_cap_overrides_the_configured_default() {
use std::sync::atomic::{AtomicUsize, Ordering};
let config = SuperPointOnnxConfig {
max_keypoints: 1500,
..SuperPointOnnxConfig::default()
};
let shared = AtomicUsize::new(0);
assert_eq!(shared.load(Ordering::Relaxed), 0, "0 means 'use config'");
assert_eq!(config.max_keypoints, 1500);
let effective = |config: &SuperPointOnnxConfig, shared: &AtomicUsize| match shared
.load(Ordering::Relaxed)
{
0 => config.max_keypoints,
override_value => override_value,
};
shared.store(512, Ordering::Relaxed);
assert_eq!(effective(&config, &shared), 512);
shared.store(2048, Ordering::Relaxed);
assert_eq!(effective(&config, &shared), 2048);
shared.store(0, Ordering::Relaxed);
assert_eq!(effective(&config, &shared), 1500);
}
#[cfg(feature = "onnx-inference")]
#[test]
fn postprocess_normalises_descriptors_to_unit_norm() {
let keypoints = ndarray::array![[10_i64, 20]];
let scores = ndarray::array![0.5_f32];
let descriptors = ndarray::array![[3.0_f32, 4.0, 0.0]];
let config = SuperPointOnnxConfig::default();
let result =
postprocess(keypoints.view(), scores.view(), descriptors.view(), &config).unwrap();
assert_eq!(result.len(), 1);
let descriptor = &result[0].2;
let norm = descriptor.iter().map(|v| v * v).sum::<f32>().sqrt();
assert!((norm - 1.0).abs() < 1.0e-6, "got norm {norm}");
assert!((descriptor[0] - 0.6).abs() < 1.0e-6);
assert!((descriptor[1] - 0.8).abs() < 1.0e-6);
assert!(descriptor[2].abs() < 1.0e-6);
}
#[cfg(feature = "onnx-inference")]
#[test]
fn postprocess_rejects_inconsistent_lengths() {
let keypoints = ndarray::array![[0_i64, 0], [1, 1]];
let scores = ndarray::array![0.5_f32]; let descriptors = ndarray::array![[1.0_f32, 0.0]];
let config = SuperPointOnnxConfig::default();
let result = postprocess(keypoints.view(), scores.view(), descriptors.view(), &config);
match result {
Err(SuperPointOnnxError::OutputShapeMismatch { .. }) => {}
other => panic!("expected OutputShapeMismatch, got {other:?}"),
}
}
#[cfg(feature = "onnx-inference")]
#[test]
fn postprocess_skips_nonfinite_and_below_threshold_scores() {
let keypoints = ndarray::array![[0_i64, 0], [1, 0], [2, 0]];
let scores = ndarray::array![f32::NAN, 0.001, 0.5];
let descriptors = ndarray::array![[1.0_f32, 0.0], [0.0, 1.0], [1.0, 1.0],];
let config = SuperPointOnnxConfig {
min_score: 0.01,
max_keypoints: 10,
nms_radius_pixels: 4,
};
let result =
postprocess(keypoints.view(), scores.view(), descriptors.view(), &config).unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].0, Point2::new(2.0, 0.0));
}
#[cfg(feature = "onnx-inference")]
#[test]
fn normalise_descriptors_handles_all_supported_layouts() {
use ndarray::ArrayD;
let nominal: Vec<f32> = (0..(3 * 256)).map(|i| i as f32 / 1000.0).collect();
let a = ArrayD::from_shape_vec(ndarray::IxDyn(&[3, 256]), nominal.clone()).unwrap();
let r = normalise_descriptors(a).unwrap();
assert_eq!(r.shape(), [3, 256]);
let a = ArrayD::from_shape_vec(ndarray::IxDyn(&[1, 3, 256]), nominal.clone()).unwrap();
let r = normalise_descriptors(a).unwrap();
assert_eq!(r.shape(), [3, 256]);
let a = ArrayD::from_shape_vec(ndarray::IxDyn(&[256, 3]), nominal.clone()).unwrap();
let r = normalise_descriptors(a).unwrap();
assert_eq!(r.shape(), [3, 256]);
}
}