Algorithmresearch
ORB-SLAM
Also called ORB-SLAM2.
Keyframe visual SLAM with ORB features for tracking, local mapping and loop closing, with pose graph and bundle adjustment back ends.
- Time
- O(l + c f) loop_queryO(n^3) toy_essential_graph_stepO(f^3) toy_geometric_check
- Space
- O(n f) map
- Where
- c = the number of covisible neighbors of a keyframe; f = the number of features of one keyframe; l = the total length of the inverted lists of the words of one keyframe; n = the number of keyframes
- Model
- Real RAM
- Properties
- deterministicnot exactonlinetoy code
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Raúl Mur Artal, J. M. M. Montiel, Juan D. Tardós, 2015
ORB-SLAM is a keyframe-based visual SLAM system. It uses one kind of feature, ORB, for every task: tracking the camera, building the map, recognizing places and closing loops. Three threads run in parallel. Tracking estimates the pose of each frame from the map points that it sees, and decides when to make a new keyframe. Local mapping adds the keyframe to the map, creates new map points by triangulation, and runs a local bundle adjustment over the keyframe, its covisible neighbors and their points. Loop closing looks for a loop with a bag of words index each time a keyframe arrives. When it finds and verifies one, it fuses the duplicated map points and corrects the drift by pose graph optimization over a sparse subgraph, the essential graph. Two graphs carry the structure. In the covisibility graph, two keyframes are joined when they see enough of the same map points (at least 15 in the paper), and the weight is the number of shared points. The essential graph keeps only a spanning tree, the strong covisibility edges (at least 100 shared points), and the loop edges. ORB-SLAM was monocular. ORB-SLAM2 added stereo and RGB-D input and a full bundle adjustment after each loop closure; the alias on this page names that later system.
The code on this page is a toy. It has no images, no ORB features, no tracking and no bundle adjustment. It keeps only the core of the loop closing thread, in the plane, with simulated features.
In plain words
A camera moves through a building. The system remembers some of the views, the keyframes, and the 3D points that those views see. Two keyframes are friends when they see many of the same points. For each new keyframe, the system asks whether it looks like an old keyframe that is not one of its friends. To answer fast, it turns each view into a list of visual words and keeps, for each word, the list of keyframes that contain it. A match must hold for three new keyframes in a row and must pass a geometric check. Then the system knows that it has come back, joins the old and the new points, and pulls the whole chain of keyframes into place.
The problem
The input is a stream of camera frames with a calibrated camera. The output, after each frame, is the camera pose and a map of 3D points with their ORB descriptors, held in keyframes. The system must run in real time, keep the map small by adding and removing keyframes, recover when tracking is lost, and remove drift when the camera returns to a mapped place.
The toy works with planar poses . A keyframe gets the odometry from the previous keyframe and a list of features. A feature is a word (an integer that stands for a quantized ORB descriptor) and a 2D point in the frame of the keyframe (which stands for a triangulated map point).
The algorithm
The pseudocode is the toy. Lines L3 to L9 follow the loop closing thread of ORB-SLAM. Lines L1 and L2 stand in for tracking and local mapping.
PROCESS-KEYFRAME(odometry u, features F)- 1
K ← a new keyframe at pose(last keyframe) ⊕ u; match each feature to a point of the local map with the same word and a close position, else make a new map point - 2
update the covisibility weights of K; parent(K) ← the earlier keyframe that shares the most map points with K - 3
s_min ← the least score between the bag of words of K and those of its covisible neighbors - 4
C ← the keyframes from the inverted index with score ≥ s_min that share no map point with K - 5
for each J in C: group(J) ← {J} ∪ the neighbors of J; count(J) ← 1 + the largest count of an overlapping group of the last keyframe, or 1 - 6
for each J with count(J) ≥ 3, best score first: match the features of K and J by word, and fit a rigid transform to the matches - 7
if at least m matches are inliers then - 8
add the loop edge (J, K); fuse the matched map points of K into those of J - 9
optimize the essential graph (spanning tree, strong covisibility edges, loop edges) by Gauss-Newton; stop - 10
add K to the inverted index
The score (lines L3 and L4). The bag of words vector of a keyframe has tf-idf weights, divided by their sum. The score of DBoW2 is , which equals , so the inverted index can compute it from the shared words alone. The least score against the covisible neighbors adapts the threshold to the place: a keyframe that is not a neighbor must look at least as much like as the neighbors do. Keyframes that already share points with are not loops.
Consistency (line L5). A candidate, with its neighbors, forms a group. The candidate is accepted only when groups that overlap have been found for three keyframes in a row. One look-alike place seldom survives this.
The geometric check (lines L6 and L7). ORB-SLAM computes a similarity transform, Sim(3), between the two keyframes with RANSAC on the 3D matches, because a monocular map has an unknown scale that drifts. It then searches for more matches and refines the transform. The toy fits a 2D rigid transform: it tries every pair of matches as a sample, keeps the largest inlier set, and refits on it in closed form.
The correction (lines L8 and L9). The edges of the essential graph get the relative poses of the current estimates, so before the loop edge is added the graph has zero error. Only the loop edge pulls. The edges are taken before the fusion. The fusion creates links between keyframes on both sides of the loop, and their relative poses from the drifted estimates must not become edges. ORB-SLAM optimizes the essential graph in Sim(3) and then moves each map point with its reference keyframe. The toy uses SE(2), and a map point stores its position in the frame of its first keyframe, so it moves with that keyframe.
Example
The toy robot drives on a circle of radius 5 m, with 24 keyframes per lap and 32 keyframes in total. Sixty landmarks lie in two rings, at radii near 3 m and 7 m, and each one has one of 40 words. The robot sees the landmarks within 3 m, with noise 0.02 m. The odometry turns 0.015 rad too much at every keyframe, plus noise. The seed is 1. The system makes 88 map points, and each keyframe has 7 to 11 features. Loop detection starts at keyframe 10.
| keyframe | candidates (score) | counts of the groups | |
|---|---|---|---|
| 11 | 0.396 | 6 (0.435), 7 (0.480) | 1, 1 |
| 17 | 0.372 | 4 (0.376) | 1 |
| 18 | 0.427 | 4 (0.473) | 2 |
| 22 | 0.419 | 0 (0.648), 1 (0.465) | 1, 1 |
| 23 | 0.284 | 0 (0.788), 1 (0.597), 2 (0.346), 3 (0.311) | 2, 2, 2, 2 |
| 24 | 0.648 | 0 (1.000), 1 (0.778) | 3, 3 |
Keyframe 4 lies on the other side of the circle from keyframes 17 and 18. It is a look-alike place, and its group dies at keyframe 19 because no candidate there overlaps it. At keyframe 24 the robot is back at the start. Keyframe 0 has the same words and the score 1. The geometric check finds 7 inliers and the relative pose , against the true . Before the correction, the relative pose between keyframes 0 and 24 is wrong by 1.747 m and 0.345 rad. After it, the error is 0.019 m and 0.012 rad, and the largest position error over keyframes 0 to 24 falls from 1.762 m to 0.094 m. The keyframes after the loop drift again at the rate of the odometry.
On eight seeds the toy closed exactly one loop each time, between one of the keyframes 0 to 3 and one of the keyframes 23 to 27. The error of the loop relative pose after the correction was at most 0.02 m. The largest position error up to the loop keyframe fell from 1.39 to 1.98 m to 0.07 to 0.71 m. It stays large when the loop joins keyframe 3 instead of keyframe 0, because the drift of the first keyframes is not observed by the loop. These are measurements of a toy on simulated data.
Correctness
ORB-SLAM as a whole has no correctness proof. It is judged by measured accuracy on data sets such as KITTI, EuRoC and TUM RGB-D. The correctness proof covers the toy. It shows that the L1 score equals the sum of the smaller weights of the shared words, so the inverted index gives exact scores; that the closed form rigid fit is the least squares solution; that a candidate is accepted only after three consecutive overlapping groups; that the covisibility weights stay equal to the counts of shared map points through the fusion; and that the essential graph without loop edges has zero error, so only loop edges move the poses. The tests check the hand example of the score, the index against brute force, the rigid fit with outliers, a local minimum of the pose graph, the closing of the loop with the error before and after on three seeds, no loop on a run without a revisit, and the consistency rule.
Proof: The parts of the ORB-SLAM toy are exact where they claim to be, the consistency rule needs three keyframes in a row, and only loop edges move the posesfull
Setting. The toy of impl/python/orb_slam.py keeps keyframes with planar poses, map points, the covisibility weights , bag of words vectors, an inverted index, the groups of the last consistency check, and loop edges. A keyframe goes through lines L1 to L10 of the pseudocode. These claims are about the toy, not about the full ORB-SLAM system.
Assumptions. (A1) Exact arithmetic. (A2) Every bag of words vector has nonnegative entries with sum 1, or is empty. bow_vector makes them so.
Claim 1 (the score). For vectors as in (A2), . So , if and only if , and only words in both vectors add to the score.
Proof. For , . Summing over all words gives , which is the identity. Each term is nonnegative, and it is zero when one of the two entries is zero, so only shared words count. The sum is at most , with equality if and only if for every , that is entrywise, and since both sum to 1, .
Claim 2 (the inverted index). InvertedIndex.query(v) returns for every indexed keyframe that shares a word with , and returns no other keyframe.
Proof. The list of word holds for every indexed with . The query adds to the score of for each word of and each entry of its list. This adds exactly the nonzero terms of the sum in Claim 1. A keyframe that shares no word appears in no visited list.
Claim 3 (the rigid fit). For pairs that are not all equal in , fit_rigid returns a minimizer of over and .
Proof. For a fixed , the best is , with the means . With the centered points , the cost becomes . Here with and . This is largest at , which is what the code returns.
robust_rigid tries every pair of matches as a sample and keeps the largest inlier set, so it finds the largest set of matches that agrees, within the tolerance, with a pose fitted to some pair of its members. It then refits on that set by Claim 3.
Claim 4 (consistency). A candidate is accepted at keyframe only if there are candidates at the keyframes , processed one after the other with no loop closure between them, such that the groups and are not empty, where the covisible neighbors of .
Proof. By induction on , a group with the count at keyframe has a chain of groups at in which consecutive groups overlap. For the chain is the group itself. A group gets the count only from a group with the count in the list of the previous keyframe that it overlaps, and the list holds only the groups of the previous keyframe, because it is replaced at each keyframe. A loop closure empties the list. With the threshold 3, the claim follows.
Claim 5 (the covisibility weights). After each call of add_keyframe, is a map point of keyframe if and only if seen_by[p], and for every pair of keyframes that share a map point, is the number of map points that they share.
Proof. A new keyframe adds itself to seen_by of exactly its map points. The fusion moves from seen_by of the old point to seen_by of the new point in the same step in which it changes the observation. So the first statement holds. _connect(K) counts, for every point of , the other keyframes in its seen_by, which is the number of shared points with each of them. It removes the old entries of in the other keyframes and writes the new counts on both sides, so the weights stay symmetric. The only keyframe whose points change is the new keyframe or the fused keyframe, and _connect runs on it right after the change. Other pairs are not affected, because their point sets did not change.
Claim 6 (only loop edges move the poses). Every edge of the essential graph that is not a loop edge has, at the moment it is built, the measurement of the current poses. So with no loop edges, the current poses have cost 0, the error and the gradient are zero, and a Gauss-Newton step does not move them. With loop edges, the optimization starts from a point at which only the loop edges have an error.
Proof. _essential_edges sets the measurement of each tree edge and of each strong covisibility edge to between(poses[i], poses[j]). The error of such an edge is at the current poses. The gradient is a sum of zero vectors, so the step solves , and because is positive definite once pose 0 is fixed and the graph is connected. Loop edges carry the measurement of the geometric check and can have an error. The edges are built before the fusion, so the new links across the loop, which join drifted poses, are not edges with zero error that would hold the drift in place.
What this does not show. It does not show that a loop that is accepted is correct; the score, the consistency check and the geometric check reduce wrong loops but do not exclude them, and the tests only measure the result on simulated data. It does not show that Gauss-Newton converges to the global minimum of the essential graph cost. It does not cover anything of the full system that the toy leaves out: ORB features, tracking, local bundle adjustment, monocular scale drift and the Sim(3) fit, keyframe culling, or the final full bundle adjustment of ORB-SLAM2.
Complexity
Let be the number of keyframes, the number of features of a keyframe, the number of covisible neighbors and the total length of the inverted lists of the words of a keyframe.
- The loop query costs for the scores and for with sparse vectors.
- ORB-SLAM fits Sim(3) with RANSAC on a few candidates. The exhaustive two point search of the toy costs .
- The essential graph is sparse, with edges, and ORB-SLAM optimizes it with a sparse solver. The dense Gauss-Newton step of the toy costs .
- The map takes space. Keyframe culling in ORB-SLAM removes redundant keyframes, so grows with the explored area, not with the time.
Properties
- One feature for all tasks. ORB features are fast to compute and to match, and their binary descriptors feed the bag of words.
- Survival of the fittest. Keyframes and map points are added generously and culled when they are redundant.
- Monocular scale. With one camera, the scale is not observed and drifts. Sim(3) loop correction fixes the scale drift too.
- Relocalization. When tracking is lost, the same bag of words index finds candidate keyframes, and a perspective-n-point solution with RANSAC recovers the pose.
- Measured, not guaranteed. Accuracy and robustness are measured on data sets.
Variants and improvements
- ORB-SLAM2. Stereo and RGB-D cameras, which observe the scale; a full bundle adjustment in a separate thread after a loop closure; a localization only mode.
- ORB-SLAM3. Visual-inertial input, fisheye cameras, and a set of maps that can be merged when the robot returns to an old map.
- Other back ends. The essential graph can be replaced by an incremental smoother such as iSAM2, and the bag of words by learned place recognition.
- Robust loops. Switchable constraints or consistency checks guard against wrong loops that pass the checks.
When to use it
Use ORB-SLAM, or one of its successors, for real-time SLAM with a camera in scenes with enough texture, when loops are expected and a sparse map is enough. For dense maps, low texture or fast motion, other systems fit better, and with a lidar, a system such as LOAM is the usual choice. Use the toy only to study the loop closing logic.
Pitfalls
- Pure rotation and initialization. A monocular system needs parallax to start. ORB-SLAM chooses between a homography and a fundamental matrix model for the first two frames.
- Low texture and motion blur. Few features mean lost tracking. Relocalization helps only at mapped places.
- Perceptual aliasing. Repeated structures produce look-alike places. The consistency and geometric checks reduce wrong loops but cannot exclude them.
- Edges from the fusion. Covisibility links that the fusion makes across a loop must not enter the correction with their drifted relative poses. The toy builds the essential graph before the fusion for this reason.
- Scale drift. A monocular map corrected in SE(3) instead of Sim(3) keeps the scale error.
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/orb-slam/. The authors are listed in prov/TY0PRT.jsonl.
"""A toy of the keyframe and loop closing core of ORB-SLAM, in the plane.
This is a toy. There are no images. A keyframe is a planar pose (x, y,
theta) and a list of features; a feature is a visual word (an integer, the
stand-in for a quantized ORB descriptor) and a 2D point in the frame of the
keyframe (the stand-in for a triangulated map point). The odometry between
keyframes stands in for the tracking thread, and there is no local bundle
adjustment. What the toy keeps from ORB-SLAM (Mur-Artal, Montiel and Tardos
2015) is the structure of the loop closing thread:
- map points shared by keyframes, and the covisibility graph whose edge
weight is the number of shared map points,
- the spanning tree (each keyframe's parent shares the most points with it),
- bag of words vectors with tf-idf weights, the L1 score of DBoW2, and an
inverted index from words to keyframes,
- loop candidates: score at least the least score of the covisible
neighbors, and no shared map point,
- the consistency check over three consecutive keyframes,
- a geometric check (here a 2D rigid fit in place of the Sim(3) fit),
- map point fusion, and pose graph optimization on the essential graph
(spanning tree, strong covisibility edges, loop edges) by Gauss-Newton
in SE(2) in place of Sim(3).
"""
import math
# ------------------------------------------------------------- SE(2) helpers
def wrap(a):
return (a + math.pi) % (2.0 * math.pi) - math.pi
def compose(a, b):
c, s = math.cos(a[2]), math.sin(a[2])
return (a[0] + c * b[0] - s * b[1], a[1] + s * b[0] + c * b[1], wrap(a[2] + b[2]))
def inverse(a):
c, s = math.cos(a[2]), math.sin(a[2])
return (-c * a[0] - s * a[1], s * a[0] - c * a[1], -a[2])
def between(a, b):
"""The pose of b in the frame of a."""
return compose(inverse(a), b)
def transform(pose, p):
c, s = math.cos(pose[2]), math.sin(pose[2])
return (pose[0] + c * p[0] - s * p[1], pose[1] + s * p[0] + c * p[1])
# ------------------------------------------------------------- bag of words
def bow_vector(words, idf):
"""tf-idf weights of a list of words, divided by their sum (L1 norm 1)."""
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
total = len(words)
vec = {w: n / total * idf.get(w, 0.0) for w, n in counts.items()}
vec = {w: x for w, x in vec.items() if x > 0.0}
norm = sum(vec.values())
return {w: x / norm for w, x in vec.items()} if norm > 0.0 else {}
def l1_score(u, v):
"""The DBoW2 score 1 - |u - v|_1 / 2 of two vectors with L1 norm 1."""
keys = set(u) | set(v)
return 1.0 - 0.5 * sum(abs(u.get(w, 0.0) - v.get(w, 0.0)) for w in keys)
class InvertedIndex:
"""Word -> list of (keyframe, weight). A query visits only shared words.
For nonnegative vectors with L1 norm 1, 1 - |u - v|_1 / 2 equals the sum
of min(u_w, v_w) over the shared words, so the index gives the exact score.
"""
def __init__(self):
self.lists = {}
def add(self, k, vec):
for w, x in vec.items():
self.lists.setdefault(w, []).append((k, x))
def query(self, vec):
scores = {}
for w, x in vec.items():
for k, y in self.lists.get(w, ()):
scores[k] = scores.get(k, 0.0) + min(x, y)
return scores
# ------------------------------------------------------------- geometric check
def fit_rigid(pairs):
"""Least squares (R, t) with q = R p + t for pairs (p, q), as a pose."""
n = len(pairs)
px = sum(p[0] for p, _ in pairs) / n
py = sum(p[1] for p, _ in pairs) / n
qx = sum(q[0] for _, q in pairs) / n
qy = sum(q[1] for _, q in pairs) / n
sxx = sum((p[0] - px) * (q[0] - qx) + (p[1] - py) * (q[1] - qy) for p, q in pairs)
sxy = sum((p[0] - px) * (q[1] - qy) - (p[1] - py) * (q[0] - qx) for p, q in pairs)
th = math.atan2(sxy, sxx)
c, s = math.cos(th), math.sin(th)
return (qx - (c * px - s * py), qy - (s * px + c * py), th)
def inliers_of(pose, pairs, tol):
out = []
for idx, (p, q) in enumerate(pairs):
r = transform(pose, p)
if math.hypot(r[0] - q[0], r[1] - q[1]) < tol:
out.append(idx)
return out
def robust_rigid(pairs, tol):
"""Try every pair of matches as a minimal sample; refit on the best inlier set."""
best = []
for a in range(len(pairs)):
for b in range(a + 1, len(pairs)):
pa, pb = pairs[a][0], pairs[b][0]
if math.hypot(pa[0] - pb[0], pa[1] - pb[1]) < 1e-6:
continue
ins = inliers_of(fit_rigid([pairs[a], pairs[b]]), pairs, tol)
if len(ins) > len(best):
best = ins
if len(best) < 2:
return None, []
pose = fit_rigid([pairs[i] for i in best])
return pose, inliers_of(pose, pairs, tol)
# ------------------------------------------------------------- pose graph
def edge_error_and_jacobians(xi, xj, z):
"""Error of the edge (i, j) with measurement z, and its Jacobians."""
ci, si = math.cos(xi[2]), math.sin(xi[2])
cz, sz = math.cos(z[2]), math.sin(z[2])
dx, dy = xj[0] - xi[0], xj[1] - xi[1]
# R_i^T (t_j - t_i)
lx, ly = ci * dx + si * dy, -si * dx + ci * dy
ex, ey = lx - z[0], ly - z[1]
e = [cz * ex + sz * ey, -sz * ex + cz * ey, wrap(xj[2] - xi[2] - z[2])]
# derivatives of (lx, ly) with respect to x_i
dl = [[-ci, -si, -si * dx + ci * dy], [si, -ci, -ci * dx - si * dy]]
a = [[cz * dl[0][k] + sz * dl[1][k] for k in range(3)], [-sz * dl[0][k] + cz * dl[1][k] for k in range(3)], [0.0, 0.0, -1.0]]
rb = [[ci, si], [-si, ci]]
b = [[cz * rb[0][0] + sz * rb[1][0], cz * rb[0][1] + sz * rb[1][1], 0.0], [-sz * rb[0][0] + cz * rb[1][0], -sz * rb[0][1] + cz * rb[1][1], 0.0], [0.0, 0.0, 1.0]]
return e, a, b
def solve_spd(h, g):
"""Solve h x = g for a symmetric positive definite h by Cholesky."""
n = len(h)
lo = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1):
s = h[i][j] - sum(lo[i][k] * lo[j][k] for k in range(j))
if i == j:
if s <= 0.0:
raise ValueError("the system is not positive definite")
lo[i][i] = math.sqrt(s)
else:
lo[i][j] = s / lo[j][j]
y = [0.0] * n
for i in range(n):
y[i] = (g[i] - sum(lo[i][k] * y[k] for k in range(i))) / lo[i][i]
x = [0.0] * n
for i in reversed(range(n)):
x[i] = (y[i] - sum(lo[k][i] * x[k] for k in range(i + 1, n))) / lo[i][i]
return x
def graph_cost(poses, edges):
total = 0.0
for i, j, z in edges:
e, _, _ = edge_error_and_jacobians(poses[i], poses[j], z)
total += sum(x * x for x in e)
return total
def optimize_pose_graph(poses, edges, iterations=10):
"""Gauss-Newton on SE(2) with unit information and pose 0 fixed."""
poses = list(poses)
n = len(poses) - 1
for _ in range(iterations):
h = [[0.0] * (3 * n) for _ in range(3 * n)]
g = [0.0] * (3 * n)
for i, j, z in edges:
e, a, b = edge_error_and_jacobians(poses[i], poses[j], z)
blocks = [(i, a), (j, b)]
for u, ju in blocks:
if u == 0:
continue
for r in range(3):
g[3 * (u - 1) + r] -= sum(ju[k][r] * e[k] for k in range(3))
for v, jv in blocks:
if v == 0:
continue
for r in range(3):
for c in range(3):
h[3 * (u - 1) + r][3 * (v - 1) + c] += sum(ju[k][r] * jv[k][c] for k in range(3))
dx = solve_spd(h, g)
for k in range(n):
p = poses[k + 1]
poses[k + 1] = (p[0] + dx[3 * k], p[1] + dx[3 * k + 1], wrap(p[2] + dx[3 * k + 2]))
if max(abs(x) for x in dx) < 1e-10:
break
return poses
# ------------------------------------------------------------- the toy system
class ToyOrbSlam:
def __init__(self, idf, covis_min=3, strong_min=8, window=4, match_radius=0.5, consistency=3, min_inliers=6, inlier_tol=0.15, skip=10):
self.idf = idf
self.covis_min = covis_min
self.strong_min = strong_min
self.window = window
self.match_radius = match_radius
self.consistency = consistency
self.min_inliers = min_inliers
self.inlier_tol = inlier_tol
self.skip = skip
self.poses = [] # keyframe poses
self.obs = [] # keyframe -> list of [word, local point, map point]
self.bow = []
self.points = [] # map point -> (reference keyframe, local point, word)
self.seen_by = [] # map point -> set of keyframes
self.weights = [] # keyframe -> {keyframe: number of shared map points}
self.parent = []
self.index = InvertedIndex()
self.groups = [] # (set of keyframes, consistency count) of the last keyframe
self.loops = [] # (j, k, measured pose of k in the frame of j)
self.last_loop = 0
self.events = []
# map points and covisibility
def point_world(self, p):
ref, local, _ = self.points[p]
return transform(self.poses[ref], local)
def neighbors(self, k):
return {j for j, w in self.weights[k].items() if w >= self.covis_min}
def _connect(self, k):
counts = {}
for _, _, p in self.obs[k]:
for j in self.seen_by[p]:
if j != k:
counts[j] = counts.get(j, 0) + 1
for j in self.weights[k]:
self.weights[j].pop(k, None)
self.weights[k] = counts
for j, w in counts.items():
self.weights[j][k] = w
return counts
def _new_keyframe(self, motion, features):
k = len(self.poses)
pose = compose(self.poses[-1], motion) if k else motion
self.poses.append(pose)
local = set()
for j in range(max(0, k - self.window), k):
local.update(p for _, _, p in self.obs[j])
obs = []
used = set()
for word, pt in features:
w = transform(pose, pt)
best, best_d = None, self.match_radius
for p in local:
if p in used or self.points[p][2] != word:
continue
q = self.point_world(p)
d = math.hypot(q[0] - w[0], q[1] - w[1])
if d < best_d:
best, best_d = p, d
if best is None:
best = len(self.points)
self.points.append((k, pt, word))
self.seen_by.append(set())
used.add(best)
self.seen_by[best].add(k)
obs.append([word, pt, best])
self.obs.append(obs)
self.bow.append(bow_vector([w for w, _, _ in obs], self.idf))
self.weights.append({})
return k
# loop closing
def _candidates(self, k):
nbrs = self.neighbors(k)
if not nbrs or k < self.last_loop + self.skip:
return [], {}
s_min = min(l1_score(self.bow[k], self.bow[j]) for j in nbrs) # @line L3
scores = self.index.query(self.bow[k])
connected = set(self.weights[k])
cands = [j for j, s in scores.items() if s >= s_min - 1e-12 and j not in connected and j != k] # @line L4
return cands, scores
def _consistent(self, cands):
new_groups = []
accepted = []
for j in cands:
group = {j} | self.neighbors(j)
count = 1
for g, n in self.groups:
if g & group:
count = max(count, n + 1)
new_groups.append((group, count)) # @line L5
if count >= self.consistency:
accepted.append(j)
self.groups = new_groups
return accepted
def _match(self, k, j):
def unique(obs):
seen = {}
for idx, (w, _, _) in enumerate(obs):
seen.setdefault(w, []).append(idx)
return {w: v[0] for w, v in seen.items() if len(v) == 1}
uk, uj = unique(self.obs[k]), unique(self.obs[j])
return [(uk[w], uj[w]) for w in uk if w in uj]
def _essential_edges(self):
edges = []
seen = set()
for k in range(1, len(self.poses)):
p = self.parent[k]
edges.append((p, k, between(self.poses[p], self.poses[k])))
seen.add((min(p, k), max(p, k)))
for k in range(len(self.poses)):
for j, w in self.weights[k].items():
if j < k and w >= self.strong_min and (j, k) not in seen:
edges.append((j, k, between(self.poses[j], self.poses[k])))
seen.add((j, k))
edges.extend(self.loops)
return edges
def _close_loop(self, k, j, rel, pairs):
self.loops.append((j, k, rel))
# The essential graph is taken before the fusion. The links that the
# fusion creates join keyframes across the loop, and their relative
# poses from the drifted estimates must not become constraints.
edges = self._essential_edges()
for a, b in pairs:
old, new = self.obs[k][a][2], self.obs[j][b][2]
if old != new:
self.seen_by[old].discard(k)
self.seen_by[new].add(k)
self.obs[k][a][2] = new
self._connect(k)
self.poses = optimize_pose_graph(self.poses, edges) # @line L9
self.last_loop = k
self.groups = []
def add_keyframe(self, motion, features):
"""Insert a keyframe and run loop closing. Return (j, k) for a closed loop, else None."""
k = self._new_keyframe(motion, features) # @line L1
counts = self._connect(k)
earlier = {j: w for j, w in counts.items() if j < k}
self.parent.append(max(earlier, key=lambda j: (earlier[j], -j)) if earlier else max(k - 1, 0)) # @line L2
cands, scores = self._candidates(k)
accepted = self._consistent(cands)
result = None
for j in sorted(accepted, key=lambda c: -scores[c]):
matches = self._match(k, j) # @line L6
pairs = [(self.obs[k][a][1], self.obs[j][b][1]) for a, b in matches]
if len(pairs) < self.min_inliers:
continue
rel, ins = robust_rigid(pairs, self.inlier_tol)
if rel is not None and len(ins) >= self.min_inliers: # @line L7
self._close_loop(k, j, rel, [matches[i] for i in ins]) # @line L8
self.events.append(("loop", j, k, len(ins)))
result = (j, k)
break
self.events.append(("rejected", j, k, len(ins)))
self.index.add(k, self.bow[k]) # @line L10
return result
test_orb_slam.py 176 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/orb-slam/. The authors are listed in prov/TY0PRT.jsonl.
import math
import random
from orb_slam import (
InvertedIndex,
ToyOrbSlam,
between,
bow_vector,
compose,
fit_rigid,
graph_cost,
inverse,
l1_score,
optimize_pose_graph,
robust_rigid,
transform,
wrap,
)
def simulate(seed, keyframes=32, per_lap=24, radius=5.0, vocabulary=40, bias=0.015):
"""A robot on a circle among two rings of landmarks, with biased odometry."""
rng = random.Random(seed)
marks = []
for ring in (3.0, 7.0):
for _ in range(30):
a = rng.uniform(-math.pi, math.pi)
r = ring + rng.uniform(-0.3, 0.3)
marks.append((r * math.cos(a), r * math.sin(a), rng.randrange(vocabulary)))
counts = {}
for _, _, w in marks:
counts[w] = counts.get(w, 0) + 1
idf = {w: math.log(len(marks) / n) for w, n in counts.items()}
step = 2.0 * math.pi / per_lap
truth = []
for k in range(keyframes):
a = -math.pi / 2 + k * step
truth.append((radius * math.cos(a), radius * math.sin(a) + radius, wrap(a + math.pi / 2)))
shift = (0.0, radius, 0.0)
marks = [(x + shift[0], y + shift[1], w) for x, y, w in marks]
frames = []
for k, pose in enumerate(truth):
if k == 0:
motion = pose
else:
m = between(truth[k - 1], pose)
motion = (m[0] + rng.gauss(0, 0.01), m[1] + rng.gauss(0, 0.01), m[2] + bias + rng.gauss(0, 0.005))
feats = []
for x, y, w in marks:
p = transform(inverse(pose), (x, y))
if math.hypot(p[0], p[1]) < 3.0:
feats.append((w, (p[0] + rng.gauss(0, 0.02), p[1] + rng.gauss(0, 0.02))))
frames.append((motion, feats))
return truth, frames, idf
def run(seed, **kw):
truth, frames, idf = simulate(seed, **kw)
slam = ToyOrbSlam(idf)
before = None
loops = []
for k, (motion, feats) in enumerate(frames):
snapshot = list(slam.poses)
out = slam.add_keyframe(motion, feats)
if out is not None:
loops.append(out)
if before is None:
before = snapshot + [compose(snapshot[-1], motion)]
return truth, slam, loops, before
def max_error(poses, truth):
return max(math.hypot(p[0] - t[0], p[1] - t[1]) for p, t in zip(poses, truth))
def test_score_and_inverted_index_match_the_hand_example():
idf = {1: 0.0, 2: math.log(2), 3: 2 * math.log(2), 4: 2 * math.log(2)}
q = bow_vector([1, 1, 2, 3], idf)
b = bow_vector([1, 2, 3, 4], idf)
c = bow_vector([1, 1, 1, 4], idf)
assert abs(l1_score(q, b) - 0.6) < 1e-12
assert abs(l1_score(q, c)) < 1e-12
index = InvertedIndex()
index.add("b", b)
index.add("c", c)
got = index.query(q)
assert abs(got["b"] - 0.6) < 1e-12 and "c" not in got
def test_inverted_index_equals_brute_force():
rng = random.Random(3)
idf = {w: rng.uniform(0.1, 2.0) for w in range(30)}
vecs = [bow_vector([rng.randrange(30) for _ in range(12)], idf) for _ in range(25)]
index = InvertedIndex()
for k, v in enumerate(vecs):
index.add(k, v)
for v in vecs[:5]:
got = index.query(v)
for k, u in enumerate(vecs):
assert abs(got.get(k, 0.0) - l1_score(v, u)) < 1e-12
def test_rigid_fit_recovers_a_pose_with_outliers():
rng = random.Random(5)
pose = (0.7, -1.2, 0.9)
pairs = []
for _ in range(10):
p = (rng.uniform(-3, 3), rng.uniform(-3, 3))
pairs.append((p, transform(pose, p)))
assert all(abs(a - b) < 1e-12 for a, b in zip(fit_rigid(pairs), pose))
for _ in range(3):
pairs.append(((rng.uniform(-3, 3), rng.uniform(-3, 3)), (rng.uniform(-3, 3), rng.uniform(-3, 3))))
got, ins = robust_rigid(pairs, 0.05)
assert sorted(ins) == list(range(10))
assert all(abs(a - b) < 1e-9 for a, b in zip(got, pose))
def test_pose_graph_optimization_reaches_a_local_minimum():
# a square of four odometry steps that turn a little too much, and a loop
# edge that says that the end is the start
poses = [(0.0, 0.0, 0.0)]
for _ in range(4):
poses.append(compose(poses[-1], (1.0, 0.0, math.pi / 2 + 0.05)))
edges = [(k, k + 1, between(poses[k], poses[k + 1])) for k in range(4)]
edges.append((0, 4, (0.0, 0.0, 0.0)))
start = graph_cost(poses, edges)
out = optimize_pose_graph(poses, edges)
best = graph_cost(out, edges)
assert out[0] == (0.0, 0.0, 0.0)
# the turn error of 0.2 rad is spread over five edges: about 5 * 0.04^2 = 0.008
assert abs(best - 0.008) < 2e-4 and start > 0.05
rng = random.Random(9)
for _ in range(50):
moved = [out[0]] + [(p[0] + rng.gauss(0, 1e-3), p[1] + rng.gauss(0, 1e-3), p[2] + rng.gauss(0, 1e-3)) for p in out[1:]]
assert graph_cost(moved, edges) >= best - 1e-12
def relative_error(poses, truth, j, k):
a, b = between(poses[j], poses[k]), between(truth[j], truth[k])
return math.hypot(a[0] - b[0], a[1] - b[1]), abs(wrap(a[2] - b[2]))
def test_the_toy_closes_the_loop_once_and_removes_the_drift():
for seed in (1, 2, 3):
truth, slam, loops, before = run(seed)
assert len(loops) == 1
j, k = loops[0]
# the loop links the second lap to the start of the first lap
assert j < 6 and 24 <= k < 30
dist, ang = relative_error(before, truth, j, k)
assert dist > 1.0 and ang > 0.2
dist, ang = relative_error(slam.poses, truth, j, k)
assert dist < 0.05 and ang < 0.05
assert max_error(slam.poses[: k + 1], truth) < 0.5 * max_error(before[: k + 1], truth)
# map points were fused: the loop keyframe now shares points with the old one
assert slam.weights[k].get(j, 0) >= slam.min_inliers
def test_no_loop_without_a_revisit():
truth, slam, loops, _ = run(4, keyframes=22)
assert loops == []
def test_consistency_needs_three_keyframes():
slam = ToyOrbSlam({})
slam.neighbors = lambda j: {j + 1}
assert slam._consistent([5]) == []
assert slam._consistent([6]) == []
assert slam._consistent([7]) == [7]
slam.groups = []
assert slam._consistent([5]) == []
assert slam._consistent([20]) == []
assert slam._consistent([6]) == []
History
PTAM of Klein and Murray (2007) split tracking and mapping into two threads and used keyframes with bundle adjustment. Strasdat and colleagues showed the value of covisibility-based local windows and of Sim(3) pose graph optimization for monocular scale drift. Gálvez-López and Tardós (2012) gave the fast bag of binary words. Mur-Artal, Montiel and Tardós (2015) joined these ideas into ORB-SLAM, with one feature for all tasks and the essential graph for loop correction. Mur-Artal and Tardós (2017) extended it to stereo and RGB-D as ORB-SLAM2, and Campos and colleagues released ORB-SLAM3 in 2021.
References
- Raúl Mur-Artal, J. M. M. Montiel and Juan D. Tardós, ORB-SLAM: a versatile and accurate monocular SLAM system, IEEE Transactions on Robotics 31(5), 2015, pages 1147 to 1163, the three threads, the covisibility graph and the essential graph, the place recognition with DBoW2, the loop candidates and their consistency check, the Sim(3) fit, the loop fusion and the essential graph optimization
- Raúl Mur-Artal and Juan D. Tardós, ORB-SLAM2: an open-source SLAM system for monocular, stereo, and RGB-D cameras, IEEE Transactions on Robotics 33(5), 2017, the extension to stereo and RGB-D input and the full bundle adjustment after a loop closure
- Dorian Gálvez-López and Juan D. Tardós, Bags of binary words for fast place recognition in image sequences, IEEE Transactions on Robotics 28(5), 2012, pages 1188 to 1197, the bag of binary words, the L1 score and the inverted index that ORB-SLAM uses for place recognition
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 | W2 basic |
|
Tag TY0PRT Edit this page History Report an error Markdown