diff --git a/docs/benchmarks/chen2020_graph_sfm.md b/docs/benchmarks/chen2020_graph_sfm.md new file mode 100644 index 000000000..107233559 --- /dev/null +++ b/docs/benchmarks/chen2020_graph_sfm.md @@ -0,0 +1,134 @@ +# Chen et al. GraphSfM baseline + +This baseline reimplements the image clustering, maximum-spanning-tree (MaxST) +subgraph expansion, and minimum-spanning-tree (MinST) + minimum-height-tree +(MHT) sub-model merging steps from +[Chen et al., arXiv:1912.10659, Sections 3.1–3.2](https://arxiv.org/pdf/1912.10659) +(Algorithms 1 and 2). It accepts a verified COLMAP database, matching the input +contract of the Zhu 2018 baseline so experiments can share image pairs, +keypoints, matches, and camera metadata. Pair filtering applies to a frozen +snapshot. + +1. Recursively partition the inlier-weighted view graph with normalized cuts + under the base size bound `S_max` (`--max-cameras`). Build the cluster graph + weighted by lost image edges, compute its MaxST via Kruskal's algorithm, and + expand clusters along MaxST edges (then remaining lost edges) until the + completeness ratio `eta(i) >= C` (`--completeness-ratio`) or `--max-overlap` + is reached. +2. Reconstruct each expanded cluster independently with PyCOLMAP incremental + SfM. +3. Estimate pairwise `Sim(3)` transforms between overlapping clusters using + median pairwise baseline scale and RANSAC over camera-pose hypotheses + refitted with chordal SO(3) orientation averaging and optimal scale/translation. + Weight each cluster-graph edge by symmetric Mean Square Distance (`msd`, + Eqs. 10–11) over shared 3D track points (falling back to camera centers). +4. Compute the Kruskal MinST of the largest cluster-graph component, peel leaf + nodes layer-by-layer to select the MHT anchor cluster, and compose `Sim(3)` + transforms along tree paths into the anchor frame. +5. Carry local camera intrinsics into PyCOLMAP triangulation and final sparse + BA, and score poses with GTSfM's evaluator (`sim3_from_Pose3_maps` and + `compute_ba_pose_metrics`). Reference poses enter only the evaluator. + +The implementation runs on a single host using PyCOLMAP for local incremental +mapping, global triangulation, and final sparse BA, whereas the paper distributes +local COLMAP jobs across multiple servers. Pairwise `Sim(3)` refitting uses both +camera orientations and centers (avoiding roll ambiguity when overlapping camera +centers are nearly collinear) rather than point-only Euclidean alignment. + +## Reproduce + +Run from the repository root in the pinned GTSfM environment (`uv run`). Each +run writes a verified database snapshot (`frontend.db`), local reconstructions, +final COLMAP geometry, and `metrics.json` to a new output directory. The +reported `frontend_sha256` identifies the filtered `frontend.db` snapshot. + +```sh +uv run python -m scripts.run_graph_sfm \ + --database tests/data/set1_lund_door/colmap.db \ + --images tests/data/set1_lund_door/images \ + --olsson-reference tests/data/set1_lund_door \ + --max-cameras 6 --min-pair-inliers 3800 --output .context/door-graphsfm +``` + +On Lund Door, `--min-pair-inliers 3800` produces 25 verified pairs, three base +clusters (`5, 3, 4` cameras), a 2-edge MaxST (`0–1–2`), and expanded clusters of +`7, 6, 5` cameras with 3 common cameras on each edge. The MHT selects cluster 1 +as the anchor. + +The Reichstag fixture uses a fresh CPU SIFT database with exhaustive matching, +matching the Zhu 2018 setup: + +```sh +mkdir -p .context +uv run python - <<'PY' +import pycolmap + +database = ".context/reichstag-sift.db" +images = "tests/data/imb_reichstag/images" +pycolmap.set_random_seed(0) +pycolmap.extract_features( + database, + images, + sift_options=pycolmap.SiftExtractionOptions(num_threads=2, max_num_features=4096), + device=pycolmap.Device.cpu, +) +pycolmap.match_exhaustive( + database, + sift_options=pycolmap.SiftMatchingOptions(num_threads=2), + device=pycolmap.Device.cpu, +) +PY +uv run python -m scripts.run_graph_sfm \ + --database .context/reichstag-sift.db \ + --images tests/data/imb_reichstag/images \ + --yfcc-imb-reference tests/data/imb_reichstag \ + --max-cameras 6 --completeness-ratio 0.4 --max-overlap 4 \ + --output .context/reichstag-graphsfm-ov4 +``` + +## Observed results + +All runs below were executed on the same frozen `frontend.db` per scene (single +Mac, CPU, `num_threads=2`). Single-model PyCOLMAP incremental SfM on the same +frozen databases is included for reference. + +| Fixture / Method | Final registered / input | Final points | Mean reproj. (px) | Pose AUC at 5° after merging | Pose AUC at 5° after final BA | +| --- | ---: | ---: | ---: | ---: | ---: | +| Lund Door — GraphSfM (free intrinsics) | 12 / 12 | 11,125 | 0.395 | 0.9100 | 0.9070 | +| Lund Door — GraphSfM (`--fix-final-intrinsics`) | 12 / 12 | 11,125 | 0.395 | 0.9100 | 0.9131 | +| Lund Door — Single-model PyCOLMAP (same DB) | 12 / 12 | 11,028 | 0.341 | — | 0.9064 | +| Reichstag — GraphSfM (`C=0.4`, `O_max=4`, free) | 10 / 10 | 1,887 | 0.510 | 0.2932 | 0.1985 | +| Reichstag — GraphSfM (`C=0.4`, `O_max=4`, fixed) | 10 / 10 | 1,887 | 0.510 | 0.2932 | 0.1856 | +| Reichstag — GraphSfM (`C=0.5`, unbounded overlap) | 10 / 10 | 2,144 | 0.407 | 0.5254 | 0.5245 | +| Reichstag — Single-model PyCOLMAP (same DB) | 10 / 10 | 2,199 | 0.400 | — | 0.5254 | +| Dubrovnik6K (120-img Old Town) — GraphSfM (`S_max=50`, `O_max=20`) | 114 / 120 | 21,656 | 1.085 | 0.4489 | 0.5216 | +| Dubrovnik6K (120-img Old Town) — Single-model PyCOLMAP (`multiple_models=True`) | 115 / 120 | 21,577 | 0.773 | — | 0.5550 | +| Dubrovnik6K (120-img Old Town) — Single-model PyCOLMAP (`multiple_models=False`) | 5 / 120 | 0 | 0.000 | — | 0.0000 | + +Notes: + +- On Lund Door, GraphSfM exercises a 3-cluster chain (`0–1–2`, `msd = 0.0452` and + `0.0763`), selects the central cluster `1` via MHT, and matches or slightly + exceeds both single-model PyCOLMAP (`0.9064`) and the Zhu 2018 baseline + (`0.9068`) on the same 25-pair graph. +- On Reichstag (10 uncalibrated internet photos), unbounded expansion at + `C=0.5` expands cluster 0 to all 10 cameras (making it equivalent to + single-model PyCOLMAP). Bounding overlap (`--max-overlap 4`) forces a genuine + 2-cluster merge (`9` and `5` cameras, `4` common cameras, `msd = 1.5437`), + where local self-calibration without the 10th camera lowers individual local + cluster quality (`local-0` alone achieves `AUC@5° = 0.2689`, `local-1` + `0.2378`). Re-running on the same frozen `frontend.db` reproduced cluster + membership, `msd`, point count, and pose AUC bit-for-bit. +- On Dubrovnik6K (120 spatially contiguous Old Town images within 6.6 m of + `[32.9, -7.6, 209.3]` from `Dubrovnik6K_images.tar`, 3,835 verified SIFT + pairs, evaluated against `bundle.orig.out` + `list.orig.txt` via + `--bundler-reference` / `--bundler-list`), GraphSfM (`--max-cameras 50 + --completeness-ratio 0.5 --max-overlap 20`) forms a 4-cluster graph with a + cycle (`0–2–3–0` + `1–3`). Kruskal MinST drops the higher-MSD cycle edge + `(0, 3)` (`msd=12.53`) in favor of `0–2–3` (`msd=5.06, 3.56`), MHT peels the + 4-node tree and breaks the 2-node center tie (`{2, 3}`) by size (`60 > 30`) to + select cluster `3` as anchor, and total runtime is 69.3 s sequentially vs + 94.4 s for single-model PyCOLMAP (`multiple_models=True`). With smaller + clusters (`--max-cameras 30`), one local cluster diverged catastrophically + during local COLMAP, underscoring the sensitivity of internet-photo local + submodels to cluster size. diff --git a/gtsfm/averaging/graph_sfm.py b/gtsfm/averaging/graph_sfm.py new file mode 100644 index 000000000..e4e8f0ed2 --- /dev/null +++ b/gtsfm/averaging/graph_sfm.py @@ -0,0 +1,659 @@ +"""Graph-based image clustering and spanning-tree sub-model merging (GraphSfM). + +Implements the image clustering with maximum-spanning-tree (MaxST) subgraph +expansion and the minimum-spanning-tree (MinST) + minimum-height-tree (MHT) +sub-model merging algorithm from Chen et al., "Graph-Based Parallel Large Scale +Structure from Motion", arXiv:1912.10659, Sections 3.1–3.2 (Algorithms 1 and 2). +""" + +from __future__ import annotations + +from collections import deque +from typing import NamedTuple + +import networkx as nx +import numpy as np +from gtsam import Pose3, Rot3, Similarity3 +from scipy.sparse import diags +from scipy.sparse.csgraph import laplacian +from scipy.sparse.linalg import eigsh + + +class ClusterPartition(NamedTuple): + """Result of GraphSfM normalized-cut clustering and MaxST expansion. + + Attributes: + base_clusters: Disjoint primary camera sets from recursive normalized cut. + expanded_clusters: Overlapping camera sets after MaxST and completeness expansion. + maxst_edges: Cluster-pair edges ``(k1, k2)`` selected in the expansion MaxST. + completeness_ratios: Final completeness ratio ``eta(k)`` for each cluster. + """ + + base_clusters: list[set[int]] + expanded_clusters: list[set[int]] + maxst_edges: list[tuple[int, int]] + completeness_ratios: list[float] + + +class LocalSubmodel(NamedTuple): + """Camera poses and triangulated 3D observations from one local cluster. + + Attributes: + poses: Registered camera-to-world poses ``wTi`` keyed by image ID. + points3d: 3D landmark positions in the local frame keyed by local point ID. + observations: Mapping from ``(image_id, point2d_idx)`` to local point ID. + """ + + poses: dict[int, Pose3] + points3d: dict[int, np.ndarray] + observations: dict[tuple[int, int], int] + + +class PairwiseEdge(NamedTuple): + """Pairwise similarity transformation and symmetric MSD between two clusters. + + Attributes: + k1: First cluster index (``k1 < k2``). + k2: Second cluster index. + k1Sk2: Similarity transform mapping coordinates from cluster ``k2`` to ``k1``. + msd: Symmetric Mean Square Distance ``max(mse_k1k2, mse_k2k1)`` (Eq. 11). + num_common_cameras: Number of shared registered cameras. + num_common_points: Number of 3D correspondences used for ``msd``. + """ + + k1: int + k2: int + k1Sk2: Similarity3 + msd: float + num_common_cameras: int + num_common_points: int + + +class MergeResult(NamedTuple): + """Merged global camera poses and spanning-tree diagnostics. + + Attributes: + anchor: Index of the MHT root/base cluster. + transforms: Composed ``anchorSk`` similarity transform per merged cluster. + poses: Merged world-from-camera poses ``wTi`` in the anchor cluster frame. + camera_source: Cluster index that supplied each merged camera's pose. + cluster_edges: All valid pairwise edges in the cluster graph. + minst_edges: Pairwise edges selected in the Kruskal MinST of the kept component. + dropped_clusters: Cluster indices not connected to the kept component. + """ + + anchor: int + transforms: dict[int, Similarity3] + poses: dict[int, Pose3] + camera_source: dict[int, int] + cluster_edges: list[PairwiseEdge] + minst_edges: list[PairwiseEdge] + dropped_clusters: list[int] + + +def normalized_cut(graph: nx.Graph, max_cameras: int, min_cluster_size: int = 3) -> list[set[int]]: + """Recursively partition an inlier-weighted image graph via normalized cut. + + Args: + graph: Connected camera graph with positive edge weights (inlier counts). + max_cameras: Upper bound ``S_max`` on base cluster size. + min_cluster_size: Minimum cameras required per base cluster for local SfM. + + Returns: + Disjoint primary camera clusters sorted by minimum camera ID. + """ + if len(graph) <= max_cameras: + return [set(graph)] + ids = sorted(graph) + weights = nx.to_scipy_sparse_array(graph, nodelist=ids, dtype=float, format="csr") + degrees = np.asarray(weights.sum(axis=1)).ravel() + if np.any(degrees <= 0): + raise ValueError("Normalized cut requires a connected subgraph with positive weights") + normalized = laplacian(weights, normed=True).asformat("csr") + if len(ids) <= 128: + values, vectors = np.linalg.eigh(normalized.toarray()) + fiedler = (degrees**-0.5) * vectors[:, 1] + else: + values, vectors = eigsh(normalized, k=2, which="SM", v0=np.arange(1.0, len(ids) + 1)) + fiedler = (diags(degrees**-0.5) @ vectors)[:, np.argsort(values)[1]] + arrangement = np.argsort(fiedler, kind="stable") + total = float(np.sum(degrees)) + volume, crossing = 0.0, 0.0 + in_left = np.zeros(len(ids), dtype=bool) + best_score, best_split = np.inf, None + for position, index in enumerate(arrangement, 1): + start, stop = weights.indptr[index : index + 2] + neighbors = weights.indices[start:stop] + crossing += degrees[index] - 2.0 * float(weights.data[start:stop][in_left[neighbors]].sum()) + volume += degrees[index] + in_left[index] = True + if min(position, len(ids) - position) < min_cluster_size: + continue + score = crossing * (1.0 / volume + 1.0 / (total - volume)) + if score < best_score: + best_score, best_split = score, position + if best_split is None: + return [set(ids)] + left = [ids[i] for i in arrangement[:best_split]] + right = [ids[i] for i in arrangement[best_split:]] + components: list[set[int]] = [] + tiny: list[set[int]] = [] + for part in (left, right): + for comp in nx.connected_components(graph.subgraph(part)): + if len(comp) < min_cluster_size: + tiny.append(set(comp)) + else: + components.append(set(comp)) + if not components: + return [set(ids)] + # Reattach any disconnected tiny fragments to their strongest neighboring component. + for fragment in tiny: + best_target = max( + range(len(components)), + key=lambda idx: sum( + float(graph[u][v].get("weight", 1.0)) for u in fragment for v in components[idx] if graph.has_edge(u, v) + ), + ) + components[best_target].update(fragment) + if len(components) == 1: + return components + result: list[set[int]] = [] + for comp in components: + result.extend(normalized_cut(graph.subgraph(comp), max_cameras, min_cluster_size)) + return sorted(result, key=min) + + +def _completeness_ratio(clusters: list[set[int]], k: int) -> float: + """Compute completeness ratio ``eta(k) = sum_{j != k} |C_k ∩ C_j| / |C_k|``. + + Args: + clusters: Current expanded camera clusters. + k: Index of the cluster to evaluate. + + Returns: + Completeness ratio for cluster ``k``. + """ + if not clusters[k]: + return 0.0 + overlap = sum(len(clusters[k] & clusters[other]) for other in range(len(clusters)) if other != k) + return overlap / len(clusters[k]) + + +def cluster_and_expand( + graph: nx.Graph, + max_cameras: int, + completeness_ratio: float = 0.5, + max_overlap: int | None = None, + min_cluster_size: int = 3, + min_mst_overlap: int = 3, + seed: int = 0, +) -> ClusterPartition: + """Partition an image graph and expand clusters along a MaxST (Algorithm 1). + + Args: + graph: Connected inlier-weighted image graph. + max_cameras: Maximum size ``S_max`` of a base cluster before expansion. + completeness_ratio: Target completeness ratio ``C`` per cluster. + max_overlap: Optional cap ``O_max`` on shared images between two clusters. + min_cluster_size: Minimum size of each base cluster. + min_mst_overlap: Minimum overlapping cameras targeted on each MaxST edge. + seed: Random seed for non-MaxST edge selection in Algorithm 1, line 11. + + Returns: + Base clusters, expanded overlapping clusters, MaxST edges, and completeness ratios. + """ + base_clusters = normalized_cut(graph, max_cameras=max_cameras, min_cluster_size=min_cluster_size) + num_clusters = len(base_clusters) + if num_clusters <= 1: + return ClusterPartition( + base_clusters=base_clusters, + expanded_clusters=[set(c) for c in base_clusters], + maxst_edges=[], + completeness_ratios=[0.0] * num_clusters, + ) + + owner = {i: k for k, cluster in enumerate(base_clusters) for i in cluster} + lost_edges: dict[tuple[int, int], list[tuple[float, int, int]]] = {} + for u, v, data in graph.edges(data=True): + k1, k2 = owner[u], owner[v] + if k1 == k2: + continue + if k1 > k2: + k1, k2 = k2, k1 + u, v = v, u + weight = float(data.get("weight", 1.0)) + lost_edges.setdefault((k1, k2), []).append((weight, u, v)) + for pair in lost_edges: + lost_edges[pair].sort(key=lambda item: (-item[0], item[1], item[2])) + + # Build cluster graph weighted by number of lost image edges and compute MaxST via Kruskal. + cluster_graph = nx.Graph() + cluster_graph.add_nodes_from(range(num_clusters)) + for (k1, k2), edges in lost_edges.items(): + cluster_graph.add_edge(k1, k2, weight=len(edges)) + maxst = nx.maximum_spanning_tree(cluster_graph, weight="weight", algorithm="kruskal") + maxst_edges = sorted((min(k1, k2), max(k1, k2)) for k1, k2 in maxst.edges()) + maxst_edges.sort(key=lambda pair: (-len(lost_edges[pair]), pair)) + + expanded = [set(c) for c in base_clusters] + + def _expand_pair(k1: int, k2: int, enforce_min_overlap: bool) -> None: + """Add top-weighted lost edges between clusters ``k1`` and ``k2``.""" + pair_edges = lost_edges[(k1, k2)] + for _, u, v in pair_edges: + shared = len(expanded[k1] & expanded[k2]) + if max_overlap is not None and shared >= max_overlap: + break + need_k1 = _completeness_ratio(expanded, k1) < completeness_ratio + need_k2 = _completeness_ratio(expanded, k2) < completeness_ratio + need_mst = enforce_min_overlap and shared < min_mst_overlap + if not (need_k1 or need_k2 or need_mst): + break + if need_k1 or need_mst: + expanded[k1].add(v) + if need_k2 or need_mst: + expanded[k2].add(u) + + # Step 1 (Algorithm 1, lines 6–9): walk along the MaxST edges first. + for k1, k2 in maxst_edges: + _expand_pair(k1, k2, enforce_min_overlap=True) + + # Step 2 (Algorithm 1, lines 10–12): randomly select remaining lost cluster edges until complete. + remaining = sorted(set(lost_edges.keys()) - set(maxst_edges)) + rng = np.random.default_rng(seed) + rng.shuffle(remaining) + for k1, k2 in remaining: + if ( + _completeness_ratio(expanded, k1) >= completeness_ratio + and _completeness_ratio(expanded, k2) >= completeness_ratio + ): + continue + _expand_pair(k1, k2, enforce_min_overlap=False) + + ratios = [_completeness_ratio(expanded, k) for k in range(num_clusters)] + return ClusterPartition( + base_clusters=base_clusters, + expanded_clusters=expanded, + maxst_edges=maxst_edges, + completeness_ratios=ratios, + ) + + +def _fit_pose_similarity( + rotations_k1: list[np.ndarray], + centers_k1: np.ndarray, + rotations_k2: list[np.ndarray], + centers_k2: np.ndarray, +) -> Similarity3 | None: + """Fit ``k1Sk2`` using both camera orientations and centers (Section 3.2.1, Eqs. 1–6). + + Computes the chordal SO(3) mean rotation from ``R_i^{k1} (R_i^{k2})^T``, which avoids + the roll ambiguity of point-only Umeyama when camera centers are nearly collinear, + then solves for optimal scale and translation in closed form. + + Args: + rotations_k1: Camera-to-world rotation matrices in cluster ``k1``. + centers_k1: Camera centers in cluster ``k1``, shape ``(m, 3)``. + rotations_k2: Camera-to-world rotation matrices in cluster ``k2``. + centers_k2: Camera centers in cluster ``k2``, shape ``(m, 3)``. + + Returns: + Fitted GTSAM ``Similarity3`` mapping cluster ``k2`` to ``k1``, or ``None``. + """ + if len(centers_k1) < 2: + return None + rot_sum = np.sum([r1 @ r2.T for r1, r2 in zip(rotations_k1, rotations_k2)], axis=0) + u, _, vt = np.linalg.svd(rot_sum) + sign = np.ones(3) + if np.linalg.det(u) * np.linalg.det(vt) < 0: + sign[2] = -1.0 + rotation = u @ np.diag(sign) @ vt + + mu_k1 = np.mean(centers_k1, axis=0) + mu_k2 = np.mean(centers_k2, axis=0) + centered_k1 = centers_k1 - mu_k1 + centered_k2 = centers_k2 - mu_k2 + denom = float(np.sum(centered_k2**2)) + if denom <= 1e-12: + return None + rotated_k2 = centered_k2 @ rotation.T + scale = float(np.sum(centered_k1 * rotated_k2) / denom) + if not np.isfinite(scale) or scale <= 1e-9: + scale_fallback = _estimate_median_scale(centers_k1, centers_k2) + if scale_fallback is None: + return None + scale = scale_fallback + # Similarity3(R, t, s).transformFrom(x) = s * (R @ x + t), so t = (mu_k1 - s * R @ mu_k2) / s. + t_world = mu_k1 - scale * (rotation @ mu_k2) + return Similarity3(Rot3(rotation), t_world / scale, scale) + + +def _estimate_median_scale(centers_dst: np.ndarray, centers_src: np.ndarray) -> float | None: + """Estimate relative scale via median pairwise baseline ratio (Eqs. 1–2). + + Args: + centers_dst: Common camera centers in destination frame ``k1``, shape ``(m, 3)``. + centers_src: Common camera centers in source frame ``k2``, shape ``(m, 3)``. + + Returns: + Median scale factor mapping frame ``k2`` to frame ``k1``, or ``None`` if degenerate. + """ + num_cameras = len(centers_dst) + if num_cameras < 2: + return None + ratios: list[float] = [] + for a in range(num_cameras): + for b in range(a + 1, num_cameras): + denom = float(np.linalg.norm(centers_src[a] - centers_src[b])) + numer = float(np.linalg.norm(centers_dst[a] - centers_dst[b])) + if denom > 1e-9 and numer > 1e-9: + ratios.append(numer / denom) + if not ratios: + return None + scale = float(np.median(ratios)) + return scale if np.isfinite(scale) and scale > 1e-9 else None + + +def estimate_pairwise_similarity( + poses_k1: dict[int, Pose3], + poses_k2: dict[int, Pose3], + min_common_cameras: int = 3, + inlier_threshold_ratio: float = 0.15, + max_rotation_error_deg: float = 15.0, +) -> Similarity3 | None: + """Estimate ``k1Sk2`` from overlapping camera poses using scale + RANSAC (Sec. 3.2.1). + + Computes the median relative scale from Eq. (1)–(2), runs RANSAC over single-camera + Euclidean hypotheses ``(R_12, t_12)`` from Eq. (5)–(6), and refits on the inlier set. + + Args: + poses_k1: Camera-to-world poses in cluster ``k1``. + poses_k2: Camera-to-world poses in cluster ``k2``. + min_common_cameras: Minimum number of shared cameras required. + inlier_threshold_ratio: Translation inlier threshold as a fraction of destination scene extent. + max_rotation_error_deg: Maximum angular error (degrees) for a camera to count as an inlier. + + Returns: + Estimated ``Similarity3`` mapping cluster ``k2`` into cluster ``k1``, or ``None``. + """ + common = sorted(poses_k1.keys() & poses_k2.keys()) + if len(common) < min_common_cameras: + return None + centers_k1 = np.array([poses_k1[i].translation() for i in common], dtype=float) + centers_k2 = np.array([poses_k2[i].translation() for i in common], dtype=float) + rotations_k1 = [poses_k1[i].rotation().matrix() for i in common] + rotations_k2 = [poses_k2[i].rotation().matrix() for i in common] + + scale = _estimate_median_scale(centers_k1, centers_k2) + if scale is None: + return None + + # Exact 2-camera solution: use median scale + average rotation from the two cameras. + if len(common) == 2: + r_candidates = [rotations_k1[idx] @ rotations_k2[idx].T for idx in range(2)] + r_mean = r_candidates[0] @ Rot3.Expmap(0.5 * Rot3.Logmap(Rot3(r_candidates[0].T @ r_candidates[1]))).matrix() + t_world = np.mean(centers_k1 - scale * (centers_k2 @ r_mean.T), axis=0) + return Similarity3(Rot3(r_mean), t_world / scale, scale) + + extent = float(np.median(np.linalg.norm(centers_k1 - np.median(centers_k1, axis=0), axis=1))) + trans_thresh = max(inlier_threshold_ratio * extent, 1e-3) + rot_thresh_rad = np.deg2rad(max_rotation_error_deg) + + num_common = len(common) + pairs = [(a, b) for a in range(num_common) for b in range(a + 1, num_common)] + if len(pairs) > 250: + rng = np.random.default_rng(0) + chosen = rng.choice(len(pairs), size=250, replace=False) + pairs = [pairs[int(k)] for k in chosen] + + best_inliers: list[int] = [] + best_cost = np.inf + + # Every camera pair (a, b) defines a minimal Sim(3) hypothesis (s, R, t) immune to outlier scales. + for a, b in pairs: + denom = float(np.linalg.norm(centers_k2[a] - centers_k2[b])) + numer = float(np.linalg.norm(centers_k1[a] - centers_k1[b])) + if denom <= 1e-9 or numer <= 1e-9: + continue + s_hyp = numer / denom + r_hyp = rotations_k1[a] @ rotations_k2[a].T + t_hyp = centers_k1[a] - s_hyp * (r_hyp @ centers_k2[a]) + predicted = s_hyp * (centers_k2 @ r_hyp.T) + t_hyp + trans_errors = np.linalg.norm(predicted - centers_k1, axis=1) + rot_errors = np.array( + [np.linalg.norm(Rot3.Logmap(Rot3(rotations_k1[m].T @ r_hyp @ rotations_k2[m]))) for m in range(num_common)] + ) + inliers = [m for m in range(num_common) if trans_errors[m] <= trans_thresh and rot_errors[m] <= rot_thresh_rad] + cost = float(np.sum(np.minimum(trans_errors, trans_thresh) ** 2)) + if len(inliers) > len(best_inliers) or (len(inliers) == len(best_inliers) and cost < best_cost): + best_inliers = inliers + best_cost = cost + + if len(best_inliers) >= min_common_cameras: + refined = _fit_pose_similarity( + [rotations_k1[m] for m in best_inliers], + centers_k1[best_inliers], + [rotations_k2[m] for m in best_inliers], + centers_k2[best_inliers], + ) + if refined is not None: + return refined + # Fall back to fitting all common poses when RANSAC finds fewer than min_common_cameras inliers. + return _fit_pose_similarity(rotations_k1, centers_k1, rotations_k2, centers_k2) + + +def _compute_mse(aSb: Similarity3, points_a: np.ndarray, points_b: np.ndarray) -> float: + """Compute one-directional MSE from cluster ``b`` into cluster ``a`` (Eq. 10). + + Args: + aSb: Similarity transform mapping points from frame ``b`` into frame ``a``. + points_a: Corresponding 3D points in frame ``a``, shape ``(n, 3)``. + points_b: Corresponding 3D points in frame ``b``, shape ``(n, 3)``. + + Returns: + ``sqrt(1 / (2n) * sum ||aSb(X_b) - X_a||^2)``. + """ + rotation = aSb.rotation().matrix() + scale = aSb.scale() + translation = aSb.translation() + transformed = scale * ((points_b @ rotation.T) + translation) + squared = np.sum((transformed - points_a) ** 2, axis=1) + return float(np.sqrt(np.sum(squared) / (2.0 * len(points_a)))) + + +def compute_symmetric_msd(k1Sk2: Similarity3, points_k1: np.ndarray, points_k2: np.ndarray) -> float: + """Compute symmetric Mean Square Distance ``msd(k1, k2)`` (Eqs. 10–11). + + Args: + k1Sk2: Similarity transform mapping frame ``k2`` to frame ``k1``. + points_k1: Corresponding 3D points in frame ``k1``, shape ``(n, 3)``. + points_k2: Corresponding 3D points in frame ``k2``, shape ``(n, 3)``. + + Returns: + ``max(mse(k1 -> k2), mse(k2 -> k1))``. + """ + mse_2_to_1 = _compute_mse(k1Sk2, points_k1, points_k2) + mse_1_to_2 = _compute_mse(k1Sk2.inverse(), points_k2, points_k1) + return max(mse_1_to_2, mse_2_to_1) + + +def _shared_3d_correspondences( + model_k1: LocalSubmodel, + model_k2: LocalSubmodel, + max_points: int = 500, +) -> tuple[np.ndarray, np.ndarray]: + """Match triangulated 3D points across two clusters via shared 2D observations. + + Args: + model_k1: First local submodel. + model_k2: Second local submodel. + max_points: Maximum number of matched 3D point pairs to return. + + Returns: + Matched 3D coordinates in frame ``k1`` and frame ``k2``, each of shape ``(n, 3)``. + """ + shared_obs = model_k1.observations.keys() & model_k2.observations.keys() + pair_votes: dict[tuple[int, int], int] = {} + for obs in shared_obs: + key = (model_k1.observations[obs], model_k2.observations[obs]) + pair_votes[key] = pair_votes.get(key, 0) + 1 + if not pair_votes: + return np.empty((0, 3)), np.empty((0, 3)) + used_1: set[int] = set() + used_2: set[int] = set() + pts_1: list[np.ndarray] = [] + pts_2: list[np.ndarray] = [] + for (p1, p2), _ in sorted(pair_votes.items(), key=lambda item: (-item[1], item[0])): + if p1 in used_1 or p2 in used_2: + continue + used_1.add(p1) + used_2.add(p2) + pts_1.append(model_k1.points3d[p1]) + pts_2.append(model_k2.points3d[p2]) + if len(pts_1) >= max_points: + break + return np.asarray(pts_1, dtype=float), np.asarray(pts_2, dtype=float) + + +def find_mht_anchor(tree: nx.Graph, cluster_sizes: dict[int, int]) -> int: + """Find the Minimum Height Tree anchor node by iterative leaf peeling (Algorithm 2). + + Args: + tree: Connected acyclic undirected spanning tree over cluster indices. + cluster_sizes: Number of registered cameras per cluster for 2-node tie breaking. + + Returns: + Index of the chosen base/anchor cluster. + """ + if len(tree) == 0: + raise ValueError("Cannot find an anchor in an empty tree") + if len(tree) == 1: + return next(iter(tree.nodes)) + remaining = tree.copy() + while len(remaining) > 2: + leaves = [node for node, degree in remaining.degree() if degree <= 1] + remaining.remove_nodes_from(leaves) + candidates = sorted(remaining.nodes) + if len(candidates) == 1: + return candidates[0] + # Algorithm 2, line 9: when 2 nodes remain, pick the larger cluster (tie-break by smaller ID). + return max(candidates, key=lambda k: (cluster_sizes.get(k, 0), -k)) + + +def merge_submodels( + submodels: list[LocalSubmodel], + primary_clusters: list[set[int]] | None = None, + min_common_cameras: int = 3, + min_common_points: int = 3, + max_common_points: int = 500, +) -> MergeResult: + """Merge local sub-reconstructions via Kruskal MinST and MHT anchor (Section 3.2). + + Args: + submodels: Independently reconstructed local submodels. + primary_clusters: Optional disjoint primary camera sets used as pose tie-breakers. + min_common_cameras: Minimum shared cameras required to create a cluster-graph edge. + min_common_points: Minimum shared 3D track points before falling back to camera centers. + max_common_points: Maximum shared 3D points evaluated per cluster pair. + + Returns: + Global camera poses in the anchor frame along with tree diagnostics. + """ + num_clusters = len(submodels) + if num_clusters == 0: + raise ValueError("At least one local submodel is required") + + cluster_edges: list[PairwiseEdge] = [] + edge_lookup: dict[tuple[int, int], PairwiseEdge] = {} + for k1 in range(num_clusters): + for k2 in range(k1 + 1, num_clusters): + common_cams = sorted(submodels[k1].poses.keys() & submodels[k2].poses.keys()) + if len(common_cams) < min_common_cameras: + continue + k1Sk2 = estimate_pairwise_similarity( + submodels[k1].poses, + submodels[k2].poses, + min_common_cameras=min_common_cameras, + ) + if k1Sk2 is None: + continue + pts_k1, pts_k2 = _shared_3d_correspondences(submodels[k1], submodels[k2], max_points=max_common_points) + if len(pts_k1) < min_common_points: + pts_k1 = np.array([submodels[k1].poses[i].translation() for i in common_cams], dtype=float) + pts_k2 = np.array([submodels[k2].poses[i].translation() for i in common_cams], dtype=float) + msd = compute_symmetric_msd(k1Sk2, pts_k1, pts_k2) + if not np.isfinite(msd): + continue + edge = PairwiseEdge( + k1=k1, + k2=k2, + k1Sk2=k1Sk2, + msd=msd, + num_common_cameras=len(common_cams), + num_common_points=len(pts_k1), + ) + cluster_edges.append(edge) + edge_lookup[(k1, k2)] = edge + + cluster_graph = nx.Graph() + cluster_graph.add_nodes_from(range(num_clusters)) + for edge in cluster_edges: + cluster_graph.add_edge(edge.k1, edge.k2, weight=edge.msd) + + cluster_sizes = {k: len(submodels[k].poses) for k in range(num_clusters)} + largest_component = max( + nx.connected_components(cluster_graph), + key=lambda comp: (sum(cluster_sizes[k] for k in comp), len(comp), -min(comp)), + ) + dropped_clusters = sorted(set(range(num_clusters)) - largest_component) + kept_graph = cluster_graph.subgraph(largest_component) + minst = nx.minimum_spanning_tree(kept_graph, weight="weight", algorithm="kruskal") + anchor = find_mht_anchor(minst, cluster_sizes) + + # Compose transforms from each cluster in the MinST into the anchor frame via BFS. + transforms: dict[int, Similarity3] = {anchor: Similarity3()} + depth: dict[int, int] = {anchor: 0} + queue: deque[int] = deque([anchor]) + minst_edges: list[PairwiseEdge] = [] + while queue: + parent = queue.popleft() + for child in sorted(minst.neighbors(parent)): + if child in transforms: + continue + if parent < child: + edge = edge_lookup[(parent, child)] + parent_S_child = edge.k1Sk2 + else: + edge = edge_lookup[(child, parent)] + parent_S_child = edge.k1Sk2.inverse() + transforms[child] = transforms[parent].compose(parent_S_child) + depth[child] = depth[parent] + 1 + minst_edges.append(edge) + queue.append(child) + + # Assign each camera's merged pose from the cluster closest to the anchor (minimizing path drift). + merged_poses: dict[int, Pose3] = {} + camera_source: dict[int, int] = {} + all_cameras = sorted({i for k in transforms for i in submodels[k].poses}) + for i in all_cameras: + candidates = [k for k in transforms if i in submodels[k].poses] + best_k = min( + candidates, + key=lambda k: ( + depth[k], + 0 if primary_clusters is not None and i in primary_clusters[k] else 1, + k, + ), + ) + merged_poses[i] = transforms[best_k].transformFrom(submodels[best_k].poses[i]) + camera_source[i] = best_k + + return MergeResult( + anchor=anchor, + transforms=transforms, + poses=merged_poses, + camera_source=camera_source, + cluster_edges=cluster_edges, + minst_edges=minst_edges, + dropped_clusters=dropped_clusters, + ) diff --git a/scripts/run_graph_sfm.py b/scripts/run_graph_sfm.py new file mode 100644 index 000000000..8aa4496fb --- /dev/null +++ b/scripts/run_graph_sfm.py @@ -0,0 +1,445 @@ +"""Run the Chen et al. (GraphSfM, arXiv:1912.10659) baseline from a verified COLMAP database.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sqlite3 +from contextlib import closing +from pathlib import Path, PurePosixPath +from time import perf_counter + +import networkx as nx +import numpy as np +import pycolmap +from gtsam import Pose3, Rot3 + +from gtsfm.averaging.graph_sfm import LocalSubmodel, cluster_and_expand, merge_submodels +from gtsfm.loader.olsson_loader import OlssonLoader +from gtsfm.loader.yfcc_imb_loader import YfccImbLoader +from gtsfm.utils.align import sim3_from_Pose3_maps +from gtsfm.utils.metrics import compute_ba_pose_metrics + + +def _camera_to_world(image: pycolmap.Image) -> Pose3: + """Convert a registered COLMAP image to GTSfM world-from-camera convention. + + Args: + image: Registered COLMAP image. + + Returns: + Its camera-to-world pose ``wTi``. + """ + pose = image.cam_from_world.inverse() + return Pose3(Rot3(pose.rotation.matrix()), pose.translation) + + +def _prepare_frontend(source: Path, database: Path, min_inliers: int) -> tuple[dict[int, str], nx.Graph]: + """Freeze verified inputs and load their largest connected view graph. + + Args: + source: Original COLMAP database with keypoints and verified pairs. + database: Path to the filtered snapshot for reconstruction. + min_inliers: Minimum inlier count required to retain a verified pair. + + Returns: + Camera names by database ID and the inlier-weighted view graph. + """ + with closing(sqlite3.connect(source.resolve().as_uri() + "?mode=ro", uri=True)) as original: + with closing(sqlite3.connect(database)) as snapshot: + original.backup(snapshot) + with snapshot: + snapshot.execute("DELETE FROM two_view_geometries WHERE rows < ?", (min_inliers,)) + with pycolmap.Database(str(database)) as db: + names = {image.image_id: image.name for image in db.read_all_images()} + pair_ids, counts = db.read_two_view_geometry_num_inliers() + graph = nx.Graph() + graph.add_nodes_from(names) + for pair_id, count in zip(pair_ids, counts): + graph.add_edge(*pycolmap.Database.pair_id_to_image_pair(pair_id), weight=count) + if graph.number_of_edges() == 0: + raise ValueError("The frontend produced no usable verified pairs") + largest = max(nx.connected_components(graph), key=lambda component: (len(component), -min(component))) + return names, graph.subgraph(largest) + + +def _map_clusters( + database: Path, + images: Path, + output: Path, + names: dict[int, str], + clusters: list[set[int]], +) -> list[pycolmap.Reconstruction]: + """Reconstruct each expanded cluster independently with PyCOLMAP incremental SfM. + + Args: + database: Shared verified frontend database. + images: Source image directory. + output: Run artifact directory. + names: COLMAP image identifiers to filenames. + clusters: Expanded overlapping image clusters. + + Returns: + One incremental reconstruction per cluster. + """ + models: list[pycolmap.Reconstruction] = [] + for k, cluster in enumerate(clusters): + destination = output / f"local-{k}" + destination.mkdir() + options = pycolmap.IncrementalPipelineOptions( + image_names={names[i] for i in cluster}, + multiple_models=True, + extract_colors=False, + num_threads=2, + ) + candidates = pycolmap.incremental_mapping(str(database), str(images), str(destination), options) + if not candidates: + raise RuntimeError(f"Incremental mapping failed for cluster {k}") + model = max(candidates.values(), key=lambda candidate: candidate.num_reg_images()) + models.append(model) + return models + + +def _to_local_submodel(model: pycolmap.Reconstruction) -> LocalSubmodel: + """Extract camera poses and 3D point observations from a PyCOLMAP reconstruction. + + Args: + model: Local incremental reconstruction. + + Returns: + ``LocalSubmodel`` in GTSfM world-from-camera convention. + """ + poses = {i: _camera_to_world(model.image(i)) for i in model.reg_image_ids()} + points3d = {j: np.asarray(point.xyz, dtype=float) for j, point in model.points3D.items()} + observations: dict[tuple[int, int], int] = {} + for j, point in model.points3D.items(): + for elem in point.track.elements: + observations[(elem.image_id, elem.point2D_idx)] = j + return LocalSubmodel(poses=poses, points3d=points3d, observations=observations) + + +def _estimated_calibrations( + camera_source: dict[int, int], + models: list[pycolmap.Reconstruction], +) -> dict[int, pycolmap.Camera]: + """Carry local intrinsics through to triangulation and final bundle adjustment. + + Args: + camera_source: Mapping from merged image ID to the cluster that supplied its pose. + models: Local incremental SfM models per cluster. + + Returns: + One fitted camera per database camera ID, selecting the cluster with most 3D support. + """ + calibrations: dict[int, pycolmap.Camera] = {} + support: dict[int, int] = {} + by_cluster: dict[int, list[int]] = {} + for i, k in camera_source.items(): + by_cluster.setdefault(k, []).append(i) + for k in sorted(by_cluster): + model = models[k] + local_support: dict[int, int] = {} + for i in by_cluster[k]: + camera_id = model.image(i).camera_id + local_support[camera_id] = local_support.get(camera_id, 0) + model.image(i).num_points3D + for camera_id, count in local_support.items(): + if count > support.get(camera_id, -1): + support[camera_id] = count + calibrations[camera_id] = model.camera(camera_id) + return calibrations + + +def _refine( + poses: dict[int, Pose3], + calibrations: dict[int, pycolmap.Camera], + database: Path, + images: Path, + output: Path, + fix_intrinsics: bool, +) -> tuple[pycolmap.Reconstruction, dict[int, Pose3]]: + """Triangulate verified tracks and run final sparse BA with PyCOLMAP. + + Args: + poses: Merged world-from-camera poses keyed by database image ID. + calibrations: Local camera intrinsics keyed by database camera ID. + database: Verified frontend database shared with local mapping. + images: Source image directory. + output: Directory where the final COLMAP model will be written. + fix_intrinsics: Hold the local calibration estimates fixed during final BA. + + Returns: + Refined reconstruction and poses after triangulation but before final BA. + """ + reconstruction = pycolmap.Reconstruction() + with pycolmap.Database(str(database)) as db: + for camera in calibrations.values(): + reconstruction.add_camera(camera) + for i in sorted(poses): + original = db.read_image(i) + wTi = poses[i] + cam_from_world_rot = wTi.rotation().matrix().T + cam_from_world_trans = -cam_from_world_rot @ wTi.translation() + rigid = pycolmap.Rigid3d(np.column_stack((cam_from_world_rot, cam_from_world_trans))) + image = pycolmap.Image( + name=original.name, + keypoints=db.read_keypoints(i)[:, :2].astype(float), + cam_from_world=rigid, + camera_id=original.camera_id, + id=i, + ) + reconstruction.add_image(image) + reconstruction.register_image(i) + output.mkdir() + tri_options = pycolmap.IncrementalPipelineOptions(num_threads=2, extract_colors=False) + reconstruction = pycolmap.triangulate_points( + reconstruction, str(database), str(images), str(output), options=tri_options + ) + if reconstruction.num_points3D() == 0: + raise RuntimeError("Triangulation produced no sparse points") + triangulated = {i: _camera_to_world(reconstruction.image(i)) for i in reconstruction.reg_image_ids()} + ba_options = pycolmap.BundleAdjustmentOptions( + refine_focal_length=not fix_intrinsics, + refine_extra_params=not fix_intrinsics, + print_summary=False, + ) + ba_options.solver_options.num_threads = 2 + pycolmap.bundle_adjustment(reconstruction, ba_options) + reconstruction.write(str(output)) + return reconstruction, triangulated + + +def _score(reference: dict[int, Pose3], estimates: dict[int, Pose3]) -> dict[str, float]: + """Compute the standard GTSfM pose AUC with a fixed reference denominator. + + Args: + reference: Reference world-from-camera poses for this scene. + estimates: Estimated world-from-camera poses keyed by database ID. + + Returns: + Pose AUC scalar values at GTSfM's published thresholds. + """ + alignment = sim3_from_Pose3_maps(reference, estimates) + group = compute_ba_pose_metrics(reference, {i: alignment.transformFrom(pose) for i, pose in estimates.items()}) + return {metric.name: float(metric.data) for metric in group.metrics if metric.name.startswith("pose_auc_")} + + +_BUNDLER_TO_GTSAM_CAMERA = np.diag([1.0, -1.0, -1.0]) + + +def _read_bundler_poses(bundle_path: Path, list_path: Path) -> dict[str, Pose3]: + """Read only the camera section of a Bundler `.out` reconstruction. + + Args: + bundle_path: Path to the Bundler `.out` file (e.g. `bundle.orig.out`). + list_path: Path to the matching image list (e.g. `list.orig.txt`). + + Returns: + World-from-camera poses ``wTi`` in GTSAM convention keyed by image basename. + """ + with list_path.open() as f: + image_names = [Path(line.split()[0]).name for line in f if line.strip()] + with bundle_path.open() as f: + header = "" + for line in f: + stripped = line.strip() + if stripped and not stripped.startswith("#"): + header = stripped + break + num_cameras = int(header.split()[0]) + if num_cameras != len(image_names): + raise ValueError(f"{bundle_path} has {num_cameras} cameras, but {list_path} lists {len(image_names)}") + poses: dict[str, Pose3] = {} + for idx in range(num_cameras): + focal_line = f.readline().split() + r0 = [float(v) for v in f.readline().split()] + r1 = [float(v) for v in f.readline().split()] + r2 = [float(v) for v in f.readline().split()] + t = np.asarray([float(v) for v in f.readline().split()], dtype=float) + focal = float(focal_line[0]) + rot = np.asarray([r0, r1, r2], dtype=float) + if focal == 0.0 or not np.any(rot): + continue + iRw = Rot3.ClosestTo(_BUNDLER_TO_GTSAM_CAMERA @ rot) + iTw = Pose3(iRw, _BUNDLER_TO_GTSAM_CAMERA @ t) + poses[image_names[idx]] = iTw.inverse() + return poses + + +def _load_reference( + names: dict[int, str], + olsson: Path | None, + yfcc_imb: Path | None, + bundler: Path | None = None, + bundler_list: Path | None = None, +) -> dict[int, Pose3]: + """Match reference cameras to database images by the dataset's filename convention. + + Args: + names: Image paths relative to the source images directory, by database ID. + olsson: Optional root of the Olsson scene. + yfcc_imb: Optional root of the Image Matching Benchmark scene. + bundler: Optional Bundler `.out` file (requires ``bundler_list``). + bundler_list: Optional image list matching ``bundler``. + + Returns: + Reference poses keyed by database ID. + """ + if bundler is not None: + if bundler_list is None: + raise ValueError("--bundler-reference requires --bundler-list") + bundler_poses = _read_bundler_poses(bundler, bundler_list) + ids = {PurePosixPath(name).name: i for i, name in names.items()} + reference = {ids[name]: pose for name, pose in bundler_poses.items() if name in ids} + if len(reference) < 3: + raise ValueError("Need at least three matching reference cameras for pose evaluation") + return {i: reference[i] for i in sorted(reference)} + if olsson is not None: + loader = OlssonLoader(str(olsson)) + ids = {str(PurePosixPath(name)): i for i, name in names.items()} + elif yfcc_imb is not None: + loader = YfccImbLoader(str(yfcc_imb), co_visibility_threshold=0.0) + ids = {} + for i, name in names.items(): + key = str(PurePosixPath(name).with_suffix("")) + if key in ids: + raise ValueError(f"IMB reference name is ambiguous for database images: {key}") + ids[key] = i + else: + return {} + reference = { + ids[key]: pose + for i, name in enumerate(loader.image_filenames()) + if (key := str(PurePosixPath(name))) in ids and (pose := loader.get_camera_pose(i)) is not None + } + if len(reference) < 3: + raise ValueError("Need at least three matching reference cameras for pose evaluation") + return {i: reference[i] for i in sorted(reference)} + + +def main() -> None: + """Run and score the GraphSfM baseline from cached verified image pairs.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--database", type=Path, required=True) + parser.add_argument("--images", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + reference_options = parser.add_mutually_exclusive_group() + reference_options.add_argument("--olsson-reference", type=Path) + reference_options.add_argument("--yfcc-imb-reference", type=Path) + reference_options.add_argument("--bundler-reference", type=Path) + parser.add_argument("--bundler-list", type=Path) + parser.add_argument("--max-cameras", type=int, default=150) + parser.add_argument("--min-pair-inliers", type=int, default=15) + parser.add_argument("--completeness-ratio", type=float, default=0.5) + parser.add_argument("--max-overlap", type=int, default=None) + parser.add_argument("--min-common-cameras", type=int, default=3) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--fix-final-intrinsics", action="store_true") + args = parser.parse_args() + if args.max_cameras < 3 or args.min_pair_inliers < 1 or args.min_common_cameras < 2: + parser.error("Need at least 3 cameras per cluster, 1 inlier per pair, and 2 common cameras for merging") + if args.completeness_ratio < 0.0: + parser.error("--completeness-ratio must be non-negative") + if args.max_overlap is not None and args.max_overlap < 2: + parser.error("--max-overlap must be >= 2 when provided") + if not args.database.is_file() or not args.images.is_dir(): + parser.error("The database and image directory must exist") + + args.output.mkdir(parents=True) + started = perf_counter() + pycolmap.set_random_seed(args.seed) + pycolmap.logging.minloglevel = pycolmap.logging.ERROR + + database = args.output / "frontend.db" + names, graph = _prepare_frontend(args.database, database, args.min_pair_inliers) + partition = cluster_and_expand( + graph, + max_cameras=args.max_cameras, + completeness_ratio=args.completeness_ratio, + max_overlap=args.max_overlap, + seed=args.seed, + ) + if len(partition.base_clusters) < 2: + parser.error("Choose --max-cameras below the scene size to exercise GraphSfM clustering and merging") + partitioned = perf_counter() + + models = _map_clusters(database, args.images, args.output, names, partition.expanded_clusters) + submodels = [_to_local_submodel(model) for model in models] + reconstructed_local = perf_counter() + + merged = merge_submodels( + submodels, + primary_clusters=partition.base_clusters, + min_common_cameras=args.min_common_cameras, + ) + merged_time = perf_counter() + + final, triangulated = _refine( + merged.poses, + _estimated_calibrations(merged.camera_source, models), + database, + args.images, + args.output / "reconstruction", + args.fix_final_intrinsics, + ) + finished = perf_counter() + + with database.open("rb") as snapshot_file: + frontend_sha256 = hashlib.file_digest(snapshot_file, "sha256").hexdigest() + + summary = { + "frontend_sha256": frontend_sha256, + "input_cameras": len(names), + "outside_largest_component": [names[i] for i in sorted(names.keys() - graph.nodes)], + "verified_pairs": graph.number_of_edges(), + "min_pair_inliers": args.min_pair_inliers, + "completeness_ratio_target": args.completeness_ratio, + "max_overlap": args.max_overlap, + "base_clusters": [[names[i] for i in sorted(c)] for c in partition.base_clusters], + "expanded_clusters": [[names[i] for i in sorted(c)] for c in partition.expanded_clusters], + "completeness_ratios": [round(r, 4) for r in partition.completeness_ratios], + "maxst_edges": [list(edge) for edge in partition.maxst_edges], + "local_registered_counts": [len(sub.poses) for sub in submodels], + "anchor_cluster": merged.anchor, + "dropped_clusters": merged.dropped_clusters, + "cluster_graph_edges": [ + { + "k1": e.k1, + "k2": e.k2, + "msd": e.msd, + "num_common_cameras": e.num_common_cameras, + "num_common_points": e.num_common_points, + "scale": e.k1Sk2.scale(), + } + for e in merged.cluster_edges + ], + "minst_edges": [{"k1": e.k1, "k2": e.k2, "msd": e.msd, "scale": e.k1Sk2.scale()} for e in merged.minst_edges], + "merged_cameras": len(merged.poses), + "final_intrinsics_fixed": args.fix_final_intrinsics, + "registered_after_refinement": final.num_reg_images(), + "final_points": final.num_points3D(), + "final_mean_reprojection_error_px": final.compute_mean_reprojection_error(), + "stages_seconds": { + "clustering_and_expansion": partitioned - started, + "local_reconstruction": reconstructed_local - partitioned, + "submodel_merging": merged_time - reconstructed_local, + "triangulation_and_final_ba": finished - merged_time, + }, + } + reference = _load_reference( + names, args.olsson_reference, args.yfcc_imb_reference, args.bundler_reference, args.bundler_list + ) + if reference: + summary["reference_cameras"] = len(reference) + summary["pose_auc_after_merging"] = _score(reference, merged.poses) + summary["pose_auc_after_triangulation"] = _score(reference, triangulated) + summary["pose_auc_after_refinement"] = _score( + reference, {i: _camera_to_world(final.image(i)) for i in final.reg_image_ids()} + ) + result = json.dumps(summary, indent=2, allow_nan=False) + (args.output / "metrics.json").write_text(result + "\n") + print(result) + + +if __name__ == "__main__": + main() diff --git a/tests/averaging/test_graph_sfm.py b/tests/averaging/test_graph_sfm.py new file mode 100644 index 000000000..7b7a14766 --- /dev/null +++ b/tests/averaging/test_graph_sfm.py @@ -0,0 +1,268 @@ +"""Unit and regression tests for GraphSfM clustering and spanning-tree merging.""" + +from __future__ import annotations + +import shutil +import sqlite3 +from contextlib import closing +from pathlib import Path + +import networkx as nx +import numpy as np +from gtsam import Pose3, Rot3, Similarity3 + +from gtsfm.averaging.graph_sfm import ( + LocalSubmodel, + cluster_and_expand, + compute_symmetric_msd, + estimate_pairwise_similarity, + find_mht_anchor, + merge_submodels, +) +from scripts.run_graph_sfm import _prepare_frontend, _read_bundler_poses + + +def _make_chain_of_cliques(num_cliques: int, clique_size: int) -> nx.Graph: + """Build a weighted graph of dense cliques linked by lighter bridge edges. + + Args: + num_cliques: Number of dense communities in the chain. + clique_size: Number of cameras per community. + + Returns: + Connected weighted camera graph. + """ + graph = nx.Graph() + for c in range(num_cliques): + nodes = list(range(c * clique_size, (c + 1) * clique_size)) + for idx, u in enumerate(nodes): + for v in nodes[idx + 1 :]: + graph.add_edge(u, v, weight=100.0) + if c > 0: + prev_nodes = list(range((c - 1) * clique_size, c * clique_size)) + for u, v in zip(prev_nodes[:3], nodes[:3]): + graph.add_edge(u, v, weight=15.0) + return graph + + +def test_cluster_and_expand_satisfies_size_maxst_and_completeness() -> None: + """Partition cliques cleanly, build a spanning MaxST, and expand to meet completeness.""" + graph = _make_chain_of_cliques(num_cliques=3, clique_size=5) + + partition = cluster_and_expand(graph, max_cameras=5, completeness_ratio=0.4, max_overlap=4, seed=0) + + assert len(partition.base_clusters) == 3 + assert all(len(c) <= 5 for c in partition.base_clusters) + assert set().union(*partition.base_clusters) == set(graph.nodes) + assert sum(len(c) for c in partition.base_clusters) == len(graph) + # MaxST over 3 clusters has 2 edges and connects all clusters. + assert len(partition.maxst_edges) == 2 + for k1, k2 in partition.maxst_edges: + shared = len(partition.expanded_clusters[k1] & partition.expanded_clusters[k2]) + assert 2 <= shared <= 4 + assert all(ratio >= 0.4 for ratio in partition.completeness_ratios) + + +def test_estimate_pairwise_similarity_rejects_outlier_camera() -> None: + """Recover true Sim(3) via median scale and RANSAC even with a corrupted shared pose.""" + true_s = Similarity3(Rot3.Ypr(0.3, -0.2, 0.1), np.array([1.2, -0.5, 0.8]), 2.5) + world_poses = { + 0: Pose3(Rot3.Rx(0.1), np.array([0.0, 0.0, 0.0])), + 1: Pose3(Rot3.Ry(0.2), np.array([2.0, 0.5, -0.3])), + 2: Pose3(Rot3.Rz(-0.15), np.array([1.0, 2.5, 0.4])), + 3: Pose3(Rot3.Ypr(0.2, 0.1, -0.1), np.array([-1.5, 1.5, 1.2])), + 4: Pose3(Rot3.Rx(-0.25), np.array([0.5, -2.0, 0.9])), + } + poses_k1 = {i: true_s.transformFrom(pose) for i, pose in world_poses.items()} + poses_k2 = dict(world_poses) + # Corrupt one shared camera severely in cluster k2. + poses_k2[4] = Pose3(Rot3.Rz(2.5), np.array([25.0, -30.0, 15.0])) + + estimated = estimate_pairwise_similarity(poses_k1, poses_k2, min_common_cameras=3) + + assert estimated is not None + assert np.isclose(estimated.scale(), true_s.scale(), atol=1e-4) + for i in range(4): + aligned = estimated.transformFrom(poses_k2[i]) + np.testing.assert_allclose(aligned.translation(), poses_k1[i].translation(), atol=1e-4) + np.testing.assert_allclose(aligned.rotation().matrix(), poses_k1[i].rotation().matrix(), atol=1e-4) + + +def test_compute_symmetric_msd_is_symmetric_and_matches_formula() -> None: + """Verify Eq. (10)–(11): msd(k1, k2) == msd(k2, k1) and matches max(mse_12, mse_21).""" + pts_k2 = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 2.0, 1.0]]) + s_12 = Similarity3(Rot3(), np.array([0.0, 0.0, 0.0]), 2.0) + # Exact transformed points in frame k1 plus a constant [1, 0, 0] residual on each point. + pts_k1 = 2.0 * pts_k2 + np.array([1.0, 0.0, 0.0]) + + msd_forward = compute_symmetric_msd(s_12, pts_k1, pts_k2) + msd_reverse = compute_symmetric_msd(s_12.inverse(), pts_k2, pts_k1) + + # Residual in k1 is 1.0 per point -> mse_21 = sqrt(1/2); in k2 is 0.5 -> mse_12 = sqrt(1/8). + expected = float(np.sqrt(0.5)) + assert np.isclose(msd_forward, expected, atol=1e-12) + assert np.isclose(msd_reverse, expected, atol=1e-12) + + +def test_find_mht_anchor_center_and_size_tiebreak() -> None: + """Peel leaves layer-by-layer to pick the tree center or larger of two central nodes.""" + # 5-node chain: 0 - 1 - 2 - 3 - 4 -> unique center is 2. + chain5 = nx.path_graph(5) + assert find_mht_anchor(chain5, {k: 10 for k in range(5)}) == 2 + + # 4-node chain: 0 - 1 - 2 - 3 -> centers are 1 and 2; larger cluster wins. + chain4 = nx.path_graph(4) + assert find_mht_anchor(chain4, {0: 50, 1: 12, 2: 20, 3: 50}) == 2 + assert find_mht_anchor(chain4, {0: 50, 1: 25, 2: 20, 3: 50}) == 1 + + +def test_merge_submodels_minst_drops_corrupted_cycle_edge_and_recovers_poses() -> None: + """Select accurate MinST edges over a noisy cycle edge and align all clusters to the MHT root.""" + rng = np.random.default_rng(7) + num_cameras = 12 + world_poses = { + i: Pose3( + Rot3.Ypr(0.1 * i, -0.05 * i, 0.03 * i), + np.array([float(i), np.sin(0.5 * i), 0.3 * np.cos(0.5 * i)]), + ) + for i in range(num_cameras) + } + world_points = {j: rng.uniform(-3.0, 3.0, size=3) for j in range(30)} + + # Three overlapping clusters forming a chain 0 -- 1 -- 2, plus a noisy shortcut 0 -- 2. + cluster_members = [ + [0, 1, 2, 3, 4, 5, 11], + [3, 4, 5, 6, 7, 8], + [6, 7, 8, 9, 10, 11, 0, 1], + ] + local_from_world = [ + Similarity3(Rot3.Rx(0.2), np.array([1.0, -0.5, 0.3]), 1.4), + Similarity3(Rot3.Ry(-0.3), np.array([-0.7, 1.2, -0.4]), 0.6), + Similarity3(Rot3.Rz(0.4), np.array([0.4, 0.8, -1.1]), 2.1), + ] + + submodels: list[LocalSubmodel] = [] + for k, members in enumerate(cluster_members): + transform = local_from_world[k] + poses = {i: transform.transformFrom(world_poses[i]) for i in members} + # Inject large noise only into the shared shortcut observations between cluster 0 and 2. + pts = {j: transform.transformFrom(pos) for j, pos in world_points.items()} + if k == 2: + # Corrupt cameras 0 and 1 in cluster 2 so edge (0, 2) has a large MSD. + poses[0] = Pose3(poses[0].rotation(), poses[0].translation() + np.array([2.5, -1.5, 1.0])) + poses[1] = Pose3(poses[1].rotation(), poses[1].translation() + np.array([-2.0, 2.0, -1.0])) + obs = {(i, j): j for i in members for j in range(10)} + submodels.append(LocalSubmodel(poses=poses, points3d=pts, observations=obs)) + + result = merge_submodels(submodels, min_common_cameras=3) + + # MinST should pick edges (0, 1) and (1, 2) and drop the corrupted (0, 2) shortcut; MHT anchor is 1. + assert result.anchor == 1 + assert result.dropped_clusters == [] + minst_pairs = {(e.k1, e.k2) for e in result.minst_edges} + assert minst_pairs == {(0, 1), (1, 2)} + assert len(result.poses) == num_cameras + + # Every camera in the anchor frame (cluster 1) should match ground truth transformed into cluster 1. + expected_in_anchor = {i: local_from_world[1].transformFrom(pose) for i, pose in world_poses.items()} + for i in range(num_cameras): + np.testing.assert_allclose(result.poses[i].translation(), expected_in_anchor[i].translation(), atol=1e-4) + np.testing.assert_allclose( + result.poses[i].rotation().matrix(), expected_in_anchor[i].rotation().matrix(), atol=1e-4 + ) + + +def test_snapshot_captures_uncheckpointed_verified_matches(tmp_path: Path) -> None: + """Freeze verified pairs via SQLite backup without mutating the source database. + + Args: + tmp_path: Temporary directory isolated from the source fixture. + """ + fixture = Path(__file__).resolve().parents[1] / "data" / "set1_lund_door" / "colmap.db" + source = tmp_path / "source.db" + shutil.copyfile(fixture, source) + with closing(sqlite3.connect(source)) as writer: + writer.execute("PRAGMA journal_mode=WAL") + writer.execute("PRAGMA wal_autocheckpoint=0") + initial_bytes = source.read_bytes() + _, original_graph = _prepare_frontend(source, tmp_path / "original.db", 15) + with writer: + writer.execute( + "DELETE FROM two_view_geometries WHERE pair_id = " + "(SELECT min(pair_id) FROM two_view_geometries WHERE rows >= 15)" + ) + assert source.read_bytes() == initial_bytes + _, changed_graph = _prepare_frontend(source, tmp_path / "changed.db", 15) + assert changed_graph.number_of_edges() == original_graph.number_of_edges() - 1 + assert source.read_bytes() == initial_bytes + + +def test_estimate_pairwise_similarity_survives_catastrophic_scale_outliers() -> None: + """Recover Sim(3) even when >30% of overlapping cameras diverge by 1e7 units.""" + true_s = Similarity3(Rot3.Ypr(-0.4, 0.25, -0.15), np.array([2.0, -1.0, 0.5]), 0.85) + world_poses = { + i: Pose3( + Rot3.Ypr(0.15 * i, -0.1 * i, 0.05 * i), + np.array([float(i), np.cos(0.7 * i), np.sin(0.5 * i)]), + ) + for i in range(10) + } + poses_k1 = {i: true_s.transformFrom(pose) for i, pose in world_poses.items()} + poses_k2 = dict(world_poses) + # Corrupt 4 of 10 cameras (40%) to 1e7 units, biasing naive median pairwise scale. + for bad in (6, 7, 8, 9): + poses_k2[bad] = Pose3(Rot3.Rz(1.8), np.array([1.5e7 * bad, -2.0e7, 3.0e7])) + + estimated = estimate_pairwise_similarity(poses_k1, poses_k2, min_common_cameras=3) + + assert estimated is not None + assert np.isclose(estimated.scale(), true_s.scale(), atol=1e-4) + for i in range(6): + aligned = estimated.transformFrom(poses_k2[i]) + np.testing.assert_allclose(aligned.translation(), poses_k1[i].translation(), atol=1e-4) + np.testing.assert_allclose(aligned.rotation().matrix(), poses_k1[i].rotation().matrix(), atol=1e-4) + + +def test_read_bundler_poses_converts_camera_axes_and_skips_unregistered(tmp_path: Path) -> None: + """Parse Bundler `.out` cameras into GTSAM world-from-camera poses and skip zero cameras. + + Args: + tmp_path: Temporary directory for synthetic Bundler files. + """ + list_path = tmp_path / "list.orig.txt" + bundle_path = tmp_path / "bundle.orig.out" + list_path.write_text("db/img0.jpg 0 1200.0\ndb/img1.jpg\ndb/img2.jpg 0 900.0\n") + + # Camera 0: identity in Bundler -> rotated 180 deg around X in GTSAM, centered at [1, 2, 3]. + # Camera 1: unregistered (focal = 0, zeros). + # Camera 2: 90 deg rotation around Z in Bundler. + r0 = np.eye(3) + c0 = np.array([1.0, 2.0, 3.0]) + t0 = -r0 @ c0 + r2 = np.array([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) + c2 = np.array([-2.0, 0.5, 4.0]) + t2 = -r2 @ c2 + + def _fmt_cam(f: float, r: np.ndarray, t: np.ndarray) -> str: + rows = "\n".join(" ".join(f"{v:.8f}" for v in row) for row in r) + t_str = " ".join(f"{v:.8f}" for v in t) + return f"{f:.4f} 0.0 0.0\n{rows}\n{t_str}\n" + + bundle_text = ( + "# Bundle file v0.3\n" + "3 1\n" + + _fmt_cam(1200.0, r0, t0) + + _fmt_cam(0.0, np.zeros((3, 3)), np.zeros(3)) + + _fmt_cam(900.0, r2, t2) + + "0.0 0.0 0.0\n0 0 0\n0\n" + ) + bundle_path.write_text(bundle_text) + + poses = _read_bundler_poses(bundle_path, list_path) + + assert sorted(poses.keys()) == ["img0.jpg", "img2.jpg"] + np.testing.assert_allclose(poses["img0.jpg"].translation(), c0, atol=1e-6) + np.testing.assert_allclose(poses["img0.jpg"].rotation().matrix(), np.diag([1.0, -1.0, -1.0]), atol=1e-6) + np.testing.assert_allclose(poses["img2.jpg"].translation(), c2, atol=1e-6) + expected_r2 = (np.diag([1.0, -1.0, -1.0]) @ r2).T + np.testing.assert_allclose(poses["img2.jpg"].rotation().matrix(), expected_r2, atol=1e-6)