#[cfg(feature = "onnx-inference")]
use super::superpoint_onnx::OnnxBackend;
use nalgebra::Point2;
use std::fmt;
use std::path::Path;
#[cfg(feature = "onnx-inference")]
use std::sync::{Arc, Mutex};
pub const DESCRIPTOR_DIM: usize = 256;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LightGlueMatch {
pub query_index: usize,
pub train_index: usize,
pub score: f32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LightGlueOnnxError {
FeatureDisabled { requested: &'static str },
DimensionMismatch { message: String },
OutputShapeMismatch {
expected: &'static str,
actual: String,
},
OnnxRuntime(String),
}
impl fmt::Display for LightGlueOnnxError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LightGlueOnnxError::FeatureDisabled { requested } => write!(
f,
"LightGlue ONNX `{requested}` requires the `onnx-inference` feature"
),
LightGlueOnnxError::DimensionMismatch { message } => {
write!(f, "LightGlue ONNX input dimension mismatch: {message}")
}
LightGlueOnnxError::OutputShapeMismatch { expected, actual } => {
write!(
f,
"LightGlue ONNX output shape: expected {expected}, got {actual}"
)
}
LightGlueOnnxError::OnnxRuntime(message) => {
write!(f, "LightGlue ONNX Runtime error: {message}")
}
}
}
}
impl std::error::Error for LightGlueOnnxError {}
#[cfg(feature = "onnx-inference")]
impl LightGlueOnnxError {
fn from_ort<E: std::fmt::Display>(error: E) -> Self {
Self::OnnxRuntime(error.to_string())
}
}
#[derive(Clone)]
pub struct LightGlueOnnxMatcher {
#[cfg(feature = "onnx-inference")]
session: Arc<Mutex<ort::session::Session>>,
}
impl fmt::Debug for LightGlueOnnxMatcher {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("LightGlueOnnxMatcher")
.field("onnx_inference_feature", &cfg!(feature = "onnx-inference"))
.finish()
}
}
#[cfg(not(feature = "onnx-inference"))]
impl LightGlueOnnxMatcher {
pub fn load_from_path<P: AsRef<Path>>(_path: P) -> Result<Self, LightGlueOnnxError> {
Err(LightGlueOnnxError::FeatureDisabled {
requested: "load_from_path",
})
}
pub const fn match_features(
&self,
_keypoints0: &[Point2<f64>],
_descriptors0: &[Vec<f32>],
_keypoints1: &[Point2<f64>],
_descriptors1: &[Vec<f32>],
) -> Result<Vec<LightGlueMatch>, LightGlueOnnxError> {
Err(LightGlueOnnxError::FeatureDisabled {
requested: "match_features",
})
}
}
#[cfg(feature = "onnx-inference")]
impl LightGlueOnnxMatcher {
pub fn load_from_path<P: AsRef<Path>>(path: P) -> Result<Self, LightGlueOnnxError> {
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, LightGlueOnnxError> {
let providers = super::superpoint_onnx::execution_providers(backend)
.map_err(LightGlueOnnxError::from_ort)?;
let session = ort::session::Session::builder()
.map_err(LightGlueOnnxError::from_ort)?
.with_optimization_level(ort::session::builder::GraphOptimizationLevel::All)
.map_err(LightGlueOnnxError::from_ort)?
.with_execution_providers(providers)
.map_err(LightGlueOnnxError::from_ort)?
.commit_from_file(path.as_ref())
.map_err(LightGlueOnnxError::from_ort)?;
Ok(Self {
session: Arc::new(Mutex::new(session)),
})
}
pub fn match_features(
&self,
keypoints0: &[Point2<f64>],
descriptors0: &[Vec<f32>],
keypoints1: &[Point2<f64>],
descriptors1: &[Vec<f32>],
) -> Result<Vec<LightGlueMatch>, LightGlueOnnxError> {
if keypoints0.is_empty() || keypoints1.is_empty() {
return Ok(Vec::new());
}
let kpts0 = build_keypoint_tensor(keypoints0)?;
let desc0 = build_descriptor_tensor(descriptors0, keypoints0.len(), "image 0")?;
let kpts1 = build_keypoint_tensor(keypoints1)?;
let desc1 = build_descriptor_tensor(descriptors1, keypoints1.len(), "image 1")?;
let kpts0 = ort::value::Tensor::from_array(kpts0).map_err(LightGlueOnnxError::from_ort)?;
let desc0 = ort::value::Tensor::from_array(desc0).map_err(LightGlueOnnxError::from_ort)?;
let kpts1 = ort::value::Tensor::from_array(kpts1).map_err(LightGlueOnnxError::from_ort)?;
let desc1 = ort::value::Tensor::from_array(desc1).map_err(LightGlueOnnxError::from_ort)?;
let mut session = self
.session
.lock()
.map_err(|error| LightGlueOnnxError::OnnxRuntime(error.to_string()))?;
let mut outputs = session
.run(ort::inputs![kpts0, desc0, kpts1, desc1])
.map_err(LightGlueOnnxError::from_ort)?;
let matches0 =
outputs
.remove("matches0")
.ok_or_else(|| LightGlueOnnxError::OutputShapeMismatch {
expected: "output named `matches0`",
actual: "missing".to_string(),
})?;
let mscores0 =
outputs
.remove("mscores0")
.ok_or_else(|| LightGlueOnnxError::OutputShapeMismatch {
expected: "output named `mscores0`",
actual: "missing".to_string(),
})?;
let matches0 = matches0
.try_extract_array::<i64>()
.map_err(LightGlueOnnxError::from_ort)?;
let mscores0 = mscores0
.try_extract_array::<f32>()
.map_err(LightGlueOnnxError::from_ort)?;
let matches0 = squeeze_to_1d_i64(matches0.view())?;
let mscores0 = squeeze_to_1d_f32(mscores0.view())?;
let mut matches = Vec::new();
for (query_index, (&target, &score)) in matches0.iter().zip(mscores0.iter()).enumerate() {
if target >= 0 {
matches.push(LightGlueMatch {
query_index,
train_index: target as usize,
score,
});
}
}
Ok(matches)
}
}
#[cfg(feature = "onnx-inference")]
fn build_keypoint_tensor(
keypoints: &[Point2<f64>],
) -> Result<ndarray::Array3<f32>, LightGlueOnnxError> {
let m = keypoints.len();
let mut array = ndarray::Array3::<f32>::zeros((1, m, 2));
for (i, p) in keypoints.iter().enumerate() {
array[(0, i, 0)] = p.x as f32;
array[(0, i, 1)] = p.y as f32;
}
Ok(array)
}
#[cfg(feature = "onnx-inference")]
fn build_descriptor_tensor(
descriptors: &[Vec<f32>],
expected_count: usize,
which: &str,
) -> Result<ndarray::Array3<f32>, LightGlueOnnxError> {
if descriptors.len() != expected_count {
return Err(LightGlueOnnxError::DimensionMismatch {
message: format!(
"{which}: {} descriptors for {expected_count} keypoints",
descriptors.len()
),
});
}
let mut array = ndarray::Array3::<f32>::zeros((1, expected_count, DESCRIPTOR_DIM));
for (i, desc) in descriptors.iter().enumerate() {
if desc.len() != DESCRIPTOR_DIM {
return Err(LightGlueOnnxError::DimensionMismatch {
message: format!(
"{which}: descriptor {i} has length {} (expected {DESCRIPTOR_DIM})",
desc.len()
),
});
}
for (j, &value) in desc.iter().enumerate() {
array[(0, i, j)] = value;
}
}
Ok(array)
}
#[cfg(feature = "onnx-inference")]
fn squeeze_to_1d_i64(
array: ndarray::ArrayView<i64, ndarray::IxDyn>,
) -> Result<Vec<i64>, LightGlueOnnxError> {
let shape = array.shape().to_vec();
match shape.as_slice() {
[_m] => Ok(array.iter().copied().collect()),
[1, _m] => Ok(array.iter().copied().collect()),
_ => Err(LightGlueOnnxError::OutputShapeMismatch {
expected: "(M,) or (1, M) matches0",
actual: format!("{shape:?}"),
}),
}
}
#[cfg(feature = "onnx-inference")]
fn squeeze_to_1d_f32(
array: ndarray::ArrayView<f32, ndarray::IxDyn>,
) -> Result<Vec<f32>, LightGlueOnnxError> {
let shape = array.shape().to_vec();
match shape.as_slice() {
[_m] => Ok(array.iter().copied().collect()),
[1, _m] => Ok(array.iter().copied().collect()),
_ => Err(LightGlueOnnxError::OutputShapeMismatch {
expected: "(M,) or (1, M) mscores0",
actual: format!("{shape:?}"),
}),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn match_struct_is_copy_and_comparable() {
let a = LightGlueMatch {
query_index: 1,
train_index: 2,
score: 0.9,
};
let b = a;
assert_eq!(a, b);
}
#[cfg(not(feature = "onnx-inference"))]
#[test]
fn stub_reports_feature_disabled() {
let err = LightGlueOnnxMatcher::load_from_path("nope.onnx").unwrap_err();
assert_eq!(
err,
LightGlueOnnxError::FeatureDisabled {
requested: "load_from_path"
}
);
}
#[cfg(feature = "onnx-inference")]
mod tensor_marshalling {
use super::*;
#[test]
fn build_keypoint_tensor_places_pixel_xy_at_batch_zero() {
let kpts = vec![Point2::new(1.5, 2.5), Point2::new(100.0, 200.0)];
let array = build_keypoint_tensor(&kpts).expect("build_keypoint_tensor");
assert_eq!(array.shape(), &[1, 2, 2]);
assert_eq!(array[(0, 0, 0)], 1.5);
assert_eq!(array[(0, 0, 1)], 2.5);
assert_eq!(array[(0, 1, 0)], 100.0);
assert_eq!(array[(0, 1, 1)], 200.0);
}
#[test]
fn build_keypoint_tensor_handles_empty_input() {
let array = build_keypoint_tensor(&[]).expect("build_keypoint_tensor");
assert_eq!(array.shape(), &[1, 0, 2]);
}
#[test]
fn build_descriptor_tensor_round_trips_values() {
let mut d0 = vec![0.0f32; DESCRIPTOR_DIM];
d0[0] = 0.25;
d0[DESCRIPTOR_DIM - 1] = -0.75;
let descriptors = vec![d0.clone()];
let array = build_descriptor_tensor(&descriptors, 1, "image 0")
.expect("build_descriptor_tensor");
assert_eq!(array.shape(), &[1, 1, DESCRIPTOR_DIM]);
assert_eq!(array[(0, 0, 0)], 0.25);
assert_eq!(array[(0, 0, DESCRIPTOR_DIM - 1)], -0.75);
}
#[test]
fn build_descriptor_tensor_rejects_keypoint_count_mismatch() {
let descriptors = vec![vec![0.0f32; DESCRIPTOR_DIM]];
let err = build_descriptor_tensor(&descriptors, 2, "image 0").unwrap_err();
match err {
LightGlueOnnxError::DimensionMismatch { message } => {
assert!(message.contains("image 0"), "message: {message}");
assert!(message.contains('1'), "message: {message}");
assert!(message.contains('2'), "message: {message}");
}
other => panic!("expected DimensionMismatch, got {other:?}"),
}
}
#[test]
fn build_descriptor_tensor_rejects_wrong_descriptor_length() {
let descriptors = vec![vec![0.0f32; DESCRIPTOR_DIM - 1]];
let err = build_descriptor_tensor(&descriptors, 1, "image 1").unwrap_err();
match err {
LightGlueOnnxError::DimensionMismatch { message } => {
assert!(message.contains("image 1"), "message: {message}");
assert!(message.contains("descriptor 0"), "message: {message}");
}
other => panic!("expected DimensionMismatch, got {other:?}"),
}
}
#[test]
fn squeeze_to_1d_i64_accepts_bare_and_batched_shapes() {
let bare = ndarray::array![1i64, -1, 2].into_dyn();
assert_eq!(squeeze_to_1d_i64(bare.view()).unwrap(), vec![1, -1, 2]);
let batched = ndarray::array![[1i64, -1, 2]].into_dyn();
assert_eq!(squeeze_to_1d_i64(batched.view()).unwrap(), vec![1, -1, 2]);
}
#[test]
fn squeeze_to_1d_i64_rejects_unexpected_rank() {
let bad = ndarray::Array::<i64, _>::zeros((2, 3)).into_dyn();
let err = squeeze_to_1d_i64(bad.view()).unwrap_err();
assert!(matches!(
err,
LightGlueOnnxError::OutputShapeMismatch { expected: _, .. }
));
}
#[test]
fn squeeze_to_1d_f32_accepts_bare_and_batched_shapes() {
let bare = ndarray::array![0.9f32, 0.5].into_dyn();
assert_eq!(squeeze_to_1d_f32(bare.view()).unwrap(), vec![0.9, 0.5]);
let batched = ndarray::array![[0.9f32, 0.5]].into_dyn();
assert_eq!(squeeze_to_1d_f32(batched.view()).unwrap(), vec![0.9, 0.5]);
}
#[test]
fn squeeze_to_1d_f32_rejects_unexpected_rank() {
let bad = ndarray::Array::<f32, _>::zeros((2, 3)).into_dyn();
let err = squeeze_to_1d_f32(bad.view()).unwrap_err();
assert!(matches!(
err,
LightGlueOnnxError::OutputShapeMismatch { expected: _, .. }
));
}
}
}