Data structureadvanced
View graph
Also called epipolar graph, match graph.
A graph with one vertex per image and an edge for each verified pair, labeled by the relative pose, that global and incremental SfM work on.
- Time
- O(1) add_edge · cycle_errorO(N) chain_rotationsO(E log E) spanning_tree
- Space
- O(N + E) extra
- Where
- E = the number of verified image pairs (edges); N = the number of images (vertices)
- Model
- Real RAM
- Properties
- deterministicexactnot static
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Venu Madhav Govindu, Noam Levi, Michael Werman, Noah Snavely, 2001
A view graph has one vertex for each image of a reconstruction and one edge for each pair of images that has passed a geometric check. The edge stores the relative pose of camera with respect to camera , a rotation and a unit translation direction , as estimated from the essential matrix of the pair, and a weight, usually the number of inlier matches. It is the data structure on which global structure from motion runs rotation averaging and translation averaging, and on which incremental structure from motion picks its first pair and the order of the next images. Its connected components are the parts of the scene that can be reconstructed together, a maximum spanning tree of the weights gives a quick first set of absolute rotations, and the product of the relative rotations around a cycle measures how well the edges agree. The name epipolar graph stresses the two-view geometry on the edges. The name match graph is also used for it, and also for the finer graph of single features from which feature tracks are built.
In plain words
Draw one dot for each photo. When two photos show the same part of the scene, and the program has checked that their matched points fit one camera motion, draw a line between the two dots. On each line, write how the second camera is turned and in which direction it moved compared with the first one, and how many points support this. That drawing is the view graph. It tells which photos can be put together, which pair is the best place to start, and where a wrong line might be: if you go around a loop of lines and add up the turns, you should come back to where you started. If you do not, one of the lines in the loop is wrong.
The abstract type
The view graph is an undirected graph with a label on each directed form of each edge. The operations are:
- add-view(i) and add-edge(i, j, R, t, w): insert an image, or a verified pair with the relative pose and the weight .
- remove-edge(i, j): delete a pair, for example after an outlier test.
- relative(i, j): return the label , in the direction asked for.
- neighbors(i), edges() and components(): the adjacency queries and the connected components.
- maximum-spanning-tree(): a spanning tree, or a forest if is not connected, of largest total weight.
- chain-rotations(tree, root): absolute rotations along the tree, with .
- cycle-error(i, j, k): the angle of the rotation around a triangle.
The label convention is the one of the relative pose problem: a point with coordinates in the frame of camera has the coordinates in the frame of camera . With absolute poses , this gives and , and the essential matrix of the pair is . The two-view data fix only up to a positive scale, so it is stored as a unit vector.
Representation
The reference code stores a dictionary of dictionaries: adj[i][j] holds the label of the direction , and adj[j][i] holds the label of the reverse direction. Each edge is stored twice so that a walk can leave a vertex along any edge without a test on the direction. The reverse of the label is , since . Large systems store the edges in a flat array with an index from each image pair, and keep the inlier matches of each edge next to its pose, because the later steps need them.
Operations
ADD-EDGE(G, i, j, R, t, w)- 1
adj[i][j] <- (R, t, w) - 2
adj[j][i] <- (R^T, -R^T t, w)
MAXIMUM-SPANNING-TREE(G)- 1
make each vertex its own set ; T <- empty - 2
for each edge (i, j) in the order of decreasing weight - 3
if FIND(i) != FIND(j) - 4
UNION(i, j) ; add (i, j) to T - 5
return T
CHAIN-ROTATIONS(G, T, root)- 1
R_root <- I ; Q <- a queue holding root - 2
while Q is not empty - 3
i <- the first vertex of Q, removed from Q - 4
for each tree neighbor j of i that has no rotation yet - 5
R_j <- R_ij R_i ; add j to Q - 6
return all R_j CYCLE-ERROR(G, i, j, k)- 7
return the angle of R_ki R_jk R_ij, that is arccos((trace - 1) / 2)
Lines L1 and L2 keep the two directions of an edge consistent. Lines L3 to L7 are Kruskal's method with the largest weights first; ties are broken by the vertex numbers, so the result is deterministic. Lines L8 to L12 walk the tree in breadth-first order and compose the relative rotations, which makes every tree edge exact: . Line L14 composes the three rotations of a triangle; for exact edges the product is , so the angle is the error of the loop.
Example
Take 4 images whose cameras turn about the axis by , , and . The pairs give 5 edges, each written as (pair, relative angle, inliers):
| edge | relative rotation about | weight |
|---|---|---|
| 120 | ||
| 95 | ||
| 80 | ||
| 60 | ||
| (wrong, the truth is ) | 30 |
Kruskal takes and , skips because it closes the cycle , takes and skips . The tree is . The chained rotations from root 0 are , , and , which are the true ones, because the wrong edge is not in the tree. The cycle error of the triangle is . The cycle error of the triangle is , an angle of , which points at one of the edges , or . The reverse label of the edge is a rotation by and the translation . The reference code gives these numbers.
Correctness
The reverse label of line L2 is the inverse rigid motion, so both directions describe the same pair (theorem). Lines L3 to L7 return a maximum weight spanning forest by the cut property of spanning trees, the same argument as for the minimum spanning tree with the order reversed (theorem). The chained rotations satisfy every tree edge exactly, and if all edges are exact they equal the true rotations up to the gauge, (theorem). The cycle error is zero for exact edges (theorem), but a zero cycle error does not prove the edges right: two errors can cancel. The proof file below gives the details.
Proof: The view graph operations keep both edge directions consistent, find a maximum spanning forest and chain the rotations exactlyfull
We use the notation of the page. The label of the direction means for the coordinates and of one point in the frames of cameras and . The edge is exact if for the true absolute rotations.
Claim. (a) The label stored by line L2 is the inverse motion of the label stored by line L1. (b) Lines L3 to L7 return a spanning forest of largest total weight. (c) Lines L8 to L13 return rotations with for every tree edge in the component of the root, and if all tree edges are exact, . (d) Line L14 returns for a triangle of exact edges.
Proof of (a). From and we get . So the motion from frame to frame is , which is the label of line L2. The rotation is in and the weight is the same, so both directions describe the same pair.
Proof of (b). Lines L3 to L7 are Kruskal's method run on the edges in the order of decreasing weight. By the invariant of union-find, holds exactly when and are joined by edges already in , so an edge is added if and only if it closes no cycle with . Hence stays a forest, and at the end every edge of either is in or closes a cycle with , so spans each component of .
For optimality, we show by induction that after each step is contained in some maximum weight spanning forest . This holds at the start with empty. Let line L6 add the edge , and let before the step. If , we are done. Otherwise holds a cycle through , since and are in one component of and so of . Let be the vertex set of the tree of that holds . The cycle leaves through , so it leaves through a second edge with exactly one end in . The edge is not in , because no edge of leaves , and closes no cycle with , because its ends are in different trees of . So was not yet processed, and the order gives . Then is again a spanning forest, since removing breaks the cycle, and , so is a maximum weight spanning forest that contains . At the end, is a spanning forest contained in a maximum one with the same number of edges, so it is that forest.
Proof of (c). Breadth-first search from the root reaches every vertex of the component of the root in the tree, and line L12 sets once, when is first reached from its parent , as . Then . Each tree edge joins a vertex and its parent in the search, so this holds for every tree edge, in the direction from the parent; for the other direction it holds by (a), since . Now let all tree edges be exact. We show by induction on the depth of in the tree. For the root both sides are . For a vertex with parent , . The factor is the gauge: right multiplication of all rotations by one fixed rotation changes no .
Proof of (d). For exact edges, . The trace of is 3, and . The rotation angle of any rotation satisfies , so line L14 returns the angle of the loop rotation in , and it is only for the identity. The converse of (d) is false: a wrong edge in the triangle can be cancelled by an equal and opposite error in another edge of the same triangle.
Complexity
In the real RAM model, add-edge, relative and cycle-error cost , with a hash table for the adjacency. Components cost by breadth-first search. The spanning tree costs for the sort and for the union-find steps. The chained rotations cost , one product per tree edge. Checking all triangles costs with the standard triangle listing, which is fine for thousands of images but not for a dense graph of a million. The space is for the poses; the inlier matches of the edges usually take far more memory than the graph.
Variants
- Weights. The weight can be the inlier count, the ratio of inliers, the triangulation angle of the pair, or a score learned from the data. The maximum spanning tree trusts the weights, so the choice matters.
- Cycle filtering. Zach, Klopschitz and Pollefeys (2010) remove edges whose rotation cycles do not close, with a Bayesian test over many cycles. Many global pipelines remove edges whose triangle error is above a few degrees.
- Skeletal graph. Snavely, Seitz and Szeliski (2008) select a small subgraph of the images, a skeletal set, that keeps the reconstruction accurate, reconstruct it first and add the rest later.
- Pose graph. In SLAM, the edges carry full relative poses with a scale from odometry, and the graph is a pose graph.
- Triplet graph. Some global methods use a graph whose vertices are image triplets, so that the relative scales of the translations in a triplet are fixed.
- Building the graph. Matching all pairs is too slow for large sets, so the candidate pairs come from image retrieval with a vocabulary tree, from GPS tags, or from the order of a video.
When to use it
Use a view graph as soon as the input has more than a few images and no known order. It is the input of rotation and translation averaging in global SfM, and incremental SfM uses it to pick the first pair and to see which images can still be registered. For a short video, the graph is mostly a chain with some loop edges, and a pose graph with relative scales is often the better structure. For a few images that all see each other, a list of pairs is enough.
Pitfalls
- Direction conventions. Mixing with is the most common bug. Fix one convention, store both directions, and test the reverse label against the inverse pose.
- Repeated structures. Symmetric buildings and repeated windows give wrong edges with many inliers. These edges pass the geometric check, and a maximum spanning tree on inlier counts may trust them; cycle tests or specialized checks are needed.
- Unknown scale. The translation of an edge has no length. Chaining translations along a tree, as one chains rotations, is wrong; positions need translation averaging.
- Disconnected graphs. A graph with several components gives several reconstructions in unrelated frames. Reconstruct each component alone, or merge them only with extra data.
- Weak edges. An edge with a short baseline has a poor translation direction even if its rotation is good. Store the triangulation angle and use it when the directions are averaged.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/view-graph/. The authors are listed in prov/P4TY5D.jsonl.
"""A view graph: images as nodes, verified image pairs as edges.
The edge (i, j) stores the relative pose of camera j with respect to
camera i, in the convention X_j = R_ij X_i + t_ij (so R_ij = R_j R_i^T for
absolute rotations with X_c = R X_w + t), and a weight, usually the number
of inlier matches. The translation t_ij is known only up to a positive
scale. Each edge is stored in both directions: the reverse of (R, t) is
(R^T, -R^T t).
"""
import math
from collections import deque
from typing import Dict, List, Optional, Sequence, Tuple
Matrix = List[List[float]]
Vector = List[float]
EdgeData = Tuple[Matrix, Vector, float]
def _mul(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> Matrix:
return [[sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)] for i in range(3)]
def _tr(a: Sequence[Sequence[float]]) -> Matrix:
return [[a[j][i] for j in range(3)] for i in range(3)]
def rotation_angle(r: Sequence[Sequence[float]]) -> float:
"""The angle of a rotation matrix, arccos((tr R - 1) / 2)."""
c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
return math.acos(max(-1.0, min(1.0, c)))
class ViewGraph:
def __init__(self) -> None:
self.adj: Dict[int, Dict[int, EdgeData]] = {}
def add_view(self, i: int) -> None:
self.adj.setdefault(i, {})
def add_edge(self, i: int, j: int, r: Matrix, t: Vector, w: float = 1.0) -> None:
"""Store the pair (i, j) in both directions."""
if i == j:
raise ValueError("add_edge: a view graph has no loops")
self.add_view(i)
self.add_view(j)
self.adj[i][j] = ([list(row) for row in r], list(t), w) # @line L1
rt = _tr(r)
self.adj[j][i] = (rt, [-sum(rt[a][b] * t[b] for b in range(3)) for a in range(3)], w) # @line L2
def remove_edge(self, i: int, j: int) -> None:
del self.adj[i][j]
del self.adj[j][i]
def relative(self, i: int, j: int) -> Optional[EdgeData]:
return self.adj.get(i, {}).get(j)
def neighbors(self, i: int) -> List[int]:
return sorted(self.adj.get(i, {}))
def edges(self) -> List[Tuple[int, int, float]]:
"""Each edge once, as (i, j, w) with i < j."""
return sorted((i, j, d[2]) for i in self.adj for j, d in self.adj[i].items() if i < j)
def components(self) -> List[List[int]]:
"""The connected components, each sorted, by breadth-first search."""
seen, out = set(), []
for s in sorted(self.adj):
if s in seen:
continue
seen.add(s)
comp, queue = [], deque([s])
while queue:
i = queue.popleft()
comp.append(i)
for j in self.adj[i]:
if j not in seen:
seen.add(j)
queue.append(j)
out.append(sorted(comp))
return out
def maximum_spanning_tree(self) -> List[Tuple[int, int]]:
"""Kruskal's method on the weights, largest first. On a graph that is
not connected, the result is a spanning forest."""
parent = {i: i for i in self.adj} # @line L3
tree = []
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for i, j, _ in sorted(self.edges(), key=lambda e: (-e[2], e[0], e[1])): # @line L4
ri, rj = find(i), find(j)
if ri != rj: # @line L5
parent[ri] = rj # @line L6
tree.append((i, j))
return tree # @line L7
def chain_rotations(self, tree: Sequence[Tuple[int, int]], root: int) -> Dict[int, Matrix]:
"""Absolute rotations of the views reached from root along the tree,
with R_root = I and R_j = R_ij R_i."""
tadj: Dict[int, List[int]] = {}
for i, j in tree:
tadj.setdefault(i, []).append(j)
tadj.setdefault(j, []).append(i)
rots = {root: [[1.0 if a == b else 0.0 for b in range(3)] for a in range(3)]} # @line L8
queue = deque([root])
while queue: # @line L9
i = queue.popleft() # @line L10
for j in tadj.get(i, []): # @line L11
if j not in rots:
rots[j] = _mul(self.adj[i][j][0], rots[i]) # @line L12
queue.append(j)
return rots # @line L13
def cycle_error(self, i: int, j: int, k: int) -> float:
"""The angle of R_ki R_jk R_ij, zero for consistent rotations."""
r = _mul(self.adj[k][i][0], _mul(self.adj[j][k][0], self.adj[i][j][0]))
return rotation_angle(r) # @line L14
test_view_graph.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/view-graph/. The authors are listed in prov/P4TY5D.jsonl.
import itertools
import math
import random
from view_graph import ViewGraph, _mul, _tr, rotation_angle
def rot(axis, th):
n = math.sqrt(sum(a * a for a in axis))
x, y, z = (a / n for a in axis)
c, s, d = math.cos(th), math.sin(th), 1 - math.cos(th)
return [[c + x * x * d, x * y * d - z * s, x * z * d + y * s],
[y * x * d + z * s, c + y * y * d, y * z * d - x * s],
[z * x * d - y * s, z * y * d + x * s, c + z * z * d]]
def random_rot(rng):
return rot([rng.gauss(0, 1) for _ in range(3)], rng.uniform(0, math.pi))
def true_graph(seed, n=7, p=0.6):
"""Cameras with X_c = R X + t and the exact relative poses on random pairs."""
rng = random.Random(seed)
rs = [random_rot(rng) for _ in range(n)]
ts = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(n)]
g = ViewGraph()
for i in range(n):
g.add_view(i)
for i, j in itertools.combinations(range(n), 2):
if j == i + 1 or rng.random() < p:
rij = _mul(rs[j], _tr(rs[i]))
tij = [ts[j][a] - sum(rij[a][b] * ts[i][b] for b in range(3)) for a in range(3)]
g.add_edge(i, j, rij, tij, rng.randint(10, 500))
return rs, ts, g
def close(a, b, tol=1e-9):
return all(abs(x - y) < tol for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def test_reverse_edge_is_the_inverse_pose():
rs, ts, g = true_graph(1)
for i, j, _ in g.edges():
r, t, _ = g.relative(i, j)
rb, tb, _ = g.relative(j, i)
assert close(_mul(rb, r), [[1, 0, 0], [0, 1, 0], [0, 0, 1]])
# X_i = R_ji (R_ij X_i + t_ij) + t_ji, so R_ji t_ij + t_ji = 0
assert max(abs(sum(rb[a][b] * t[b] for b in range(3)) + tb[a]) for a in range(3)) < 1e-12
# the stored translation maps camera i to camera j
assert max(abs(ts[j][a] - sum(r[a][b] * ts[i][b] for b in range(3)) - t[a]) for a in range(3)) < 1e-12
def brute_force_max_tree_weight(nodes, edges):
best = None
for subset in itertools.combinations(edges, len(nodes) - 1):
parent = {v: v for v in nodes}
def find(x):
while parent[x] != x:
x = parent[x]
return x
ok = True
for i, j, _ in subset:
a, b = find(i), find(j)
if a == b:
ok = False
break
parent[a] = b
if ok:
w = sum(e[2] for e in subset)
best = w if best is None else max(best, w)
return best
def test_maximum_spanning_tree_matches_brute_force():
for seed in range(5):
_, _, g = true_graph(seed, n=6, p=0.5)
tree = g.maximum_spanning_tree()
assert len(tree) == 5
wt = sum(g.relative(i, j)[2] for i, j in tree)
assert wt == brute_force_max_tree_weight(list(range(6)), g.edges())
def test_chained_rotations_are_exact_up_to_the_gauge():
rs, _, g = true_graph(2, n=8)
tree = g.maximum_spanning_tree()
est = g.chain_rotations(tree, 3)
assert sorted(est) == list(range(8))
for i in range(8):
# est_i = R_i R_3^T for exact data
assert close(est[i], _mul(rs[i], _tr(rs[3])))
def test_cycle_error_finds_a_bad_edge():
rs, _, g = true_graph(3, n=5, p=1.0)
assert g.cycle_error(0, 1, 2) < 1e-7
r, t, w = g.relative(1, 2)
g.add_edge(1, 2, _mul(rot([0, 0, 1], 0.3), r), t, w)
assert abs(g.cycle_error(0, 1, 2) - 0.3) < 1e-9
assert abs(g.cycle_error(2, 1, 0) - 0.3) < 1e-9
assert g.cycle_error(0, 1, 3) < 1e-7
def test_components_after_edge_removal():
g = ViewGraph()
eye = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
for i, j in [(0, 1), (1, 2), (3, 4)]:
g.add_edge(i, j, eye, [1.0, 0.0, 0.0], 5)
g.add_view(5)
assert g.components() == [[0, 1, 2], [3, 4], [5]]
g.remove_edge(1, 2)
assert g.components() == [[0, 1], [2], [3, 4], [5]]
assert len(g.maximum_spanning_tree()) == 2
assert rotation_angle(eye) == 0.0
History
Govindu (2001) combined the relative motions of many image pairs on a graph of views and used the consistency of the motions around cycles. Levi and Werman (2003) defined the viewing graph, with fundamental matrices on the edges, and asked which graphs determine all the cameras. In large photo collections, Snavely, Seitz and Szeliski (2006, 2008) organized the images by their matches and used the image graph to find a skeletal set. Global methods since Martinec and Pajdla (2007) and the survey of Özyeşil, Voroninski, Basri and Singer (2017) state rotation and location estimation as problems on this graph, and incremental systems such as COLMAP (Schönberger and Frahm 2016) build a scene graph of the same kind.
References
- Venu Madhav Govindu, Combining two-view constraints for motion estimation, IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2001), vol. 2, 218-225, the whole paper (relative motions on the edges of a graph of views, and the consistency of the motions around cycles)
- Johannes L. Schönberger and Jan-Michael Frahm, Structure-from-motion revisited, IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2016), 4104-4113, the correspondence search and the scene graph (images as nodes, verified pairs as edges)
- Kyle Wilson and Noah Snavely, Robust global translations with 1DSfM, Computer Vision ECCV 2014, Lecture Notes in Computer Science, Springer, 2014, 61-75, the problem setup (the graph of pairwise translation directions) and the outlier filter on it
- Onur Özyeşil, Vladislav Voroninski, Ronen Basri and Amit Singer, A survey of structure from motion, Acta Numerica 26, 2017, 305-364, the sections on the viewing graph, rotation estimation and location estimation
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag P4TY5D Edit this page History Report an error Markdown