visloc-vision 0.4.0

Feature, matching, PnP, RANSAC, and pose-refinement building blocks for visloc-rs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! In-Rust LightGlue matcher via ONNX Runtime.
//!
//! The sibling of [`super::superpoint_onnx`]: where that module runs the
//! SuperPoint feature *extractor* in-process, this runs the learned
//! **LightGlue matcher** in-process, so a full deep front-end (extract +
//! match) needs no Python feature-export pass.
//!
//! Two build profiles share this module, exactly like `superpoint_onnx`:
//!
//! * **Default (`onnx-inference` off)** — a skeleton whose every method
//!   returns [`LightGlueOnnxError::FeatureDisabled`].
//! * **`onnx-inference` enabled** — wraps an `ort::session::Session`.
//!
//! Expected ONNX I/O contract (batch size 1), produced by
//! `scripts/export_lightglue_onnx.py`:
//!
//! * inputs  `kpts0 (1, M, 2) f32`, `desc0 (1, M, 256) f32`,
//!   `kpts1 (1, N, 2) f32`, `desc1 (1, N, 256) f32`
//! * outputs `matches0 (M,) i64` (matched index in image 1, or `-1`),
//!   `mscores0 (M,) f32` (confidence in `(0, 1]`)
//!
//! Keypoints are pixel coordinates; the exported graph normalises them by the
//! baked-in image size. The export disables LightGlue's adaptive
//! depth/width pruning and FlashAttention (a speed knob, not a quality one);
//! the ONNX matches are bit-identical to the Python reference on real EuRoC
//! pairs.

#[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};

/// Expected descriptor dimensionality (SuperPoint / LightGlue).
pub const DESCRIPTOR_DIM: usize = 256;

/// A single LightGlue match: keypoint `query_index` in image 0 matched to
/// keypoint `train_index` in image 1 with confidence `score` in `(0, 1]`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LightGlueMatch {
    pub query_index: usize,
    pub train_index: usize,
    pub score: f32,
}

/// Errors from the in-Rust LightGlue ONNX matcher.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LightGlueOnnxError {
    /// The `onnx-inference` feature is not enabled.
    FeatureDisabled { requested: &'static str },
    /// A descriptor did not have the expected [`DESCRIPTOR_DIM`] length, or
    /// the keypoint / descriptor counts disagreed for one image.
    DimensionMismatch { message: String },
    /// A model output had an unexpected shape.
    OutputShapeMismatch {
        expected: &'static str,
        actual: String,
    },
    /// Underlying ONNX Runtime error (stored as `String` to stay cheaply
    /// comparable).
    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())
    }
}

/// In-Rust LightGlue matcher. Wraps a shared `ort` session so `Clone` is cheap
/// (mirrors [`super::superpoint_onnx::SuperPointOnnxExtractor`]).
#[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()
    }
}

// ---------------------------------------------------------------
// Feature-disabled stub
// ---------------------------------------------------------------

#[cfg(not(feature = "onnx-inference"))]
impl LightGlueOnnxMatcher {
    /// **Stub** — without `onnx-inference` this returns
    /// [`LightGlueOnnxError::FeatureDisabled`].
    pub fn load_from_path<P: AsRef<Path>>(_path: P) -> Result<Self, LightGlueOnnxError> {
        Err(LightGlueOnnxError::FeatureDisabled {
            requested: "load_from_path",
        })
    }

    /// **Stub** — see [`load_from_path`](Self::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",
        })
    }
}

// ---------------------------------------------------------------
// Active implementation (`onnx-inference`)
// ---------------------------------------------------------------

#[cfg(feature = "onnx-inference")]
impl LightGlueOnnxMatcher {
    /// Load a LightGlue ONNX model, preferring CUDA with a CPU fallback.
    pub fn load_from_path<P: AsRef<Path>>(path: P) -> Result<Self, LightGlueOnnxError> {
        Self::load_from_path_with_backend(path, OnnxBackend::default())
    }

    /// Like [`load_from_path`](Self::load_from_path) with an explicit
    /// execution-provider choice (shares [`OnnxBackend`] with SuperPoint).
    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)),
        })
    }

    /// Match keypoints/descriptors between two images. Returns one
    /// [`LightGlueMatch`] per matched keypoint in image 0 (unmatched
    /// keypoints are omitted).
    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()))?;
        // Positional binding follows the export's input order:
        // kpts0, desc0, kpts1, desc1.
        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"
            }
        );
    }

    // -----------------------------------------------------------------
    // M6 (`docs/colmap_port_plan.md`): always-on unit tests for the
    // Rust-side pre/post-processing math around the ONNX graph itself.
    //
    // Keypoint *normalisation* (dividing by the baked-in image size) and
    // match *extraction* from the assignment matrix (the score-threshold
    // cut implementing `filter_matches`) both live **inside the exported
    // ONNX graph** (`scripts/export_lightglue_onnx.py`'s `normalize_keypoints`
    // call and `filter_matches` call respectively) — not in this file — by
    // deliberate design, the same "push it into the graph, keep the Rust
    // wrapper thin" choice `superpoint_onnx.rs` already made, and reused
    // rather than re-litigated here (see this file's module doc: the ONNX
    // output is bit-identical to the Python reference on real pairs, which
    // already exercises that logic end-to-end via the ignore-gated fixture
    // tests in `crates/vision/tests/lightglue_onnx_parity.rs`).
    //
    // What genuinely *is* Rust-side pre/post-processing math, and therefore
    // belongs here as an always-on (non-`#[ignore]`) unit test independent
    // of any ONNX Runtime session or model file: the tensor-shape
    // marshalling functions below (`build_keypoint_tensor`,
    // `build_descriptor_tensor`, `squeeze_to_1d_i64`, `squeeze_to_1d_f32`)
    // and their `DimensionMismatch`/`OutputShapeMismatch` error paths.
    // -----------------------------------------------------------------
    #[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: _, .. }
            ));
        }
    }
}