Algorithmcore
ORB features
Also called oriented FAST and rotated BRIEF.
FAST keypoints with an orientation from the intensity centroid and a BRIEF descriptor steered by that orientation, with test pairs learned for low correlation.
- Solves
- Feature matching
- Time
- O(W H log(W H) + n m) worst · averageO(W H + n m) best
- Space
- O(W H + n m) extra
- Where
- H = the image height in pixels; W = the image width in pixels; m = the number of binary tests; n = the number of keypoints
- Model
- Word RAM
- Properties
- deterministicnot exactheuristicrotation invariantnot scale invariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ethan Rublee, Vincent Rabaud, Kurt Konolige, Gary Bradski, 2011
ORB (oriented FAST and rotated BRIEF) finds corners with the FAST segment test and describes them with a BRIEF string of 256 binary tests. It adds what both lack: FAST gives no orientation, so ORB takes the direction from the corner to the centroid of the intensities in a disk around it; BRIEF is not invariant to rotation, so ORB turns the test pattern by that direction. It also learns a set of tests that have a mean near one half and a low correlation, which keeps the descriptor distinctive after the turning. Descriptors are compared by the Hamming distance, and the whole method runs more than ten times faster than SURF. ORB is the feature of ORB-SLAM and of much real-time work.
In plain words
First find corners: points where a ring of 16 pixels around the point has 9 pixels in a row that are all much brighter, or all much darker, than the point. Keep the corners with the strongest corner score. For each corner, look at a round patch around it and find where its brightness is centered. The arrow from the corner to that center gives a direction that turns with the image. Then compare the brightness of 256 pairs of small squares in the patch, laid out in a fixed pattern that is turned to the direction of the arrow. Each comparison gives one bit. Two corners match when their 256 bits mostly agree, which a computer counts very fast.
The problem
The input is a gray image with columns and rows; a pixel is , with the column and the row, and angles grow from the axis toward the axis. The output is a set of keypoints with an orientation , each with a binary string of bits. As for every local feature, the same scene point in two views should give keypoints with near descriptors, here near in the Hamming distance, for feature matching.
oFAST. FAST-9 finds the corners: on the circle of 16 pixels at radius 3, at least 9 contiguous pixels are brighter than , or at least 9 are darker than . FAST answers strongly along edges, so ORB ranks the corners by the Harris measure and keeps the best . For scale, it runs on each level of a pyramid with the factor ; the paper uses 5 levels.
Intensity centroid. Rosin defines the moments of a patch as , with relative to the corner. The centroid is , and the orientation is
ORB sums over a disk of radius , not a square, so that the region does not change when it is turned.
Steered BRIEF. A test compares two points and of the patch, , where is the sum of a window, so that one pixel of noise has less effect. The patch is pixels. For the orientation the test points are turned by . ORB rounds to a multiple of , 12 degrees, and keeps a table of the turned patterns, so that no rotation is computed at run time.
The algorithm
ORB(I, N, t) ▷ pattern tables T_0, ..., T_29 built once- 1
C ← FAST-9 corners of I with threshold t (on each pyramid level) - 2
keep the corners that are local maxima of the Harris measure, then the N with the largest measure - 3
for each keypoint k: m_10, m_01 ← Σ x I, Σ y I over the disk of radius 15; θ ← atan2(m_01, m_10) - 4
b ← round(θ / (2π/30)) mod 30 - 5
for each test i with the turned points (p_i, q_i) in T_b do - 6
bit i of the descriptor ← [S(k + p_i) < S(k + q_i)] - 7
return the keypoints with θ and their descriptors
Learning the tests (rBRIEF). Turning makes the tests less useful: for BRIEF on upright patches each test has a mean near , but once the patches are turned to their orientation, many tests have means far from and are correlated. ORB therefore picks its tests by a greedy search. The paper enumerates the tests between windows of the patch, removes the tests whose windows overlap, and keeps candidates. It runs them on about 300000 keypoints from the PASCAL 2006 images.
- Run each test on all training patches, turned to their orientation, and order the tests by the distance of their mean from .
- Put the first test in the result.
- Take the next test, and add it to the result if the absolute correlation with every test in the result is below a threshold. Repeat until there are 256 tests.
- If the candidates run out first, raise the threshold and start again.
The code has the same search in learn_tests. Its default pattern is random, because the learned pattern needs the training set; OpenCV ships the learned pattern as a fixed table.
Example
Orientation. Take the disk of radius 1, five pixels around a corner : , the right neighbor 20, the left neighbor 0, the neighbor above 10 and the neighbor below 30. Then and , so , toward the lower right where the patch is bright. With bins of 12 degrees, rounds to bin 4, which is 48 degrees.
A turned test. The test point turned by 48 degrees is , which rounds to . So in bin 4 the test reads the window centered 3 pixels to the right of and 4 pixels below the corner.
Rotation by 90 degrees. With 32 bins instead of 30, a quarter turn is exactly 8 bins. The code builds the bins 8 to 31 as exact quarter turns of the bins 0 to 7. If an image is turned by 90 degrees, the centroid turns with it, so grows by , and the descriptors of a keypoint and its turned copy are equal bit for bit. The tests check this on a image: all keypoints are found again, all at Hamming distance 0, while the same tests without steering differ in more than 40 of the 256 bits on average.
Correctness
ORB is a heuristic; its matching quality is a benchmark result. The proof in proofs/correctness.md shows that:
- The segment test of the code is the FAST-9 test: it finds a run of 9 in the circle of 16 pixels, including runs that wrap around.
- The centroid angle turns with the image: for a turn by about a pixel, grows by exactly . Adding a constant to the image does not change , since over a disk.
- When the number of bins is a multiple of 4 and the turned image keeps the bins, the descriptor of the turned image is the same.
- The greedy search ends, and every two chosen tests have an absolute correlation below the final threshold on the training set.
Proof: Correctness of ORBfull
Pixels are with the column and the row. The turn by is ; it maps the angle of a vector to . For an image of size , the turned image is , so the pixel of is the pixel of , and the offset from a pixel becomes the offset .
Lemma 1 (segment test). Let be the states of the circle pixels in order, each brighter, darker or similar. The code returns true if and only if there are 9 cyclically contiguous indices with the same state, brighter or darker.
Proof. The code scans the sequence and counts the length of the current run of the wanted state. A cyclic run of 9 starting at appears in the doubled sequence at the positions , so the count reaches 9. Conversely, a run of 9 in the doubled sequence covers 9 consecutive positions, which are 9 cyclically consecutive indices since .
Lemma 2 (centroid angle). Let be the centroid angle of at over the disk of radius , and that of at the turned point . If , then . Adding a constant to does not change , and multiplying by does not change it either.
Proof. is symmetric under . The pixel of has the value . So , whose angle is . For the offset, since is symmetric under , so adds 0 to both moments. A factor multiplies both moments and does not change . The moments are sums of integers, so all of this holds exactly in the code; the angles agree up to the rounding of .
Lemma 3 (turned tables). If the number of bins is a multiple of 4, the tables satisfy for all , indices modulo , where acts on both points of each test.
Proof. For the code defines , which is the claim for . For , , and applying the definition three times gives , so , since is the identity.
Lemma 4 (descriptor under a quarter turn). Let be a keypoint of and the turned point in , both at least 17 pixels from the border, and let and be their bins. If and is a multiple of 4, the descriptors are equal.
Proof. The window centered at in holds the same pixels as the window centered at in , since the window is symmetric under . So for every point of a test. By Lemma 3 the test of is when is the test of . So each bit of the descriptor of compares the same two sums as the bit of .
By Lemma 2 the turned angle is , so the bins shift by exactly unless the rounding of moves an angle that lies on a bin border; the tests check that the shift holds for the keypoints used.
Lemma 5 (greedy search). learn_tests ends. Every two tests it returns have an absolute correlation on the training patches below the returned threshold, and it returns tests unless the threshold has reached 1.
Proof. Each round runs over a finite list. A round ends with tests, or raises the threshold by a fixed step; after finitely many rounds the threshold is at least 1, and the search returns. In a round, a test enters the result only if its absolute correlation with each test already in the result is below the threshold of the round, so every pair in the result satisfies the bound. The returned threshold is that of the last round.
When the threshold is above 1, every correlation is below it, so the last round takes the first tests of the order; if there are fewer than candidates, the result is shorter.
Theorem. ORB returns the FAST-9 corners that are local maxima of the Harris measure, the best by that measure, each with its centroid angle and the descriptor of the definition. With a multiple of 4, turning the image by about its center turns the angles by and keeps the descriptors whenever the bins shift by . Adding a constant to the image does not change the output.
Proof. Line L1 is the segment test by Lemma 1, and line L2 keeps and sorts as defined. Line L3 computes the angle, line L4 the bin, and lines L5 and L6 the bits with the table of the bin. Lemmas 2 and 4 give the claim on the turned image. For the offset: the segment test compares differences of pixels, the Harris measure uses differences, the angle does not change by Lemma 2, and each test compares two sums of 25 pixels, which both grow by . So every step gives the same result.
Complexity
The model is the word RAM: pixel values, sums and descriptors of 64-bit words.
- Line L1 tests each pixel in time, in total.
- Line L2 computes the Harris measure in time per corner and sorts the corners, in the worst case; a selection of the best is .
- Line L3 takes time per keypoint, a constant for .
- Lines L5 and L6 take time per test with an integral image, so for all keypoints.
The total time is , and the space is for the image and the integral image and bits for the descriptors. A Hamming distance costs XOR and popcount operations. Rublee and his coauthors report 15.3 ms per image of pixels for ORB, against 217.3 ms for SURF and 5228.7 ms for SIFT, on one test computer.
Properties
- Rotation invariant. The pattern follows , up to the rounding of to 12 degrees and of the points to pixels.
- Partly scale invariant. The pyramid gives keypoints at several scales, but the patch has the same size in pixels at each level, and there is no scale selection as in SIFT.
- Contrast invariant. The tests compare two sums of equal size, so they do not change when a constant is added or the image is multiplied by a positive number. The centroid angle does not change either.
- Binary. 256 bits are 32 bytes, against 64 floats for SURF and 128 for SIFT, and the Hamming distance is a few machine instructions.
- Free. ORB is not patented, which was one reason for its design.
Variants and improvements
- Matching. The paper matches with multi-probe LSH, which suits binary strings; brute force with the Hamming distance is often fast enough.
- OpenCV ORB. It smooths the image with a Gaussian and compares single pixels instead of window sums, scores the corners by Harris or by the FAST score, and spreads the keypoints over the levels of the pyramid.
- ORB-SLAM. It spreads the keypoints over a grid of cells so that they cover the whole image, which matters for tracking.
- BRISK and FREAK. BRISK uses a fixed pattern of points on rings and takes the orientation from long pairs; FREAK uses a retina-like pattern.
When to use it
Use ORB when speed or the absence of patents matters: on phones and robots, in visual SLAM and visual odometry, and in image stitching of many frames. For large changes of scale or strong blur, float descriptors such as SIFT match better; learned features such as SuperPoint are better still when a GPU is available.
Pitfalls
- Clustered corners. FAST fires many times on one corner. Without non-maximum suppression the best corners lie in a few places.
- The border. The patch, turned and with its windows, needs a margin of about 16 pixels; points nearer to the border have no descriptor.
- Bins of 12 degrees. Two views whose angles fall on both sides of a bin border get patterns turned 12 degrees apart, which flips some bits. This is a source of error, not a bug.
- A flat patch. When and are both near 0, is unstable, and so is the descriptor.
- Tests and patterns. A learned pattern must be the same at training and at matching time, and different libraries use different patterns.
- Distance thresholds. Thresholds on the Hamming distance depend on ; use the Lowe ratio test or mutual nearest neighbors instead of a fixed distance when possible.
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-features/. The authors are listed in prov/X00NNP.jsonl.
"""ORB: oriented FAST and rotated BRIEF (Rublee, Rabaud, Konolige and Bradski, 2011).
An image is a list of H rows of W integers; pixel (u, v) is img[v][u], with u
the column (to the right) and v the row (down). Angles are atan2(dv, du), so
the angle grows from the u axis toward the v axis.
1. FAST-9 corners: 9 contiguous pixels of the circle of 16 pixels at radius 3
are all brighter than p + t or all darker than p - t.
2. The corners are ranked by the Harris measure det(M) - k tr(M)^2 over a
7 x 7 window, and the best N are kept. With levels > 1 this runs on each
level of a pyramid with the factor sqrt(2).
3. Orientation by the intensity centroid: m_pq = sum x^p y^q I(x, y) over a
disk of radius 15, theta = atan2(m01, m10).
4. Steered BRIEF: 256 tests on a patch of 31 x 31 pixels. Each test point is
the sum of a 5 x 5 window. The pattern is turned by theta rounded to one of
the bins of 2 pi / 30; the turned patterns are computed once.
5. The tests can be learned by the greedy search of the paper: order the
candidate tests by the distance of their mean from 1/2, and add a test when
its correlation with every chosen test is below a threshold.
A descriptor is a Python int; bit i is 1 when the first point of test i is
darker than the second.
"""
import math
import random
from typing import List, Optional, Sequence, Tuple
Image = Sequence[Sequence[int]]
Point = Tuple[int, int]
Test = Tuple[Point, Point]
CIRCLE = [(0, -3), (1, -3), (2, -2), (3, -1), (3, 0), (3, 1), (2, 2), (1, 3),
(0, 3), (-1, 3), (-2, 2), (-3, 1), (-3, 0), (-3, -1), (-2, -2), (-1, -3)]
PATCH_RADIUS = 15 # the patch is 31 x 31
PATTERN_RADIUS = 13 # test points stay inside the patch after turning and the 5 x 5 window
BORDER = PATCH_RADIUS + 2
def is_fast_corner(img: Image, u: int, v: int, t: int, n: int = 9) -> bool:
"""The segment test: n contiguous circle pixels all brighter or all darker."""
p = img[v][u]
states = []
for du, dv in CIRCLE:
q = img[v + dv][u + du]
states.append(1 if q > p + t else (-1 if q < p - t else 0))
for want in (1, -1):
run = 0
for s in states + states:
run = run + 1 if s == want else 0
if run >= n:
return True
return False
def harris(img: Image, u: int, v: int, half: int = 3, k: float = 0.04) -> float:
"""Harris measure with central differences summed over a (2 half + 1)^2 window."""
a = b = c = 0.0
for y in range(v - half, v + half + 1):
for x in range(u - half, u + half + 1):
gx = (img[y][x + 1] - img[y][x - 1]) / 2.0
gy = (img[y + 1][x] - img[y - 1][x]) / 2.0
a += gx * gx
b += gx * gy
c += gy * gy
return a * c - b * b - k * (a + c) ** 2
def detect(img: Image, n_features: int = 50, t: int = 20) -> List[Tuple[int, int]]:
"""FAST-9 corners, kept where the Harris measure is the largest among the
neighboring corners, ranked by the Harris measure; the best n_features."""
h, w = len(img), len(img[0])
score = {}
for v in range(BORDER, h - BORDER):
for u in range(BORDER, w - BORDER):
if is_fast_corner(img, u, v, t): # @line L1
score[(u, v)] = harris(img, u, v)
kept = [p for p, s in score.items()
if all(score.get((p[0] + du, p[1] + dv), -math.inf) < s
for du in (-1, 0, 1) for dv in (-1, 0, 1) if du or dv)]
kept.sort(key=lambda p: (-score[p], p[1], p[0]))
return kept[:n_features] # @line L2
def centroid_angle(img: Image, u: int, v: int, r: int = PATCH_RADIUS) -> float:
"""theta = atan2(m01, m10) over the disk of radius r around (u, v)."""
m10 = m01 = 0
for y in range(-r, r + 1):
for x in range(-r, r + 1):
if x * x + y * y <= r * r:
p = img[v + y][u + x]
m10 += x * p
m01 += y * p
return math.atan2(m01, m10) # @line L3
def random_pattern(n: int = 256, seed: int = 0, radius: int = PATTERN_RADIUS) -> List[Test]:
"""n tests with both points uniform in the disk of the given radius."""
rng = random.Random(seed)
def point() -> Point:
while True:
x, y = rng.randint(-radius, radius), rng.randint(-radius, radius)
if x * x + y * y <= radius * radius:
return x, y
tests = []
while len(tests) < n:
p, q = point(), point()
if p != q:
tests.append((p, q))
return tests
def steered_patterns(pattern: Sequence[Test], bins: int = 30) -> List[List[Test]]:
"""The pattern turned by 2 pi b / bins for each b, rounded to pixels.
When bins is a multiple of 4, the bins of the second to fourth quarter are
exact 90 degree turns of the first quarter.
"""
def turn(p: Point, a: float) -> Point:
c, s = math.cos(a), math.sin(a)
return int(round(c * p[0] - s * p[1])), int(round(s * p[0] + c * p[1]))
out: List[List[Test]] = []
for b in range(bins):
if bins % 4 == 0 and b >= bins // 4:
prev = out[b - bins // 4]
out.append([((-p[1], p[0]), (-q[1], q[0])) for p, q in prev])
else:
a = 2 * math.pi * b / bins
out.append([(turn(p, a), turn(q, a)) for p, q in pattern])
return out
def angle_bin(theta: float, bins: int) -> int:
return int(round(theta / (2 * math.pi / bins))) % bins
def integral_image(img: Image) -> List[List[int]]:
h, w = len(img), len(img[0])
ii = [[0] * (w + 1) for _ in range(h + 1)]
for v in range(h):
row = 0
for u in range(w):
row += img[v][u]
ii[v + 1][u + 1] = ii[v][u + 1] + row
return ii
def window_sum(ii, u: int, v: int) -> int:
"""Sum of the 5 x 5 window centered at (u, v)."""
return ii[v + 3][u + 3] - ii[v - 2][u + 3] - ii[v + 3][u - 2] + ii[v - 2][u - 2]
def describe(ii, u: int, v: int, tests: Sequence[Test]) -> int:
"""The binary descriptor of (u, v) with already turned tests."""
d = 0
for i, ((px, py), (qx, qy)) in enumerate(tests): # @line L5
if window_sum(ii, u + px, v + py) < window_sum(ii, u + qx, v + qy):
d |= 1 << i # @line L6
return d
def resize(img: Image, factor: float) -> List[List[int]]:
"""Bilinear resampling by 1 / factor, rounded to integers."""
h, w = len(img), len(img[0])
nh, nw = int(h / factor), int(w / factor)
out = []
for v in range(nh):
y = min((v + 0.5) * factor - 0.5, h - 1.0)
y0 = max(0, min(int(math.floor(y)), h - 2))
fy = y - y0
row = []
for u in range(nw):
x = min((u + 0.5) * factor - 0.5, w - 1.0)
x0 = max(0, min(int(math.floor(x)), w - 2))
fx = x - x0
p = ((1 - fy) * ((1 - fx) * img[y0][x0] + fx * img[y0][x0 + 1])
+ fy * ((1 - fx) * img[y0 + 1][x0] + fx * img[y0 + 1][x0 + 1]))
row.append(int(round(p)))
out.append(row)
return out
def orb(img: Image, n_features: int = 50, t: int = 20, levels: int = 1, factor: float = math.sqrt(2.0),
pattern: Optional[Sequence[Test]] = None, bins: int = 30, tables=None):
"""Keypoints (u, v, level, theta) in the coordinates of img, with their descriptors."""
if tables is None:
tables = steered_patterns(pattern if pattern is not None else random_pattern(), bins)
out = []
level_img: List[List[int]] = [list(row) for row in img]
for level in range(levels):
if level > 0:
level_img = resize(img, factor ** level)
if len(level_img) <= 2 * BORDER or len(level_img[0]) <= 2 * BORDER:
break
ii = integral_image(level_img)
scale = factor ** level
for u, v in detect(level_img, n_features, t):
theta = centroid_angle(level_img, u, v)
b = angle_bin(theta, bins) # @line L4
d = describe(ii, u, v, tables[b])
out.append((((u + 0.5) * scale - 0.5, (v + 0.5) * scale - 0.5, level, theta), d))
return out # @line L7
def hamming(a: int, b: int) -> int:
return (a ^ b).bit_count()
def bit_table(patches: Sequence[Image], tests: Sequence[Test]) -> List[int]:
"""For each test, an int whose bit j is the result of the test on patch j.
Each patch is a 31 x 31 image already turned to its orientation; its center is (15, 15).
"""
iis = [integral_image(p) for p in patches]
out = []
for (px, py), (qx, qy) in tests:
bits = 0
for j, ii in enumerate(iis):
if window_sum(ii, 15 + px, 15 + py) < window_sum(ii, 15 + qx, 15 + qy):
bits |= 1 << j
out.append(bits)
return out
def correlation(a: int, b: int, n: int) -> float:
"""Pearson correlation of two binary vectors of length n stored as ints."""
pa, pb = a.bit_count() / n, b.bit_count() / n
pab = (a & b).bit_count() / n
den = math.sqrt(pa * (1 - pa) * pb * (1 - pb))
return 0.0 if den == 0 else (pab - pa * pb) / den
def learn_tests(patches: Sequence[Image], candidates: Sequence[Test], n: int = 256,
threshold: float = 0.2, step: float = 0.05):
"""The greedy search of ORB; returns (chosen tests, the threshold used)."""
m = len(patches)
bits = bit_table(patches, candidates)
order = sorted(range(len(candidates)), key=lambda i: (abs(bits[i].bit_count() / m - 0.5), i))
while True:
chosen = [order[0]]
for i in order[1:]:
if len(chosen) == n:
break
if all(abs(correlation(bits[i], bits[j], m)) < threshold for j in chosen):
chosen.append(i)
if len(chosen) == n or threshold >= 1.0:
return [candidates[i] for i in chosen], threshold
threshold += step
test_orb_features.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/orb-features/. The authors are listed in prov/X00NNP.jsonl.
import math
import random
from orb_features import (CIRCLE, angle_bin, centroid_angle, correlation, describe, detect, hamming,
integral_image, is_fast_corner, learn_tests, orb, random_pattern, steered_patterns,
bit_table, window_sum)
def blob_image(seed, w=64, h=64, n=30):
rng = random.Random(seed)
bl = [(rng.uniform(5, w - 5), rng.uniform(5, h - 5), rng.uniform(2, 5), rng.uniform(-90, 90)) for _ in range(n)]
return [[int(round(120 + sum(a * math.exp(-((u - x) ** 2 + (v - y) ** 2) / (2 * r * r)) for x, y, r, a in bl)))
for u in range(w)] for v in range(h)]
def rot90(img):
"""rot[v][u] = img[63 - u][v]: the pixel (u, v) of img goes to (63 - v, u), an angle grows by pi / 2."""
n = len(img)
return [[img[n - 1 - u][v] for u in range(n)] for v in range(n)]
def test_fast_matches_the_definition():
rng = random.Random(1)
img = [[rng.choice((0, 50, 100, 150, 200)) for _ in range(20)] for _ in range(20)]
for v in range(3, 17):
for u in range(3, 17):
p = img[v][u]
s = "".join("b" if img[v + dv][u + du] > p + 30 else ("d" if img[v + dv][u + du] < p - 30 else "s")
for du, dv in CIRCLE)
want = "b" * 9 in s + s or "d" * 9 in s + s
assert is_fast_corner(img, u, v, 30) == want
assert len(set(CIRCLE)) == 16 and all(round(math.hypot(x, y)) == 3 for x, y in CIRCLE)
def test_centroid_angle():
ramp_u = [[100 + 3 * u for u in range(40)] for _ in range(40)]
ramp_v = [[100 + 3 * v for _ in range(40)] for v in range(40)]
assert centroid_angle(ramp_u, 20, 20) == 0.0
assert abs(centroid_angle(ramp_v, 20, 20) - math.pi / 2) < 1e-15
img = blob_image(2)
rot = rot90(img)
for u, v in [(30, 31), (25, 40), (40, 22)]:
a, b = centroid_angle(img, u, v), centroid_angle(rot, 63 - v, u)
d = (b - a - math.pi / 2 + math.pi) % (2 * math.pi) - math.pi
assert abs(d) < 1e-12
def test_steered_patterns():
pattern = random_pattern(256, seed=3)
assert all(x * x + y * y <= 169 for p in pattern for x, y in p)
tables = steered_patterns(pattern, 32)
assert tables[0] == pattern
for b in range(24):
assert tables[b + 8] == [((-p[1], p[0]), (-q[1], q[0])) for p, q in tables[b]]
for table in tables:
assert all(abs(c) <= 13 for p, q in table for c in p + q)
t30 = steered_patterns(pattern, 30)
# The bin of 2 pi / 30 * 5 is 60 degrees.
c, s = math.cos(math.pi / 3), math.sin(math.pi / 3)
p = pattern[0][0]
assert t30[5][0][0] == (round(c * p[0] - s * p[1]), round(s * p[0] + c * p[1]))
assert angle_bin(2 * math.pi / 30 * 7 + 0.01, 30) == 7 and angle_bin(-0.01, 30) == 0
def test_window_sums():
rng = random.Random(4)
img = [[rng.randint(0, 255) for _ in range(12)] for _ in range(12)]
ii = integral_image(img)
for v in range(2, 10):
for u in range(2, 10):
assert window_sum(ii, u, v) == sum(img[y][x] for y in range(v - 2, v + 3) for x in range(u - 2, u + 3))
def test_rotation_by_90_degrees_gives_the_same_descriptor():
img = blob_image(7)
rot = rot90(img)
tables = steered_patterns(random_pattern(256, seed=0), 32)
a = orb(img, n_features=20, t=10, bins=32, tables=tables)
b = {(k[0], k[1]): (k, d) for k, d in orb(rot, n_features=20, t=10, bins=32, tables=tables)}
assert len(a) >= 8
plain = []
for k, d in a:
k2, d2 = b[(63 - k[1], k[0])]
assert angle_bin(k2[3], 32) == (angle_bin(k[3], 32) + 8) % 32
assert hamming(d, d2) == 0
ii, ir = integral_image(img), integral_image(rot)
plain.append(hamming(describe(ii, int(k[0]), int(k[1]), tables[0]),
describe(ir, int(k2[0]), int(k2[1]), tables[0])))
# Without steering, the same tests on the turned image disagree on many bits.
assert sum(plain) / len(plain) > 40
def test_offset_gives_the_same_output():
img = blob_image(8)
brighter = [[x + 25 for x in row] for row in img]
assert orb(img, n_features=15, t=10) == orb(brighter, n_features=15, t=10)
def test_detector_keeps_local_maxima_ranked():
img = blob_image(9)
kps = detect(img, n_features=100, t=10)
assert kps and len(set(kps)) == len(kps)
for u, v in kps:
assert is_fast_corner(img, u, v, 10)
assert len(detect(img, n_features=3, t=10)) == 3
assert detect(img, n_features=3, t=10) == kps[:3]
def test_hamming_and_correlation():
rng = random.Random(10)
for _ in range(100):
a, b = rng.getrandbits(256), rng.getrandbits(256)
assert hamming(a, b) == sum(((a >> i) & 1) != ((b >> i) & 1) for i in range(256))
n = 40
for _ in range(50):
a, b = rng.getrandbits(n), rng.getrandbits(n)
xa = [(a >> i) & 1 for i in range(n)]
xb = [(b >> i) & 1 for i in range(n)]
ma, mb = sum(xa) / n, sum(xb) / n
cov = sum((x - ma) * (y - mb) for x, y in zip(xa, xb)) / n
sa = math.sqrt(sum((x - ma) ** 2 for x in xa) / n)
sb = math.sqrt(sum((y - mb) ** 2 for y in xb) / n)
assert abs(correlation(a, b, n) - cov / (sa * sb)) < 1e-12
def naive_greedy(patches, candidates, n, threshold, step):
"""The greedy search written with lists of 0 and 1."""
m = len(patches)
table = []
for (px, py), (qx, qy) in candidates:
table.append([1 if sum(p[15 + py + j][15 + px + i] for i in range(-2, 3) for j in range(-2, 3))
< sum(p[15 + qy + j][15 + qx + i] for i in range(-2, 3) for j in range(-2, 3)) else 0
for p in patches])
means = [sum(r) / m for r in table]
order = sorted(range(len(candidates)), key=lambda i: (abs(means[i] - 0.5), i))
def corr(i, j):
mi, mj = means[i], means[j]
si, sj = math.sqrt(mi * (1 - mi)), math.sqrt(mj * (1 - mj))
if si == 0 or sj == 0:
return 0.0
return (sum(x * y for x, y in zip(table[i], table[j])) / m - mi * mj) / (si * sj)
while True:
chosen = [order[0]]
for i in order[1:]:
if len(chosen) == n:
break
if all(abs(corr(i, j)) < threshold for j in chosen):
chosen.append(i)
if len(chosen) == n or threshold >= 1.0:
return [candidates[i] for i in chosen], threshold
threshold += step
def test_greedy_learning():
patches = []
for seed in range(6):
img = blob_image(100 + seed, 48, 48, 18)
for u, v in [(16, 16), (31, 16), (16, 31), (31, 31), (24, 24)]:
patches.append([row[u - 15:u + 16] for row in img[v - 15:v + 16]])
candidates = random_pattern(150, seed=11)
chosen, thr = learn_tests(patches, candidates, n=24, threshold=0.1, step=0.05)
assert (chosen, thr) == naive_greedy(patches, candidates, 24, 0.1, 0.05)
assert len(chosen) == 24
bits = bit_table(patches, chosen)
m = len(patches)
for i in range(len(chosen)):
for j in range(i):
assert abs(correlation(bits[i], bits[j], m)) < thr
History
Calonder and his coauthors gave BRIEF in 2010. It was fast but not rotation invariant. Rublee, Rabaud, Konolige and Bradski, at Willow Garage, presented ORB at ICCV 2011, at the same conference as BRISK. They joined FAST of Rosten and Drummond (2006), the Harris measure (1988) and the intensity centroid of Rosin (1999) with a learned, steered BRIEF, and added ORB to OpenCV. Mur-Artal, Montiel and Tardos built ORB-SLAM on it in 2015, and ORB became a standard feature of visual SLAM.
References
- Ethan Rublee, Vincent Rabaud, Kurt Konolige and Gary Bradski, ORB, an efficient alternative to SIFT or SURF, IEEE International Conference on Computer Vision (ICCV), 2564-2571, 2011, the sections on oFAST (the Harris ranking, the pyramid, the intensity centroid), on rBRIEF (steered BRIEF, variance and correlation, the greedy learning), on matching with multi-probe LSH, and the timing table
- Paul L. Rosin, Measuring corner properties, Computer Vision and Image Understanding 73(2), 291-307, 1999, the section on the orientation of a corner by the intensity centroid
- Edward Rosten and Tom Drummond, Machine learning for high-speed corner detection, European Conference on Computer Vision (ECCV), Lecture Notes in Computer Science 3951, 430-443, 2006, the section on the segment test (the circle of 16 pixels and n contiguous pixels)
- Michael Calonder, Vincent Lepetit, Mustafa Ozuysal, Tomasz Trzcinski, Christoph Strecha and Pascal Fua, BRIEF, computing a local binary descriptor very fast, IEEE Transactions on Pattern Analysis and Machine Intelligence 34(7), 1281-1298, 2012, the sections on the binary tests and their sampling
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 | W2 basic |
|
Tag X00NNP Edit this page History Report an error Markdown