Algorithmcore
BRIEF descriptor
Also called binary robust independent elementary features.
Describe a keypoint by a string of n_d bits, each the result of one intensity comparison between two random points of a smoothed patch, and compare strings by Hamming distance.
- Solves
- Feature matching
- Time
- O(W H + k d) worst · average · best
- Space
- O(W H + k d / w) extra
- Where
- H = the image height in pixels; W = the image width in pixels; d = the number of tests; k = the number of keypoints; w = the word size
- Model
- Word RAM
- Properties
- deterministicexactheuristicnot rotation invariantnot scale invariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Michael Calonder, Vincent Lepetit, Christoph Strecha, Pascal Fua, 2010
BRIEF (binary robust independent elementary features) is a feature descriptor made of bits. It smooths the image, takes a square patch of side around a keypoint, and compares the intensities of pairs of points in the patch. Each comparison gives one bit, and the bits form a string of bits, usually 128, 256 or 512. Two descriptors are compared by the Hamming distance, the number of bits in which they differ, which a computer finds with an exclusive or and a population count. BRIEF does not detect keypoints and does not find an orientation or a scale. It is fast to compute and to match, but it changes when the patch turns by more than a few degrees. ORB adds an orientation to it.
In plain words
Pick 256 pairs of points in a small square around a keypoint, at random, once. Use the same pairs for all keypoints. For each pair, ask one question: is the first point darker than the second? Write 1 for yes and 0 for no. The 256 answers are the descriptor. To compare two keypoints, count the questions that got different answers. Two views of the same spot give mostly the same answers, so the count is small. Two different spots give answers that agree about half the time. The image is blurred first, so that one noisy pixel does not change an answer. The method does not care about the overall brightness, because the answer to "is this darker than that" stays the same.
The problem
The input is a gray digital image with integer values, a list of keypoints , a patch size and a number of tests . A pixel is , with the column (to the right) and the row (down). Let be smoothed by a low-pass filter. A test is a pair of offsets in , and
The descriptor of is the number
a string of bits. The tests are drawn once, before any image, and stay fixed. For two descriptors and the distance is the Hamming distance . The output is one descriptor for each keypoint whose patch, with the smoothing window, is inside the image.
Calonder and his coauthors smooth with a Gaussian of variance 2 on a window, and they compare five ways to draw the tests in Section 3.2:
- G I: both points uniform on the patch.
- G II: both points i.i.d. Gaussian, with mean 0 and variance .
- G III: Gaussian with variance , and Gaussian around with variance .
- G IV: points from a coarse polar grid.
- G V: and on a coarse polar grid.
G II did slightly better than the others in their tests, and G V, which compares the center with other points, did worst. The sampling is a design choice, not a result. Points that fall outside the patch are clamped to the border.
The algorithm
BRIEF(I, keypoints, S, n_d)- 1
J ← I smoothed by the 9 × 9 kernel of variance 2 - 2
draw n_d pairs (x_i, y_i), each coordinate Gaussian with variance S^2/25, rounded and clamped to [-S/2, S/2] - 3
for each keypoint k whose patch is inside the image do - 4
d ← 0 - 5
for i = 1 to n_d do - 6
if J(k + x_i) < J(k + y_i) then d ← d + 2^(i-1) - 7
output d as the descriptor of k HAMMING(a, b)- 8
return the number of ones of a XOR b, summed over the words of the strings
Our code smooths with the separable binomial kernel . This kernel is the distribution of a sum of 8 fair coin flips, so its variance is exactly in each direction, the variance of the paper, and it is close to a Gaussian. The code keeps the integer sums and does not divide by , so every test is an exact integer comparison. Matching takes, for each descriptor of one image, the descriptor of the other image with the smallest Hamming distance. The population count of a 64-bit word uses the SWAR popcount.
Example
Take tests on a patch that is already smoothed, with the keypoint at the center. Offsets are .
| 1 | 10 | 47 | 1 | ||
| 2 | 28 | 17 | 0 | ||
| 3 | 15 | 29 | 1 | ||
| 4 | 27 | 14 | 0 | ||
| 5 | 19 | 23 | 1 | ||
| 6 | 22 | 33 | 1 | ||
| 7 | 15 | 22 | 1 | ||
| 8 | 34 | 22 | 0 |
The bits from test 1 to test 8 are 10101110, so . Now take a second patch with about twice the contrast, 10 more brightness and some noise, for example the first row and the center 47. The eight comparisons give the same answers, so its descriptor is also 117 and the Hamming distance is 0. Turn the first patch by 90 degrees instead. The bits become 00001111, the number 240, and the Hamming distance to 117 is 3 of 8. Three answers changed because the patch has a gradient to the bottom right, and a turn moves the gradient.
Correctness
BRIEF is a definition, so correctness means that the algorithm returns and the Hamming distance as defined, and that the stated invariances hold. The proof in proofs/correctness.md shows that:
- Lines L4 to L7 return , and line L8 returns the Hamming distance.
- The descriptor does not change when the image changes by with , because the smoothing is linear with positive weights that sum to a constant.
- A shift of the image by whole pixels shifts the descriptors with the keypoints.
- For a fixed descriptor and a uniformly random string, the Hamming distance has mean . This is why unrelated keypoints have distances near ; for real patches the tests are not independent, and the spread is wider.
The ability of BRIEF to tell keypoints apart is a measured result, not a theorem. Calonder and his coauthors measured recognition rates on image sequences with SURF keypoints. In their tests BRIEF-64 did better than SURF and U-SURF on all sequences except Graffiti, BRIEF-32 did slightly worse than BRIEF-64 but compared well, and BRIEF-16 was too short.
Proof: Correctness of the BRIEF descriptorfull
Fix the tests for , the smoothing kernel with weights and , and an image . Let , so , and let if and otherwise. All keypoints below have their patch and the smoothing window inside the image, so no border rule is used.
Lemma 1 (the descriptor). For each keypoint , lines L4 to L7 output .
Proof. We show by induction on that after the iteration of line L5, . Before the loop by line L4, the empty sum. In iteration , line L6 adds exactly when . So the claim holds after iteration . After iteration , , and line L7 outputs it.
Lemma 2 (the Hamming distance). Line L8 returns the number of positions in which and differ.
Proof. Bit of is 1 exactly when bit of differs from bit of . The words of split its bits into disjoint groups, and the popcount of each word counts the ones in its group. So the sum over the words counts all positions where and differ.
Lemma 3 (affine change of intensity). Let with . Then for each keypoint .
Proof. . So . Since this difference is negative exactly when is negative, so for each , and by Lemma 1 .
With integer weights, integer images, integer and integer , every quantity in this proof is an integer, so the implementation follows the lemma exactly.
Lemma 4 (shift). Let for a fixed integer vector . Then the descriptor of at equals the descriptor of at .
Proof. . So and , and each test of at equals the same test of at . By Lemma 1 the descriptors are equal.
Lemma 5 (random strings). Let be a fixed string of bits and a string with independent bits, each 1 with probability . Then the Hamming distance of and has the binomial distribution with trials and probability , with mean and variance .
Proof. Bit of is 1 exactly when bit of differs from bit of , which has probability whatever bit of is. The bits of are independent, so the bits of are independent with probability each, and their sum is binomial.
Lemma 5 is a model for unrelated keypoints, not a fact about images. The tests of BRIEF on real patches are correlated and do not have probability exactly , so the distances of unrelated keypoints spread more widely than the binomial; Section 3.3 of Calonder et al. shows measured distributions.
Theorem. BRIEF returns for each keypoint whose patch is inside the image, and HAMMING returns the Hamming distance. The descriptor does not change under with , and it moves with the keypoints under a shift by whole pixels.
Proof. Lemmas 1 to 4.
Complexity
The model is the word RAM with integer pixels and a word of bits. Let be the number of tests and the number of keypoints.
- Line L1 takes time with a separable kernel of fixed size.
- Line L2 takes time.
- Lines L4 to L7 take time per keypoint, so in total.
- A descriptor takes words: 4 words for and . Line L8 takes time with a popcount of time per word.
- Matching descriptors against by brute force takes time.
The extra space is for the smoothed image and for the descriptors. Only the comparisons of line L6 touch the image, so the cost per keypoint does not depend on .
The paper reports timings for 512 keypoints: about 8 to 10 ms for the BRIEF descriptors against 335 ms for SURF-64, and 2 to 8 ms for exact nearest neighbor matching against 28 ms for SURF. These are measurements on the hardware of the authors in 2010, not properties of the method.
Properties
- Affine change of intensity. The descriptor does not change under with . Each test would also allow an increasing change of the smoothed image, but the smoothing is linear, so a nonlinear change of can change a test.
- Not rotation invariant. The tests are fixed in the image frame. Calonder and his coauthors measured that the recognition rate stays high up to about 10 to 15 degrees and then drops quickly.
- Not scale invariant. The patch has a fixed size in pixels. Use it at the scale of a detector, or on a pyramid.
- Compact. 256 tests take 32 bytes, against 64 floats for SURF-64 or 128 for SIFT.
- Cheap to match. The distance is an exclusive or and a popcount per word.
- Not learned. The tests are random. Many of them are correlated, which wastes bits; ORB learns a set of tests with low correlation.
Variants and improvements
- BRIEF-16, BRIEF-32, BRIEF-64. The names give the length in bytes: , 256 and 512.
- U-BRIEF and O-BRIEF. The upright form is the plain one. An oriented form turns the tests by the orientation of the keypoint, as in ORB.
- rBRIEF. ORB turns the tests by the orientation from the intensity centroid and learns tests with high variance and low correlation.
- BRISK and FREAK. BRISK uses a fixed pattern of points on circles, smooths each point by its own Gaussian, and takes the orientation from long pairs. FREAK uses a retina-like pattern.
- Census transform. The census transform compares each pixel of a window with the center, and local binary patterns do the same on a circle and keep a histogram.
- Hashing. Binary strings fit locality-sensitive hashing with bit sampling, and ORB uses multi-probe LSH.
When to use it
Use BRIEF when speed and memory matter more than invariance, for example in tracking between video frames where the camera turns little. Pair it with a fast detector such as FAST. When the camera can turn, use ORB or BRISK, which add an orientation. When large changes of scale or viewpoint occur, a float descriptor such as SIFT is often more robust.
Pitfalls
- No smoothing. Without smoothing a single noisy pixel flips a test. The paper shows a large loss of recognition rate without it.
- Different tests. Two descriptors are comparable only if they use the same pairs in the same order. Fix the seed, or store the pattern.
- Border. The patch and the smoothing window must be inside the image. Drop keypoints near the border, or pad the image.
- Ties. On flat areas many tests compare equal values and give 0. The test is strict, so equal values always give 0. Our integer smoothing keeps ties exact; float smoothing can break them at random.
- Rotation. BRIEF fails when the camera turns by more than about 15 degrees. This is a property of the method, not of the implementation.
- Popcount. In Python,
bin(x).count("1")orint.bit_countis the simplest popcount. In C, use the hardware instruction; the SWAR form is the portable fallback.
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/brief-descriptor/. The authors are listed in prov/BQH47W.jsonl.
"""BRIEF: binary robust independent elementary features.
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).
The patch is smoothed with the separable 9 x 9 binomial kernel
(1, 8, 28, 56, 70, 56, 28, 8, 1). This is the distribution of a sum of 8 fair
coin flips, so its variance is 2 in each direction, the value that Calonder et
al. use for the Gaussian. The weights are integers and the code does not
divide by 256 * 256, so the smoothed image is an exact integer image and every
comparison is exact.
The tests follow the sampling G II of the paper: both points of a pair are
i.i.d. Gaussian with variance S^2 / 25 around the keypoint, here rounded to the
nearest pixel and clamped to the patch [-S/2, S/2]^2. Bit i - 1 of the
descriptor is 1 when J(k + x_i) < J(k + y_i). A descriptor is a Python int
with n_d bits, which is n_d / 64 words of 64 bits.
"""
import random
from typing import List, Optional, Sequence, Tuple
Image = Sequence[Sequence[int]]
Pair = Tuple[Tuple[int, int], Tuple[int, int]]
BINOMIAL9 = (1, 8, 28, 56, 70, 56, 28, 8, 1)
M1 = 0x5555555555555555
M2 = 0x3333333333333333
M4 = 0x0F0F0F0F0F0F0F0F
H01 = 0x0101010101010101
MASK64 = (1 << 64) - 1
def smooth(img: Image) -> List[List[int]]:
"""Separable binomial smoothing with replicated borders, integer output."""
h, w = len(img), len(img[0])
tmp = [[0] * w for _ in range(h)]
for v in range(h):
row = img[v]
for u in range(w):
s = 0
for k, wt in enumerate(BINOMIAL9):
uu = min(max(u + k - 4, 0), w - 1)
s += wt * row[uu]
tmp[v][u] = s
out = [[0] * w for _ in range(h)]
for v in range(h):
for u in range(w):
s = 0
for k, wt in enumerate(BINOMIAL9):
vv = min(max(v + k - 4, 0), h - 1)
s += wt * tmp[vv][u]
out[v][u] = s
return out
def sample_pairs(n_d: int = 256, patch: int = 32, seed: int = 0) -> List[Pair]:
"""n_d test pairs by the G II sampling, clamped to the patch."""
rng = random.Random(seed)
half = patch // 2
sigma = patch / 5.0
def coord() -> int:
return max(-half, min(half, int(round(rng.gauss(0.0, sigma)))))
return [((coord(), coord()), (coord(), coord())) for _ in range(n_d)]
def describe(smoothed: Sequence[Sequence[int]], u: int, v: int, pairs: Sequence[Pair]) -> int:
"""The descriptor of the keypoint (u, v) as an int of len(pairs) bits."""
d = 0 # @line L4
for i, ((xu, xv), (yu, yv)) in enumerate(pairs): # @line L5
if smoothed[v + xv][u + xu] < smoothed[v + yv][u + yu]: # @line L6
d |= 1 << i
return d # @line L7
def brief(img: Image, keypoints: Sequence[Tuple[int, int]], n_d: int = 256, patch: int = 32,
seed: int = 0, pairs: Optional[Sequence[Pair]] = None) -> List[Optional[int]]:
"""BRIEF descriptors of the keypoints; None for a keypoint too close to the border."""
j = smooth(img) # @line L1
if pairs is None:
pairs = sample_pairs(n_d, patch, seed) # @line L2
h, w = len(img), len(img[0])
half = patch // 2
out: List[Optional[int]] = []
for u, v in keypoints: # @line L3
if half <= u < w - half and half <= v < h - half:
out.append(describe(j, u, v, pairs))
else:
out.append(None)
return out
def popcount64(x: int) -> int:
"""SWAR popcount of a 64-bit word."""
x = x - ((x >> 1) & M1)
x = (x & M2) + ((x >> 2) & M2)
x = (x + (x >> 4)) & M4
return ((x * H01) & MASK64) >> 56
def hamming(a: int, b: int, n_d: int = 256) -> int:
"""Hamming distance of two n_d-bit descriptors, one 64-bit word at a time."""
x = a ^ b # @line L8
total = 0
for k in range(0, n_d, 64):
total += popcount64((x >> k) & MASK64)
return total
def match(desc1: Sequence[int], desc2: Sequence[int], n_d: int = 256) -> List[Tuple[int, int]]:
"""For each descriptor of the first list: (index of the nearest in the second, distance)."""
out = []
for a in desc1:
best, best_j = n_d + 1, -1
for j, b in enumerate(desc2):
d = hamming(a, b, n_d)
if d < best:
best, best_j = d, j
out.append((best_j, best))
return out
test_brief_descriptor.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/brief-descriptor/. The authors are listed in prov/BQH47W.jsonl.
import random
from brief_descriptor import BINOMIAL9, brief, hamming, match, popcount64, sample_pairs, smooth
def random_image(rng, w, h, hi=255):
return [[rng.randint(0, hi) for _ in range(w)] for _ in range(h)]
def texture(rng, w, h):
"""A smooth random texture: a coarse random grid, upsampled and summed."""
coarse = [[rng.randint(0, 255) for _ in range(w // 4 + 2)] for _ in range(h // 4 + 2)]
return [[coarse[v // 4][u // 4] + coarse[(v + 2) // 4][(u + 2) // 4] for u in range(w)] for v in range(h)]
def test_binomial_kernel_has_variance_two():
total = sum(BINOMIAL9)
mean = sum(k * w for k, w in enumerate(BINOMIAL9)) / total
var = sum((k - mean) ** 2 * w for k, w in enumerate(BINOMIAL9)) / total
assert total == 256 and mean == 4 and var == 2
def test_smooth_matches_direct_2d_sum():
rng = random.Random(1)
img = random_image(rng, 14, 12)
s = smooth(img)
h, w = 12, 14
for v in range(h):
for u in range(w):
want = 0
for a in range(9):
for b in range(9):
uu = min(max(u + b - 4, 0), w - 1)
vv = min(max(v + a - 4, 0), h - 1)
want += BINOMIAL9[a] * BINOMIAL9[b] * img[vv][uu]
assert s[v][u] == want
def test_popcount_and_hamming_match_brute_force():
rng = random.Random(2)
for _ in range(500):
x = rng.getrandbits(64)
assert popcount64(x) == bin(x).count("1")
for _ in range(200):
a, b = rng.getrandbits(512), rng.getrandbits(512)
assert hamming(a, b, 512) == bin(a ^ b).count("1")
def test_pairs_follow_the_patch_and_the_seed():
p = sample_pairs(256, 32, seed=7)
assert p == sample_pairs(256, 32, seed=7)
assert len(p) == 256
assert all(-16 <= c <= 16 for pair in p for pt in pair for c in pt)
q = sample_pairs(512, 48, seed=3)
coords = [c for pair in q for pt in pair for c in pt]
mean = sum(coords) / len(coords)
var = sum((c - mean) ** 2 for c in coords) / len(coords)
assert abs(mean) < 1.0 and 70 < var < 115 # sigma^2 = 48^2 / 25 = 92.16
def test_descriptor_matches_direct_definition():
rng = random.Random(3)
img = random_image(rng, 40, 40)
pairs = sample_pairs(128, 16, seed=1)
d = brief(img, [(20, 20)], pairs=pairs)[0]
j = smooth(img)
for i, ((xu, xv), (yu, yv)) in enumerate(pairs):
bit = 1 if j[20 + xv][20 + xu] < j[20 + yv][20 + yu] else 0
assert (d >> i) & 1 == bit
def test_offset_and_positive_gain_give_the_same_descriptor():
rng = random.Random(4)
img = random_image(rng, 40, 40)
kps = [(20, 20), (18, 23), (16, 16)]
base = brief(img, kps, patch=32)
for a, b in ((1, 50), (3, 0), (7, -100)):
assert brief([[a * x + b for x in row] for row in img], kps, patch=32) == base
def test_shift_by_whole_pixels():
rng = random.Random(5)
img = random_image(rng, 48, 48)
shifted = [[img[v][(u + 5) % 48] for u in range(48)] for v in range(48)]
# Pixel (u, v) of shifted is pixel (u + 5, v) of img; stay 9 pixels from the wrap.
for u, v in ((22, 24), (21, 26)):
assert brief(shifted, [(u, v)])[0] == brief(img, [(u + 5, v)])[0]
def test_border_keypoints_get_none():
rng = random.Random(6)
img = random_image(rng, 40, 40)
assert brief(img, [(3, 20), (20, 39)]) == [None, None]
def test_noisy_copy_matches_its_own_keypoints():
rng = random.Random(7)
img = texture(rng, 64, 64)
noisy = [[x + rng.randint(-6, 6) for x in row] for row in img]
kps = [(u, v) for u in range(18, 47, 7) for v in range(18, 47, 7)]
d1 = brief(img, kps)
d2 = brief(noisy, kps)
m = match(d1, d2)
right = sum(1 for i, (j, _) in enumerate(m) if j == i)
assert right >= len(kps) - 2
same = [hamming(d1[i], d2[i]) for i in range(len(kps))]
assert max(same) < 64
History
Calonder, Lepetit, Strecha and Fua published BRIEF at ECCV 2010. Earlier keypoint classifiers of the same group, randomized trees and ferns, already used simple pairwise intensity tests, but they needed training for each scene. The 2012 journal paper added experiments and more authors. In 2011 Rublee and his coauthors built ORB on BRIEF, and Leutenegger, Chli and Siegwart built BRISK with a fixed pattern. Binary descriptors became the default in real-time systems such as ORB-SLAM.
References
- Michael Calonder, Vincent Lepetit, Christoph Strecha and Pascal Fua, BRIEF, binary robust independent elementary features, European Conference on Computer Vision (ECCV 2010), Part IV, LNCS 6314, 778-792, Section 3 (the test, the descriptor as a sum of powers of 2), Section 3.1 (smoothing), Section 3.2 (the five sampling geometries G I to G V), Section 3.3 (distance distributions), Section 4 (recognition rates and timings)
- 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 whole paper (the journal version with more experiments)
- 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, Section 4 (the analysis of BRIEF under rotation and the variance and correlation of its tests)
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 BQH47W Edit this page History Report an error Markdown