Skip to main content

visloc_vision/optical_flow/
feature_bridge.rs

1//! Bridge Basalt-style optical flow into [`crate::features::FeatureSet`].
2//!
3//! Track IDs are encoded as unique descriptors so the existing OnlineSlam
4//! descriptor matcher re-associates the same landmark across frames without
5//! a separate temporal index (faithful enough for the first wiring step).
6
7use std::cell::RefCell;
8
9use nalgebra::Point2;
10
11use crate::features::{FeatureExtractor, FeatureSet, GrayscaleImage};
12
13use super::config::BasaltOpticalFlowConfig;
14use super::pyramid::GrayImage;
15use super::tracker::{track_points_between, OpticalFlowTracker, PATTERN51_SIZE};
16
17/// Descriptor length for track-id encodings (compact + L2-friendly).
18pub const TRACK_ID_DESCRIPTOR_DIM: usize = 16;
19
20/// Encode a stable optical-flow track id as a unique unit-ish descriptor.
21pub fn encode_track_id_descriptor(id: u64) -> Vec<f32> {
22    let mut desc = vec![0.0f32; TRACK_ID_DESCRIPTOR_DIM];
23    for i in 0..8 {
24        let byte = ((id >> (8 * i)) & 0xff) as f32;
25        desc[i] = byte;
26        desc[i + 8] = 255.0 - byte;
27    }
28    let norm = desc.iter().map(|v| v * v).sum::<f32>().sqrt();
29    if norm > 0.0 {
30        for v in &mut desc {
31            *v /= norm;
32        }
33    }
34    desc
35}
36
37/// Convert a normalized [`GrayscaleImage`] (float 0..1) into OF [`GrayImage`].
38pub fn gray_image_from_features_image(image: &GrayscaleImage) -> GrayImage {
39    let data: Vec<u8> = image
40        .pixels()
41        .iter()
42        .map(|p| (p.clamp(0.0, 1.0) * 255.0).round() as u8)
43        .collect();
44    GrayImage {
45        width: image.width(),
46        height: image.height(),
47        data,
48    }
49}
50
51/// Stateful extractor: one [`OpticalFlowTracker`] owned across frames.
52pub struct OpticalFlowFeatureExtractor {
53    tracker: RefCell<OpticalFlowTracker>,
54    config: BasaltOpticalFlowConfig,
55}
56
57impl OpticalFlowFeatureExtractor {
58    pub fn new(config: BasaltOpticalFlowConfig) -> Self {
59        Self {
60            tracker: RefCell::new(OpticalFlowTracker::new(config.clone())),
61            config,
62        }
63    }
64
65    pub fn with_euroc_defaults() -> Self {
66        Self::new(BasaltOpticalFlowConfig::default())
67    }
68
69    pub const fn config(&self) -> &BasaltOpticalFlowConfig {
70        &self.config
71    }
72
73    /// Track `points` from `from` into `to` (e.g. cam0 → cam1 stereo).
74    pub fn track_points_to(
75        &self,
76        from: &GrayscaleImage,
77        to: &GrayscaleImage,
78        points: &[(f32, f32)],
79    ) -> Vec<Option<(f32, f32)>> {
80        let from_g = gray_image_from_features_image(from);
81        let to_g = gray_image_from_features_image(to);
82        track_points_between(&from_g, &to_g, points, &self.config)
83    }
84}
85
86impl FeatureExtractor for OpticalFlowFeatureExtractor {
87    type Image = GrayscaleImage;
88    type Error = String;
89
90    fn extract(&self, image: &Self::Image) -> Result<FeatureSet, Self::Error> {
91        let gray = gray_image_from_features_image(image);
92        let obs = self.tracker.borrow_mut().process(&gray);
93        let mut keypoints = Vec::with_capacity(obs.len());
94        let mut descriptors = Vec::with_capacity(obs.len());
95        for o in obs {
96            keypoints.push(Point2::new(o.x as f64, o.y as f64));
97            descriptors.push(encode_track_id_descriptor(o.id));
98        }
99        FeatureSet::new(keypoints, descriptors).map_err(|e| e.to_string())
100    }
101}
102
103impl std::fmt::Debug for OpticalFlowFeatureExtractor {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        f.debug_struct("OpticalFlowFeatureExtractor")
106            .field("config", &self.config)
107            .field("pattern_size", &PATTERN51_SIZE)
108            .finish()
109    }
110}
111
112// RefCell interior is not Sync for Clone via tracker state — demo holds one
113// extractor. Provide Clone that resets the tracker (fresh stream).
114impl Clone for OpticalFlowFeatureExtractor {
115    fn clone(&self) -> Self {
116        Self::new(self.config.clone())
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    #[test]
125    fn track_id_descriptors_are_unique_and_stable() {
126        let a = encode_track_id_descriptor(42);
127        let b = encode_track_id_descriptor(42);
128        let c = encode_track_id_descriptor(43);
129        assert_eq!(a, b);
130        assert_ne!(a, c);
131        assert_eq!(a.len(), TRACK_ID_DESCRIPTOR_DIM);
132    }
133}