Skip to main content

visloc_localization/
keyframe_retrieval.rs

1//! Keyframe retrieval for the map-wide search.
2//!
3//! [`BinaryLandmarkIndex::match_all`] compares each query keypoint with
4//! every landmark of the map, and its ratio test weighs the best landmark
5//! against the second best anywhere in the map. The larger the map (a
6//! merged one above all), the more often an unrelated landmark comes close
7//! enough to reject a correct match. [`KeyframeRetrieval`] first picks the
8//! map keyframes that look most like the query and hands only the
9//! landmarks they observe to [`BinaryLandmarkIndex::match_among`].
10//!
11//! Each keyframe is described by the binary descriptors of the landmarks
12//! it observes, hashed to visual words: the descriptor bits at fixed
13//! positions (Basalt's `HashBow` permutation), as the SLAM mapper's own loop
14//! detection does. A keyframe's bag of words is the L1-normalized histogram
15//! of its words. A query scores each keyframe by histogram intersection
16//! (`sum min(q_w, k_w)` over shared words, Basalt's `HashBow` score), through
17//! an inverted index of the keyframes' words.
18
19use std::collections::{BTreeSet, HashMap};
20
21use visloc_core::types::VisualMap;
22
23use crate::binary_index::{BinaryLandmarkIndex, PackedDescriptors};
24
25/// Bits of a 256-bit descriptor taken, in order, for its visual word: the
26/// permutation of Basalt's `HashBow` (and of the mapper's
27/// `hash_descriptor`).
28const WORD_BITS: [usize; 32] = [
29    170, 215, 41, 38, 96, 172, 52, 1, 182, 89, 234, 98, 217, 73, 195, 113, 161, 247, 24, 75, 7,
30    232, 49, 196, 144, 69, 3, 86, 94, 201, 107, 251,
31];
32
33/// The visual word of a packed 256-bit descriptor, from its first `bits`
34/// permuted bits.
35fn word(descriptor: &[u64], bits: u8) -> u32 {
36    let mut word = 0_u32;
37    for (index, &bit) in WORD_BITS.iter().take(usize::from(bits.min(32))).enumerate() {
38        if descriptor
39            .get(bit / 64)
40            .is_some_and(|w| w & (1_u64 << (bit % 64)) != 0)
41        {
42            word |= 1 << index;
43        }
44    }
45    word
46}
47
48/// L1-normalized histogram of the words of `descriptors`.
49fn bag_of_words<'a>(descriptors: impl Iterator<Item = &'a [u64]>, bits: u8) -> HashMap<u32, f32> {
50    let mut counts = HashMap::<u32, f32>::new();
51    let mut total = 0.0_f32;
52    for descriptor in descriptors {
53        *counts.entry(word(descriptor, bits)).or_default() += 1.0;
54        total += 1.0;
55    }
56    for weight in counts.values_mut() {
57        *weight /= total;
58    }
59    counts
60}
61
62/// A map's keyframes, described by the words of the landmarks they observe.
63#[derive(Debug, Clone)]
64pub struct KeyframeRetrieval {
65    bits: u8,
66    keyframe_ids: Vec<u64>,
67    /// Per keyframe, the indices (into the [`BinaryLandmarkIndex`]) of the
68    /// landmarks it observes, ascending.
69    landmarks: Vec<Vec<usize>>,
70    /// Word -> `(keyframe, weight)` of every keyframe that has it.
71    inverted: HashMap<u32, Vec<(u32, f32)>>,
72}
73
74impl KeyframeRetrieval {
75    /// Describes every keyframe of `map` that observes landmarks of `index`,
76    /// with `bits`-bit words (Basalt's mapper uses 16; fewer bits make
77    /// coarser words that survive more descriptor noise).
78    pub fn new(map: &VisualMap, index: &BinaryLandmarkIndex, bits: u8) -> Self {
79        let mut keyframes = map.keyframes.iter().collect::<Vec<_>>();
80        keyframes.sort_by_key(|(id, _)| **id);
81        let mut retrieval = Self {
82            bits,
83            keyframe_ids: Vec::new(),
84            landmarks: Vec::new(),
85            inverted: HashMap::new(),
86        };
87        for (&id, keyframe) in keyframes {
88            let landmarks = keyframe
89                .observations
90                .iter()
91                .filter_map(|observation| index.landmark_index(observation.landmark_id))
92                .collect::<BTreeSet<_>>()
93                .into_iter()
94                .collect::<Vec<_>>();
95            if landmarks.is_empty() {
96                continue;
97            }
98            let words = bag_of_words(
99                landmarks
100                    .iter()
101                    .filter_map(|&landmark| index.landmark_descriptor(landmark)),
102                bits,
103            );
104            let keyframe_index = retrieval.keyframe_ids.len() as u32;
105            for (word, weight) in words {
106                retrieval
107                    .inverted
108                    .entry(word)
109                    .or_default()
110                    .push((keyframe_index, weight));
111            }
112            retrieval.keyframe_ids.push(id);
113            retrieval.landmarks.push(landmarks);
114        }
115        retrieval
116    }
117
118    /// Number of described keyframes.
119    pub fn len(&self) -> usize {
120        self.keyframe_ids.len()
121    }
122
123    pub fn is_empty(&self) -> bool {
124        self.keyframe_ids.is_empty()
125    }
126
127    /// The `top_k` keyframes most like `query`, best first, as
128    /// `(position, score)`; ties go to the lower keyframe id.
129    fn ranked(&self, query: &PackedDescriptors, top_k: usize) -> Vec<(usize, f32)> {
130        let words = bag_of_words(
131            (0..query.len()).filter_map(|index| query.get(index)),
132            self.bits,
133        );
134        let mut scores = vec![0.0_f32; self.keyframe_ids.len()];
135        for (word, query_weight) in words {
136            for &(keyframe, weight) in self.inverted.get(&word).into_iter().flatten() {
137                scores[keyframe as usize] += query_weight.min(weight);
138            }
139        }
140        let mut ranked = scores
141            .into_iter()
142            .enumerate()
143            .filter(|(_, score)| *score > 0.0)
144            .collect::<Vec<_>>();
145        ranked.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
146        ranked.truncate(top_k);
147        ranked
148    }
149
150    /// The ids and scores of the `top_k` keyframes most like `query`, best
151    /// first.
152    pub fn query(&self, query: &PackedDescriptors, top_k: usize) -> Vec<(u64, f32)> {
153        self.ranked(query, top_k)
154            .into_iter()
155            .map(|(keyframe, score)| (self.keyframe_ids[keyframe], score))
156            .collect()
157    }
158
159    /// The landmarks (indices into the [`BinaryLandmarkIndex`]) observed by
160    /// the `top_k` keyframes most like `query`, ascending, for
161    /// [`BinaryLandmarkIndex::match_among`].
162    pub fn candidate_landmarks(&self, query: &PackedDescriptors, top_k: usize) -> Vec<usize> {
163        self.ranked(query, top_k)
164            .into_iter()
165            .flat_map(|(keyframe, _)| self.landmarks[keyframe].iter().copied())
166            .collect::<BTreeSet<_>>()
167            .into_iter()
168            .collect()
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175    use crate::binary_index::BinaryMatchGates;
176    use nalgebra::{Point2, Point3};
177    use visloc_core::geometry::Pose;
178    use visloc_core::types::{Frame, Keyframe, Landmark, LandmarkDescriptorStore, Observation};
179
180    /// Deterministic, well-separated pseudo-random bits per seed.
181    fn descriptor(seed: u64) -> Vec<f32> {
182        let mut state = (seed + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15);
183        (0..256)
184            .map(|_| {
185                state ^= state << 13;
186                state ^= state >> 7;
187                state ^= state << 17;
188                f32::from(u8::from(state & 1 == 1))
189            })
190            .collect()
191    }
192
193    /// Three keyframes, each observing its own 40 landmarks.
194    fn map() -> (VisualMap, LandmarkDescriptorStore) {
195        let mut map = VisualMap::new();
196        let mut store = LandmarkDescriptorStore::new();
197        for keyframe in 0..3_u64 {
198            let mut observations = Vec::new();
199            for point in 0..40_u64 {
200                let id = keyframe * 100 + point;
201                map.landmarks.insert(
202                    id,
203                    Landmark {
204                        id,
205                        position: Point3::new(keyframe as f64, point as f64, 5.0),
206                        descriptor: None,
207                        observations: Vec::new(),
208                    },
209                );
210                store.insert(id, descriptor(id));
211                observations.push(Observation {
212                    frame_id: keyframe,
213                    landmark_id: id,
214                    keypoint_index: point as usize,
215                    xy: Point2::new(point as f64, 0.0),
216                });
217            }
218            map.keyframes.insert(
219                keyframe,
220                Keyframe {
221                    frame: Frame {
222                        id: keyframe,
223                        camera_id: 1,
224                        keypoints: Vec::new(),
225                        descriptors: Vec::new(),
226                        pose: Some(Pose::identity()),
227                    },
228                    observations,
229                },
230            );
231        }
232        (map, store)
233    }
234
235    #[test]
236    fn a_query_retrieves_the_keyframe_it_shares_landmarks_with() {
237        let (map, store) = map();
238        let index = BinaryLandmarkIndex::new(&map, &store);
239        let retrieval = KeyframeRetrieval::new(&map, &index, 8);
240        assert_eq!(retrieval.len(), 3);
241        // The query sees 30 of keyframe 1's landmarks.
242        let query = (0..30)
243            .map(|point| descriptor(100 + point))
244            .collect::<Vec<_>>();
245        let packed = index.pack_query(&query);
246        let ranked = retrieval.query(&packed, 3);
247        assert_eq!(ranked[0].0, 1, "{ranked:?}");
248        assert!(ranked.get(1).is_none_or(|second| second.1 < ranked[0].1));
249
250        let landmarks = retrieval.candidate_landmarks(&packed, 1);
251        assert_eq!(landmarks.len(), 40);
252        let keypoints = (0..30)
253            .map(|i| Point2::new(i as f64, 0.0))
254            .collect::<Vec<_>>();
255        let gates = BinaryMatchGates {
256            max_distance: 10,
257            ratio: Some(0.8),
258        };
259        let set = index.match_among(&keypoints, &packed, gates, &landmarks);
260        assert_eq!(set.match_count, 30);
261        assert_eq!(set.candidate_landmark_count, 40);
262        assert!(set.landmark_ids.iter().all(|id| (100..140).contains(id)));
263        // The same as the map-wide search, which finds the same landmarks.
264        let all = index.match_all(&keypoints, &packed, gates, 1);
265        assert_eq!(all.landmark_ids, set.landmark_ids);
266    }
267
268    #[test]
269    fn landmarks_outside_the_index_and_empty_keyframes_are_skipped() {
270        let (mut map, store) = map();
271        map.keyframes.insert(
272            9,
273            Keyframe {
274                frame: Frame {
275                    id: 9,
276                    camera_id: 1,
277                    keypoints: Vec::new(),
278                    descriptors: Vec::new(),
279                    pose: Some(Pose::identity()),
280                },
281                observations: vec![Observation {
282                    frame_id: 9,
283                    landmark_id: 12_345,
284                    keypoint_index: 0,
285                    xy: Point2::new(0.0, 0.0),
286                }],
287            },
288        );
289        let index = BinaryLandmarkIndex::new(&map, &store);
290        assert_eq!(index.landmark_index(12_345), None);
291        assert_eq!(index.landmark_index(100), Some(40));
292        let retrieval = KeyframeRetrieval::new(&map, &index, 16);
293        assert_eq!(retrieval.len(), 3);
294        let empty = index.pack_query::<Vec<f32>>(&[]);
295        assert!(retrieval.query(&empty, 5).is_empty());
296        assert!(retrieval.candidate_landmarks(&empty, 5).is_empty());
297    }
298
299    #[test]
300    fn words_take_the_permuted_bits() {
301        let mut descriptor = [0_u64; 4];
302        descriptor[170 / 64] |= 1 << (170 % 64); // first permuted bit
303        descriptor[0] |= 1 << 38; // fourth
304        assert_eq!(word(&descriptor, 16), 0b1001);
305        assert_eq!(word(&descriptor, 1), 0b1);
306        assert_eq!(word(&descriptor, 0), 0);
307    }
308}