use std::collections::{HashMap, HashSet};
use std::hash::{BuildHasherDefault, Hasher};
use super::colmap_verification::ConfigurationType;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Correspondence {
pub image_id: u32,
pub point2d_idx: u32,
}
impl Correspondence {
pub const fn new(image_id: u32, point2d_idx: u32) -> Self {
Self {
image_id,
point2d_idx,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EdgeMetadata {
pub num_matches: usize,
pub config: ConfigurationType,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct IngestStats {
pub added: usize,
pub out_of_bounds: usize,
pub duplicate: usize,
}
impl IngestStats {
pub const fn total(&self) -> usize {
self.added + self.out_of_bounds + self.duplicate
}
}
#[derive(Debug, Clone, Copy)]
pub struct PairMatches<'a> {
pub image_id1: usize,
pub image_id2: usize,
pub matches: &'a [(u32, u32)],
pub config: ConfigurationType,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CorrespondenceGraphError {
SelfMatch(usize),
UnknownImage(usize),
DuplicatePair(usize, usize),
AlreadyFinalized,
}
impl std::fmt::Display for CorrespondenceGraphError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SelfMatch(id) => write!(f, "cannot add a self-match for image {id}"),
Self::UnknownImage(id) => write!(f, "image {id} was never added to the graph"),
Self::DuplicatePair(a, b) => {
write!(f, "two-view geometry for pair ({a}, {b}) was already added")
}
Self::AlreadyFinalized => write!(f, "graph is already finalized"),
}
}
}
impl std::error::Error for CorrespondenceGraphError {}
fn pair_key(a: usize, b: usize) -> (usize, usize) {
(a.min(b), a.max(b))
}
#[derive(Debug, Clone, PartialEq)]
struct ImageEntry {
num_observations: usize,
num_correspondences: usize,
corrs: Vec<Vec<Correspondence>>,
flat_corrs: Vec<Correspondence>,
flat_corr_begs: Vec<u32>,
}
impl ImageEntry {
fn new(num_points2d: usize) -> Self {
Self {
num_observations: 0,
num_correspondences: 0,
corrs: vec![Vec::new(); num_points2d],
flat_corrs: Vec::new(),
flat_corr_begs: Vec::new(),
}
}
fn num_points2d(&self) -> usize {
if self.flat_corr_begs.is_empty() {
self.corrs.len()
} else {
self.flat_corr_begs.len() - 1
}
}
}
#[derive(Debug, Default, Clone, Copy)]
struct IdHasher(u64);
impl Hasher for IdHasher {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
for &b in bytes {
self.write_u64(u64::from(b));
}
}
fn write_u64(&mut self, x: u64) {
self.0 = (self.0.rotate_left(5) ^ x).wrapping_mul(0x517c_c1b7_2722_0a95);
}
fn write_usize(&mut self, x: usize) {
self.write_u64(x as u64);
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct CorrespondenceGraph {
finalized: bool,
images: HashMap<usize, ImageEntry, BuildHasherDefault<IdHasher>>,
image_pairs: HashMap<(usize, usize), EdgeMetadata>,
}
impl CorrespondenceGraph {
pub fn new() -> Self {
Self::default()
}
pub fn add_image(&mut self, image_id: usize, num_points2d: usize) {
assert_fits_u32(image_id, num_points2d);
assert!(
!self.images.contains_key(&image_id),
"image {image_id} already added to the correspondence graph"
);
self.images.insert(image_id, ImageEntry::new(num_points2d));
}
pub fn num_images(&self) -> usize {
self.images.len()
}
pub fn num_image_pairs(&self) -> usize {
self.image_pairs.len()
}
pub fn exists_image(&self, image_id: usize) -> bool {
self.images.contains_key(&image_id)
}
fn image(&self, image_id: usize) -> &ImageEntry {
self.images
.get(&image_id)
.unwrap_or_else(|| panic!("image {image_id} does not exist"))
}
pub fn num_observations_for_image(&self, image_id: usize) -> usize {
self.image(image_id).num_observations
}
pub fn num_correspondences_for_image(&self, image_id: usize) -> usize {
self.image(image_id).num_correspondences
}
pub fn num_matches_between_images(&self, image_id1: usize, image_id2: usize) -> usize {
self.image_pairs
.get(&pair_key(image_id1, image_id2))
.map_or(0, |e| e.num_matches)
}
pub fn num_matches_between_all_images(&self) -> HashMap<(usize, usize), usize> {
self.image_pairs
.iter()
.map(|(&pair, edge)| (pair, edge.num_matches))
.collect()
}
pub fn image_pairs(&self) -> Vec<(usize, usize)> {
self.image_pairs.keys().copied().collect()
}
pub fn edge(&self, image_id1: usize, image_id2: usize) -> Option<EdgeMetadata> {
self.image_pairs
.get(&pair_key(image_id1, image_id2))
.copied()
}
pub fn update_edge_config(
&mut self,
image_id1: usize,
image_id2: usize,
config: ConfigurationType,
) -> bool {
match self.image_pairs.get_mut(&pair_key(image_id1, image_id2)) {
Some(edge) => {
edge.config = config;
true
}
None => false,
}
}
pub fn add_two_view_geometry(
&mut self,
image_id1: usize,
image_id2: usize,
matches: &[(usize, usize)],
config: ConfigurationType,
) -> Result<IngestStats, CorrespondenceGraphError> {
if self.finalized {
return Err(CorrespondenceGraphError::AlreadyFinalized);
}
if image_id1 == image_id2 {
return Err(CorrespondenceGraphError::SelfMatch(image_id1));
}
if !self.images.contains_key(&image_id1) {
return Err(CorrespondenceGraphError::UnknownImage(image_id1));
}
if !self.images.contains_key(&image_id2) {
return Err(CorrespondenceGraphError::UnknownImage(image_id2));
}
let key = pair_key(image_id1, image_id2);
if self.image_pairs.contains_key(&key) {
return Err(CorrespondenceGraphError::DuplicatePair(
image_id1, image_id2,
));
}
let mut stats = IngestStats::default();
let [Some(img1), Some(img2)] = self.images.get_disjoint_mut([&image_id1, &image_id2])
else {
unreachable!("both images exist (checked above)");
};
for &(k1, k2) in matches {
let valid1 = k1 < img1.num_points2d();
let valid2 = k2 < img2.num_points2d();
if !valid1 || !valid2 {
stats.out_of_bounds += 1;
continue;
}
let forward = Correspondence::new(image_id2 as u32, k2 as u32);
if img1.corrs[k1].contains(&forward) {
stats.duplicate += 1;
continue;
}
img1.corrs[k1].push(forward);
if img1.corrs[k1].len() == 1 {
img1.num_observations += 1;
}
img2.corrs[k2].push(Correspondence::new(image_id1 as u32, k1 as u32));
if img2.corrs[k2].len() == 1 {
img2.num_observations += 1;
}
stats.added += 1;
}
img1.num_correspondences += stats.added;
img2.num_correspondences += stats.added;
self.image_pairs.insert(
key,
EdgeMetadata {
num_matches: stats.added,
config,
},
);
Ok(stats)
}
pub fn has_correspondences(&self, image_id: usize, point2d_idx: usize) -> bool {
!self.find_correspondences(image_id, point2d_idx).is_empty()
}
pub fn find_correspondences(&self, image_id: usize, point2d_idx: usize) -> &[Correspondence] {
let image = self.image(image_id);
if self.finalized {
let beg = image.flat_corr_begs[point2d_idx] as usize;
let end = image.flat_corr_begs[point2d_idx + 1] as usize;
&image.flat_corrs[beg..end]
} else {
&image.corrs[point2d_idx]
}
}
pub fn extract_correspondences(
&self,
image_id: usize,
point2d_idx: usize,
) -> Vec<Correspondence> {
self.find_correspondences(image_id, point2d_idx).to_vec()
}
pub fn is_two_view_observation(&self, image_id: usize, point2d_idx: usize) -> bool {
let corrs = self.find_correspondences(image_id, point2d_idx);
if corrs.len() != 1 {
return false;
}
let other = corrs[0];
self.find_correspondences(other.image_id as usize, other.point2d_idx as usize)
.len()
== 1
}
pub fn extract_transitive_correspondences(
&self,
image_id: usize,
point2d_idx: usize,
transitivity: usize,
) -> Vec<Correspondence> {
if transitivity == 1 {
return self.extract_correspondences(image_id, point2d_idx);
}
if !self.exists_image(image_id) || !self.has_correspondences(image_id, point2d_idx) {
return Vec::new();
}
let seed = Correspondence::new(image_id as u32, point2d_idx as u32);
let mut corrs = vec![seed];
let mut visited: HashSet<Correspondence> = HashSet::new();
visited.insert(seed);
let mut queue_beg = 0usize;
let mut queue_end = 1usize;
for _level in 0..transitivity {
for i in queue_beg..queue_end {
let reference = corrs[i];
for &next in self.find_correspondences(
reference.image_id as usize,
reference.point2d_idx as usize,
) {
if visited.insert(next) {
corrs.push(next);
}
}
}
queue_beg = queue_end;
queue_end = corrs.len();
if queue_beg == queue_end {
break;
}
}
if corrs.len() > 1 {
let last = corrs.len() - 1;
corrs.swap(0, last);
}
corrs.pop();
corrs
}
pub fn finalize(&mut self) {
assert!(!self.finalized, "correspondence graph is already finalized");
self.finalized = true;
self.images.retain(|_, image| image.num_observations > 0);
let flatten = |image: &mut ImageEntry| {
let num_points2d = image.corrs.len();
assert_offsets_fit_u32(image.num_correspondences);
let mut flat_corrs = Vec::with_capacity(image.num_correspondences);
let mut flat_corr_begs = Vec::with_capacity(num_points2d + 1);
for point2d_idx in 0..num_points2d {
flat_corr_begs.push(flat_corrs.len() as u32);
flat_corrs.extend(image.corrs[point2d_idx].iter().copied());
}
flat_corr_begs.push(flat_corrs.len() as u32);
image.flat_corrs = flat_corrs;
image.flat_corr_begs = flat_corr_begs;
image.corrs = Vec::new();
};
#[cfg(feature = "parallel")]
{
use rayon::prelude::*;
self.images
.par_iter_mut()
.for_each(|(_, image)| flatten(image));
}
#[cfg(not(feature = "parallel"))]
self.images.values_mut().for_each(flatten);
}
pub fn finalized_from_pairs(
images: &[(usize, usize)],
pairs: &[PairMatches<'_>],
) -> Result<(Self, Vec<IngestStats>), (usize, CorrespondenceGraphError)> {
assert!(pairs.len() < u32::MAX as usize, "too many image pairs");
let mut index_of: HashMap<usize, u32, BuildHasherDefault<IdHasher>> =
HashMap::with_capacity_and_hasher(images.len(), Default::default());
for (index, &(image_id, num_points2d)) in images.iter().enumerate() {
assert_fits_u32(image_id, num_points2d);
assert!(
index_of.insert(image_id, index as u32).is_none(),
"image {image_id} already added to the correspondence graph"
);
}
let mut pair_images = Vec::with_capacity(pairs.len());
let mut keys = HashSet::with_capacity(pairs.len());
for (index, pair) in pairs.iter().enumerate() {
let (id1, id2) = (pair.image_id1, pair.image_id2);
if id1 == id2 {
return Err((index, CorrespondenceGraphError::SelfMatch(id1)));
}
let Some(&index1) = index_of.get(&id1) else {
return Err((index, CorrespondenceGraphError::UnknownImage(id1)));
};
let Some(&index2) = index_of.get(&id2) else {
return Err((index, CorrespondenceGraphError::UnknownImage(id2)));
};
if !keys.insert(pair_key(id1, id2)) {
return Err((index, CorrespondenceGraphError::DuplicatePair(id1, id2)));
}
pair_images.push([index1, index2]);
}
drop(keys);
let num_points2d = |index: u32| images[index as usize].1;
let drop_list = |seen: &mut Vec<u32>, p: usize| {
let [index1, index2] = pair_images[p];
dropped_matches(
pairs[p].matches,
num_points2d(index1),
num_points2d(index2),
seen,
p as u32 + 1,
)
};
#[cfg(feature = "parallel")]
let dropped: Vec<(IngestStats, Vec<u32>)> = {
use rayon::prelude::*;
(0..pairs.len())
.into_par_iter()
.map_init(Vec::new, drop_list)
.collect()
};
#[cfg(not(feature = "parallel"))]
let dropped: Vec<(IngestStats, Vec<u32>)> = {
let mut seen = Vec::new();
(0..pairs.len()).map(|p| drop_list(&mut seen, p)).collect()
};
let mut incident_off = vec![0usize; images.len() + 1];
for &[index1, index2] in &pair_images {
incident_off[index1 as usize + 1] += 1;
incident_off[index2 as usize + 1] += 1;
}
for i in 0..images.len() {
incident_off[i + 1] += incident_off[i];
}
let mut incident = vec![0u32; incident_off[images.len()]];
let mut next = incident_off.clone();
for (p, &[index1, index2]) in pair_images.iter().enumerate() {
for index in [index1, index2] {
incident[next[index as usize]] = p as u32;
next[index as usize] += 1;
}
}
drop(next);
let build = |i: usize| -> Option<ImageEntry> {
let (_, n) = images[i];
let incident = &incident[incident_off[i]..incident_off[i + 1]];
let for_each_kept = |p: usize, f: &mut dyn FnMut(usize, usize, usize)| {
let pair = &pairs[p];
let first = pair_images[p][0] as usize == i;
let mut dropped = dropped[p].1.iter().copied().peekable();
for (m, &(k1, k2)) in pair.matches.iter().enumerate() {
if dropped.next_if_eq(&(m as u32)).is_some() {
continue;
}
if first {
f(k1 as usize, pair.image_id2, k2 as usize);
} else {
f(k2 as usize, pair.image_id1, k1 as usize);
}
}
};
let num_correspondences: usize =
incident.iter().map(|&p| dropped[p as usize].0.added).sum();
assert_offsets_fit_u32(num_correspondences);
let mut begs = vec![0u32; n + 1];
for &p in incident {
for_each_kept(p as usize, &mut |k, _, _| begs[k + 1] += 1);
}
let num_observations = begs[1..].iter().filter(|&&count| count > 0).count();
if num_observations == 0 {
return None;
}
for k in 0..n {
begs[k + 1] += begs[k];
}
let mut flat = vec![Correspondence::new(0, 0); num_correspondences];
let mut next = begs[..n].to_vec();
for &p in incident {
for_each_kept(p as usize, &mut |k, other_id, other_k| {
flat[next[k] as usize] = Correspondence::new(other_id as u32, other_k as u32);
next[k] += 1;
});
}
Some(ImageEntry {
num_observations,
num_correspondences,
corrs: Vec::new(),
flat_corrs: flat,
flat_corr_begs: begs,
})
};
#[cfg(feature = "parallel")]
let entries: Vec<Option<ImageEntry>> = {
use rayon::prelude::*;
(0..images.len()).into_par_iter().map(build).collect()
};
#[cfg(not(feature = "parallel"))]
let entries: Vec<Option<ImageEntry>> = (0..images.len()).map(build).collect();
let mut graph = Self {
finalized: true,
..Self::default()
};
graph
.images
.reserve(entries.iter().filter(|entry| entry.is_some()).count());
for (&(image_id, _), entry) in images.iter().zip(entries) {
if let Some(entry) = entry {
graph.images.insert(image_id, entry);
}
}
graph.image_pairs.reserve(pairs.len());
let mut stats = Vec::with_capacity(pairs.len());
for (pair, (pair_stats, _)) in pairs.iter().zip(dropped) {
graph.image_pairs.insert(
pair_key(pair.image_id1, pair.image_id2),
EdgeMetadata {
num_matches: pair_stats.added,
config: pair.config,
},
);
stats.push(pair_stats);
}
Ok((graph, stats))
}
}
fn assert_fits_u32(image_id: usize, num_points2d: usize) {
assert!(
u32::try_from(image_id).is_ok() && u32::try_from(num_points2d).is_ok(),
"image {image_id} with {num_points2d} points2D exceeds the graph's 32-bit ids"
);
}
fn assert_offsets_fit_u32(num_correspondences: usize) {
assert!(
u32::try_from(num_correspondences).is_ok(),
"{num_correspondences} correspondences of one image exceed the graph's 32-bit offsets"
);
}
fn dropped_matches(
matches: &[(u32, u32)],
num_points2d1: usize,
num_points2d2: usize,
seen: &mut Vec<u32>,
stamp: u32,
) -> (IngestStats, Vec<u32>) {
let in_bounds =
|k1: u32, k2: u32| (k1 as usize) < num_points2d1 && (k2 as usize) < num_points2d2;
if seen.len() < num_points2d1 {
seen.resize(num_points2d1, 0);
}
let mut stats = IngestStats::default();
let mut dropped = Vec::new();
let mut repeated = false;
for (m, &(k1, k2)) in matches.iter().enumerate() {
if !in_bounds(k1, k2) {
stats.out_of_bounds += 1;
dropped.push(m as u32);
continue;
}
let mark = &mut seen[k1 as usize];
repeated |= *mark == stamp;
*mark = stamp;
}
if repeated {
let mut kept = HashSet::with_capacity(matches.len());
dropped.clear();
stats.out_of_bounds = 0;
for (m, &(k1, k2)) in matches.iter().enumerate() {
if !in_bounds(k1, k2) {
stats.out_of_bounds += 1;
dropped.push(m as u32);
} else if !kept.insert((k1, k2)) {
stats.duplicate += 1;
dropped.push(m as u32);
}
}
}
stats.added = matches.len() - stats.out_of_bounds - stats.duplicate;
(stats, dropped)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_graph_reports_zero_everything() {
let graph = CorrespondenceGraph::new();
assert_eq!(graph.num_images(), 0);
assert_eq!(graph.num_image_pairs(), 0);
assert_eq!(graph.num_matches_between_all_images().len(), 0);
assert_eq!(graph.image_pairs().len(), 0);
}
fn two_view_case(finalize: bool) {
let mut graph = CorrespondenceGraph::new();
graph.add_image(0, 10);
graph.add_image(1, 10);
assert!(graph.exists_image(0));
assert!(graph.exists_image(1));
assert!(!graph.exists_image(2));
assert_eq!(graph.num_images(), 2);
let matches = vec![(0, 0), (1, 2), (3, 7), (4, 8)];
let stats = graph
.add_two_view_geometry(0, 1, &matches, ConfigurationType::Calibrated)
.expect("valid pair must be added");
assert_eq!(stats.added, 4);
assert_eq!(stats.out_of_bounds, 0);
assert_eq!(stats.duplicate, 0);
if finalize {
graph.finalize();
}
assert_eq!(graph.num_correspondences_for_image(0), 4);
assert_eq!(graph.num_correspondences_for_image(1), 4);
assert_eq!(graph.num_matches_between_all_images().len(), 1);
assert_eq!(graph.num_matches_between_images(0, 1), 4);
assert_eq!(graph.image_pairs(), vec![(0, 1)]);
assert_eq!(
graph.edge(0, 1).unwrap().config,
ConfigurationType::Calibrated
);
assert_eq!(
graph.extract_correspondences(0, 0),
vec![Correspondence::new(1, 0)]
);
assert!(graph.has_correspondences(0, 0));
assert!(graph.is_two_view_observation(0, 0));
assert_eq!(
graph.extract_correspondences(1, 0),
vec![Correspondence::new(0, 0)]
);
assert!(graph.is_two_view_observation(1, 0));
assert_eq!(
graph.extract_correspondences(0, 1),
vec![Correspondence::new(1, 2)]
);
assert_eq!(
graph.extract_correspondences(1, 2),
vec![Correspondence::new(0, 1)]
);
assert_eq!(
graph.extract_correspondences(0, 4),
vec![Correspondence::new(1, 8)]
);
assert_eq!(
graph.extract_correspondences(0, 3),
vec![Correspondence::new(1, 7)]
);
assert_eq!(
graph.extract_correspondences(1, 7),
vec![Correspondence::new(0, 3)]
);
assert_eq!(
graph.extract_correspondences(1, 8),
vec![Correspondence::new(0, 4)]
);
for point2d_idx in 0..10 {
assert_eq!(
graph
.extract_transitive_correspondences(0, point2d_idx, 0)
.len(),
0
);
assert_eq!(
graph.extract_correspondences(0, point2d_idx).len(),
graph
.extract_transitive_correspondences(0, point2d_idx, 2)
.len()
);
assert_eq!(
graph
.extract_transitive_correspondences(1, point2d_idx, 0)
.len(),
0
);
assert_eq!(
graph.extract_correspondences(1, point2d_idx).len(),
graph
.extract_transitive_correspondences(1, point2d_idx, 2)
.len()
);
}
assert_eq!(graph.num_observations_for_image(0), 4);
assert_eq!(graph.num_observations_for_image(1), 4);
}
#[test]
fn two_view_not_finalized() {
two_view_case(false);
}
#[test]
fn two_view_finalized() {
two_view_case(true);
}
fn three_view_case(finalize: bool) {
let mut graph = CorrespondenceGraph::new();
graph.add_image(0, 10);
graph.add_image(1, 10);
graph.add_image(2, 10);
graph
.add_two_view_geometry(0, 1, &[(0, 0)], ConfigurationType::Calibrated)
.unwrap();
graph
.add_two_view_geometry(0, 2, &[(0, 0)], ConfigurationType::Calibrated)
.unwrap();
graph
.add_two_view_geometry(1, 2, &[(0, 0), (5, 5)], ConfigurationType::Calibrated)
.unwrap();
if finalize {
graph.finalize();
}
assert_eq!(graph.num_observations_for_image(0), 1);
assert_eq!(graph.num_observations_for_image(1), 2);
assert_eq!(graph.num_observations_for_image(2), 2);
assert_eq!(graph.num_correspondences_for_image(0), 2);
assert_eq!(graph.num_correspondences_for_image(1), 3);
assert_eq!(graph.num_correspondences_for_image(2), 3);
assert_eq!(graph.num_matches_between_all_images().len(), 3);
assert_eq!(graph.num_matches_between_images(0, 1), 1);
assert_eq!(graph.num_matches_between_images(0, 2), 1);
assert_eq!(graph.num_matches_between_images(1, 2), 2);
let corrs0 = graph.extract_correspondences(0, 0);
assert_eq!(
corrs0,
vec![Correspondence::new(1, 0), Correspondence::new(2, 0)]
);
let corrs1 = graph.extract_correspondences(1, 0);
assert_eq!(
corrs1,
vec![Correspondence::new(0, 0), Correspondence::new(2, 0)]
);
let corrs2 = graph.extract_correspondences(2, 0);
assert_eq!(
corrs2,
vec![Correspondence::new(0, 0), Correspondence::new(1, 0)]
);
assert_eq!(
graph.extract_correspondences(1, 5),
vec![Correspondence::new(2, 5)]
);
assert_eq!(
graph.extract_correspondences(2, 5),
vec![Correspondence::new(1, 5)]
);
for image_id in [0usize, 1, 2] {
assert_eq!(
graph
.extract_transitive_correspondences(image_id, 0, 2)
.len(),
2
);
assert_eq!(
graph
.extract_transitive_correspondences(image_id, 0, 3)
.len(),
2
);
}
}
#[test]
fn three_view_not_finalized() {
three_view_case(false);
}
#[test]
fn three_view_finalized() {
three_view_case(true);
}
#[test]
fn out_of_bounds_matches_are_dropped() {
let mut graph = CorrespondenceGraph::new();
graph.add_image(0, 10);
graph.add_image(1, 4);
let matches = vec![(9, 3), (10, 3), (9, 4)];
let stats = graph
.add_two_view_geometry(0, 1, &matches, ConfigurationType::Calibrated)
.unwrap();
assert_eq!(stats.added, 1);
assert_eq!(stats.out_of_bounds, 2);
assert_eq!(graph.num_correspondences_for_image(0), 1);
assert_eq!(graph.num_correspondences_for_image(1), 1);
assert_eq!(graph.num_matches_between_images(0, 1), 1);
}
#[test]
fn duplicate_matches_are_dropped() {
let mut graph = CorrespondenceGraph::new();
graph.add_image(0, 10);
graph.add_image(1, 10);
let matches = vec![(0, 0), (1, 1), (1, 1), (3, 3), (3, 4)];
let stats = graph
.add_two_view_geometry(0, 1, &matches, ConfigurationType::Calibrated)
.unwrap();
assert_eq!(stats.added, 4);
assert_eq!(stats.duplicate, 1);
assert_eq!(graph.num_correspondences_for_image(0), 4);
assert_eq!(graph.num_correspondences_for_image(1), 4);
assert_eq!(graph.num_matches_between_images(0, 1), 4);
}
#[test]
fn update_edge_config_replaces_stored_configuration() {
let mut graph = CorrespondenceGraph::new();
graph.add_image(0, 10);
graph.add_image(1, 10);
graph
.add_two_view_geometry(
0,
1,
&[(0, 0), (1, 2), (3, 7)],
ConfigurationType::Calibrated,
)
.unwrap();
graph.finalize();
assert_eq!(
graph.edge(0, 1).unwrap().config,
ConfigurationType::Calibrated
);
assert!(graph.update_edge_config(0, 1, ConfigurationType::Planar));
assert_eq!(graph.edge(0, 1).unwrap().config, ConfigurationType::Planar);
assert_eq!(graph.edge(1, 0).unwrap().config, ConfigurationType::Planar);
assert_eq!(
graph.extract_correspondences(0, 0),
vec![Correspondence::new(1, 0)]
);
}
#[test]
fn self_match_is_rejected() {
let mut graph = CorrespondenceGraph::new();
graph.add_image(0, 10);
let err = graph
.add_two_view_geometry(0, 0, &[(0, 0)], ConfigurationType::Calibrated)
.unwrap_err();
assert_eq!(err, CorrespondenceGraphError::SelfMatch(0));
}
#[test]
fn duplicate_pair_add_is_rejected() {
let mut graph = CorrespondenceGraph::new();
graph.add_image(0, 10);
graph.add_image(1, 10);
graph
.add_two_view_geometry(0, 1, &[(0, 0)], ConfigurationType::Calibrated)
.unwrap();
let err = graph
.add_two_view_geometry(0, 1, &[(1, 1)], ConfigurationType::Calibrated)
.unwrap_err();
assert_eq!(err, CorrespondenceGraphError::DuplicatePair(0, 1));
let err_swapped = graph
.add_two_view_geometry(1, 0, &[(1, 1)], ConfigurationType::Calibrated)
.unwrap_err();
assert_eq!(err_swapped, CorrespondenceGraphError::DuplicatePair(1, 0));
}
#[test]
fn finalize_drops_images_without_observations() {
let mut graph = CorrespondenceGraph::new();
graph.add_image(0, 10);
graph.add_image(1, 10);
graph.add_image(2, 10); graph
.add_two_view_geometry(0, 1, &[(0, 0)], ConfigurationType::Calibrated)
.unwrap();
assert!(graph.exists_image(2));
graph.finalize();
assert!(graph.exists_image(0));
assert!(graph.exists_image(1));
assert!(!graph.exists_image(2));
assert_eq!(graph.num_images(), 2);
}
#[test]
fn transitivity_parameter_bounds_the_closure_depth() {
let mut graph = CorrespondenceGraph::new();
for id in 0..4 {
graph.add_image(id, 5);
}
graph
.add_two_view_geometry(0, 1, &[(0, 0)], ConfigurationType::Calibrated)
.unwrap();
graph
.add_two_view_geometry(1, 2, &[(0, 0)], ConfigurationType::Calibrated)
.unwrap();
graph
.add_two_view_geometry(2, 3, &[(0, 0)], ConfigurationType::Calibrated)
.unwrap();
assert_eq!(graph.extract_transitive_correspondences(0, 0, 1).len(), 1); assert_eq!(graph.extract_transitive_correspondences(0, 0, 2).len(), 2); assert_eq!(graph.extract_transitive_correspondences(0, 0, 3).len(), 3); assert_eq!(
graph
.extract_transitive_correspondences(0, 0, usize::MAX)
.len(),
3
);
assert_eq!(
graph
.extract_transitive_correspondences(3, 0, usize::MAX)
.len(),
3
);
}
#[test]
fn panoramic_classified_pair_contributes_correspondences_to_graph() {
use super::super::colmap_verification::{TwoViewGeometryOptions, TwoViewGeometryVerifier};
use super::super::TwoViewCorrespondence;
use nalgebra::{Point3, UnitQuaternion, Vector3};
use visloc_core::geometry::Pose;
use visloc_core::types::Camera;
let camera = Camera::pinhole(0, 640, 480, 500.0, 500.0, 320.0, 240.0);
let mut points = Vec::new();
for i in 0..6 {
for j in 0..4 {
points.push(Point3::new(
-1.5 + 0.6 * i as f64,
-1.0 + 0.7 * j as f64,
3.0 + 0.8 * ((i + j) % 5) as f64,
));
}
}
let previous =
Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
let yaw = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.12);
let current = Pose::from_world_to_camera(yaw, Vector3::new(0.0, 0.0, 0.0));
let correspondences: Vec<TwoViewCorrespondence> = points
.iter()
.filter_map(|p| {
let p1 = camera.project(&previous.transform_world_point(p))?;
let p2 = camera.project(¤t.transform_world_point(p))?;
Some(TwoViewCorrespondence::new(p1, p2))
})
.collect();
assert!(correspondences.len() >= 20, "fixture sanity");
let verifier =
TwoViewGeometryVerifier::new(TwoViewGeometryOptions::for_camera(&camera, 4.0));
let report = verifier.classify(&correspondences, &camera);
assert_eq!(
report.config,
ConfigurationType::Panoramic,
"fixture sanity: pure rotation must classify PANORAMIC"
);
assert!(
!report.inliers.is_empty(),
"a PANORAMIC report must carry the winning homography's inliers, \
not an empty list like DEGENERATE"
);
let keep = matches!(
report.config,
ConfigurationType::Calibrated
| ConfigurationType::Uncalibrated
| ConfigurationType::Planar
| ConfigurationType::Panoramic
| ConfigurationType::PlanarOrPanoramic
| ConfigurationType::Multiple
);
assert!(keep, "M2.1: PANORAMIC must be kept by the demo's keep-list");
let matches: Vec<(usize, usize)> = report.inliers.iter().map(|&i| (i, i)).collect();
let mut graph = CorrespondenceGraph::new();
graph.add_image(0, correspondences.len());
graph.add_image(1, correspondences.len());
let stats = graph
.add_two_view_geometry(0, 1, &matches, report.config)
.expect("PANORAMIC pair must be a valid graph edge, same as any other configuration");
assert_eq!(stats.added, matches.len());
assert!(
graph.num_correspondences_for_image(0) > 0,
"PANORAMIC pair's correspondences must reach the graph/track-building layer"
);
assert_eq!(
graph.edge(0, 1).unwrap().config,
ConfigurationType::Panoramic
);
}
#[test]
fn degenerate_classified_pair_contributes_no_correspondences() {
use super::super::colmap_verification::TwoViewGeometryVerifier;
use super::super::TwoViewCorrespondence;
use nalgebra::{Point3, UnitQuaternion, Vector3};
use visloc_core::geometry::Pose;
use visloc_core::types::Camera;
let camera = Camera::pinhole(0, 640, 480, 500.0, 500.0, 320.0, 240.0);
let previous =
Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
let current =
Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-0.3, 0.0, 0.0));
let points: Vec<Point3<f64>> = (0..10)
.map(|i| Point3::new(-1.0 + 0.2 * i as f64, 0.0, 3.0))
.collect();
let correspondences: Vec<TwoViewCorrespondence> = points
.iter()
.filter_map(|p| {
let p1 = camera.project(&previous.transform_world_point(p))?;
let p2 = camera.project(¤t.transform_world_point(p))?;
Some(TwoViewCorrespondence::new(p1, p2))
})
.collect();
let verifier = TwoViewGeometryVerifier::default();
let report = verifier.classify(&correspondences, &camera);
assert_eq!(
report.config,
ConfigurationType::Degenerate,
"fixture sanity"
);
assert!(report.inliers.is_empty());
let keep = matches!(
report.config,
ConfigurationType::Calibrated
| ConfigurationType::Uncalibrated
| ConfigurationType::Planar
| ConfigurationType::Panoramic
| ConfigurationType::PlanarOrPanoramic
| ConfigurationType::Multiple
);
assert!(
!keep,
"DEGENERATE must never be kept by the demo's keep-list"
);
let mut graph = CorrespondenceGraph::new();
graph.add_image(0, correspondences.len());
graph.add_image(1, correspondences.len());
let matches: Vec<(usize, usize)> = report.inliers.iter().map(|&i| (i, i)).collect();
assert!(matches.is_empty());
let stats = graph
.add_two_view_geometry(0, 1, &matches, report.config)
.expect("adding an empty match list is still a valid (if useless) edge");
assert_eq!(stats.added, 0);
assert_eq!(graph.num_correspondences_for_image(0), 0);
assert_eq!(graph.num_correspondences_for_image(1), 0);
}
fn incremental(
images: &[(usize, usize)],
pairs: &[PairMatches<'_>],
) -> Result<(CorrespondenceGraph, Vec<IngestStats>), (usize, CorrespondenceGraphError)> {
let mut graph = CorrespondenceGraph::new();
for &(image_id, num_points2d) in images {
graph.add_image(image_id, num_points2d);
}
let mut stats = Vec::new();
for (index, pair) in pairs.iter().enumerate() {
let matches: Vec<(usize, usize)> = pair
.matches
.iter()
.map(|&(k1, k2)| (k1 as usize, k2 as usize))
.collect();
stats.push(
graph
.add_two_view_geometry(pair.image_id1, pair.image_id2, &matches, pair.config)
.map_err(|error| (index, error))?,
);
}
graph.finalize();
Ok((graph, stats))
}
type RawPair = (usize, usize, Vec<(u32, u32)>);
fn random_scene(seed: u64) -> (Vec<(usize, usize)>, Vec<RawPair>) {
use rand::{rngs::StdRng, Rng, SeedableRng};
let mut rng = StdRng::seed_from_u64(seed);
let n_images = rng.gen_range(2..12);
let images: Vec<(usize, usize)> = (0..n_images)
.map(|i| {
let num_points2d = if rng.gen_bool(0.1) {
0
} else {
rng.gen_range(1..40)
};
(3 * i + 7, num_points2d)
})
.collect();
let mut pairs = Vec::new();
for a in 0..n_images {
for b in a + 1..n_images {
if rng.gen_bool(0.5) {
continue;
}
let (id_a, n_a) = images[a];
let (id_b, n_b) = images[b];
let mut matches: Vec<(u32, u32)> = Vec::new();
for _ in 0..rng.gen_range(0..60) {
let pick = rng.gen_range(0..10);
if pick == 0 && !matches.is_empty() {
matches.push(matches[rng.gen_range(0..matches.len())]);
} else if pick == 1 && !matches.is_empty() {
let k1 = matches[rng.gen_range(0..matches.len())].0;
matches.push((k1, rng.gen_range(0..n_b as u32 + 2)));
} else {
matches.push((
rng.gen_range(0..n_a as u32 + 2),
rng.gen_range(0..n_b as u32 + 2),
));
}
}
if rng.gen_bool(0.5) {
pairs.push((id_a, id_b, matches));
} else {
let swapped = matches.iter().map(|&(k1, k2)| (k2, k1)).collect();
pairs.push((id_b, id_a, swapped));
}
}
}
for i in (1..pairs.len()).rev() {
pairs.swap(i, rng.gen_range(0..=i));
}
(images, pairs)
}
fn pair_matches(pairs: &[RawPair]) -> Vec<PairMatches<'_>> {
const CONFIGS: [ConfigurationType; 3] = [
ConfigurationType::Calibrated,
ConfigurationType::Planar,
ConfigurationType::Panoramic,
];
pairs
.iter()
.enumerate()
.map(|(index, (image_id1, image_id2, matches))| PairMatches {
image_id1: *image_id1,
image_id2: *image_id2,
matches,
config: CONFIGS[index % CONFIGS.len()],
})
.collect()
}
#[test]
fn finalized_from_pairs_equals_the_incremental_build() {
let mut dropped = IngestStats::default();
for seed in 0..300 {
let (images, pairs) = random_scene(seed);
let pairs = pair_matches(&pairs);
let expected = incremental(&images, &pairs).expect("valid scene");
let built =
CorrespondenceGraph::finalized_from_pairs(&images, &pairs).expect("valid scene");
assert_eq!(built, expected, "seed {seed}");
for stats in &built.1 {
dropped.out_of_bounds += stats.out_of_bounds;
dropped.duplicate += stats.duplicate;
}
}
assert!(
dropped.out_of_bounds > 100 && dropped.duplicate > 100,
"{dropped:?}"
);
}
#[test]
fn finalized_from_pairs_rejects_the_first_pair_the_incremental_build_rejects() {
let (images, pairs) = random_scene(11);
assert!(pairs.len() > 3);
let (first_id, second_id) = (pairs[1].0, pairs[1].1);
let unknown = images.iter().map(|&(image_id, _)| image_id).max().unwrap() + 1;
let cases: [(usize, usize, usize); 4] = [
(2, first_id, first_id), (1, unknown, second_id), (3, first_id, unknown), (3, second_id, first_id), ];
for (at, image_id1, image_id2) in cases {
let mut bad = pairs.clone();
bad.insert(at, (image_id1, image_id2, vec![(0, 0)]));
let bad = pair_matches(&bad);
let expected = incremental(&images, &bad).expect_err("invalid pair");
assert_eq!(
CorrespondenceGraph::finalized_from_pairs(&images, &bad).expect_err("invalid pair"),
expected
);
assert_eq!(expected.0, at);
}
}
}