Algorithm Search⌘K

Algorithmadvanced

BRISK features

Also called binary robust invariant scalable keypoints.

Scale-space AGAST keypoints with a binary descriptor from a fixed concentric sampling pattern, with long pairs giving the orientation and short pairs the bits.

Time
O(W H + n q) worst · average · best
Space
O(W H + n) extra
Where
H = the image height in pixels; W = the image width in pixels; n = the number of keypoints; q = the number of pixels under the largest smoothing window of a pattern point
Properties
deterministicnot exactheuristicrotation invariantscale invariant
Origin
Stefan Leutenegger, Margarita Chli, Roland Y. Siegwart, 2011

BRISK (binary robust invariant scalable keypoints) finds corners at many scales and describes each one by a string of 512 bits. The detector runs the FAST segment test, in the faster AGAST form, on a pyramid of octaves and intra-octaves, and keeps the points whose FAST score is larger than at all neighbors in space and scale. The descriptor reads 60 smoothed intensities on four rings around the keypoint. Pairs of distant points give the direction of the local gradient, which turns the pattern; pairs of near points give the bits, one comparison each, as in BRIEF. Descriptors are compared with the Hamming distance. Unlike ORB, whose tests are learned, BRISK uses a fixed, hand-designed pattern.

In plain words

Look for corners in the image, and in smaller copies of the image so that large corners are found too. A corner is a point where many of the pixels on a small ring around it are all much brighter or all much darker. Keep a corner only where it is stronger than its neighbors and than the same place in the copies just smaller and just larger. Around each corner, read the brightness at 60 points on four circles, each blurred a little. Points that are far apart show which way the brightness rises, and that gives a direction. Turn the circles to that direction, and then compare each pair of nearby points: the brighter one gives a 1 or a 0. The 512 answers are the description of the corner.

The problem

The input is a gray image II with WW columns and HH rows; a pixel is (u,v)(u, v), with uu the column and vv the row, and angles grow from the uu axis toward the vv axis. The output is a set of keypoints (u,v,t,α)(u, v, t, \alpha) with a scale tt and an orientation α\alpha, each with 512 bits, for feature matching by the Hamming distance.

Scale space. The pyramid has octaves c0,c1,…c_0, c_1, \dots, each half the size of the one before, and intra-octaves d0,d1,…d_0, d_1, \dots between them. The layer d0d_0 is c0c_0 downsampled by 1.51.5, and each next did_i is half of di−1d_{i-1}. So the scales are t(ci)=2it(c_i) = 2^i and t(di)=1.5⋅2it(d_i) = 1.5 \cdot 2^i.

FAST score. On each layer, the FAST 9-16 test asks whether 9 contiguous pixels of the circle of 16 are all brighter than I(p)+TI(p) + T or all darker than I(p)−TI(p) - T. The score ss of a pixel is the largest threshold for which it is still a corner. A keypoint is a pixel with s>Ts > T that is larger than the scores of its 8 neighbors and of the layers above and below near the same place. The paper fits a 2D quadratic to the scores in each of the three layers and a parabola along the log of the scale to refine the position and the scale. For c0c_0 it makes the scores of a virtual layer d−1d_{-1} below it with the FAST 5-8 mask on c0c_0.

Pattern. The 60 points pip_i lie on a center point and on four rings. In the OpenCV pattern, the radii are 0.85⋅(0,2.9,4.9,7.4,10.8)0.85 \cdot (0, 2.9, 4.9, 7.4, 10.8), with 1,10,14,151, 10, 14, 15 and 2020 points, all scaled by tt. Each point is read after smoothing with a Gaussian whose σi\sigma_i grows with the spacing of the points on its ring, so that the smoothed areas do not overlap much. Write I(pi,σi)I(p_i, \sigma_i) for the smoothed value.

Pairs. Of the 60⋅59/2=177060 \cdot 59 / 2 = 1770 pairs, the short pairs S\mathcal{S} have ∥pj−pi∥<δmax⁡\lVert p_j - p_i \rVert < \delta_{\max} and the long pairs L\mathcal{L} have ∥pj−pi∥>δmin⁡\lVert p_j - p_i \rVert > \delta_{\min}. The paper gives δmax⁡=9.75t\delta_{\max} = 9.75 t and δmin⁡=13.67t\delta_{\min} = 13.67 t for its pattern; in the units of the radii above the thresholds are 5.85t5.85 t and 8.2t8.2 t, which give 512 short and 870 long pairs. The local gradient of a long pair, and their mean, are

g(pi,pj)=(pj−pi)I(pj,σj)−I(pi,σi)∥pj−pi∥2,g=1∣L∣∑(pi,pj)∈Lg(pi,pj),g(p_i, p_j) = (p_j - p_i) \frac{I(p_j, \sigma_j) - I(p_i, \sigma_i)}{\lVert p_j - p_i \rVert^2}, \qquad g = \frac{1}{|\mathcal{L}|} \sum_{(p_i, p_j) \in \mathcal{L}} g(p_i, p_j),

and the orientation is α=atan2⁡(gv,gu)\alpha = \operatorname{atan2}(g_v, g_u). With the pattern turned by α\alpha, the bit of a short pair is b=[I(pjα,σj)>I(piα,σi)]b = [I(p_j^\alpha, \sigma_j) > I(p_i^\alpha, \sigma_i)].

The algorithm

  1. BRISK(I, T)
  2. 1build the layers c_0, d_0, c_1, d_1, ...; compute the FAST 9-16 score s on each
  3. 2keep the points with s > T that beat their 8 neighbors and the layers above and below; refine the scale t
  4. 3for each keypoint (u, v, t), read the 60 pattern points scaled by t, each smoothed with σ_i t
  5. 4g ← the mean of (p_j - p_i)(I(p_j) - I(p_i)) / ‖p_j - p_i‖² over the 870 long pairs
  6. 5α ← atan2(g_v, g_u)
  7. 6read the 60 points again with the pattern turned by α
  8. 7for each of the 512 short pairs (i, j), bit ← [I(p_j) > I(p_i)]
  9. 8return the keypoints with their 512-bit descriptors

Our code simplifies the detector. It computes the FAST score on all layers without AGAST, compares a point with the largest score in a 3×33 \times 3 neighborhood of the layers above and below, refines only the scale by the parabola, and has no layer d−1d_{-1}; a missing layer counts as the score 0. The smoothing is a Gaussian-weighted mean of the pixels within 3σ3\sigma of the point, and σ≈1.3 rsin⁡(π/n)\sigma \approx 1.3\, r \sin(\pi / n) for a ring of radius rr with nn points (0.5 for the center), which is our choice. The descriptor is the one of the paper.

Example

A square. In a 64×6464 \times 64 image that is 30 everywhere except a square of value 200 with the corners (20,20)(20, 20) and (43,43)(43, 43), the pixel (20,20)(20, 20) is the corner pixel of the square. On its circle of 16 pixels, 11 contiguous pixels are outside the square and darker by 170170, so its FAST score is 170170; the pixel (19,19)(19, 19) outside the square has the score 0. Some neighbors along the edges have the same score 170, and the code keeps the first in raster order. The detector finds all four corners of the square at the scale t≈1.22t \approx 1.22, and again in the coarser layers. At (20,20)(20, 20) the long pairs give α≈44.5°\alpha \approx 44.5°: the mean gradient points from the corner into the bright square, toward the lower right.

The pattern. The radii are 0,2.47,4.17,6.290, 2.47, 4.17, 6.29 and 9.189.18 pixels at t=1t = 1, and our σ\sigma values are 0.5,0.99,1.21,1.700.5, 0.99, 1.21, 1.70 and 1.871.87. The two outer rings are about 2.9 pixels apart, so the smoothed areas of neighboring points touch but do not cover each other.

Rotation by 90 degrees. On a 64×6464 \times 64 image turned by 90 degrees, the orientation of a point grows by about π/2\pi/2, and the tests find fewer than 40 of the 512 bits different between the point and its turned copy, while two points about 6 pixels apart differ in more than 40 bits. The pattern has 10, 14 and 15 points on three rings, which are not multiples of 4, so a turned pattern does not fall on the same points, and the match is close but not exact.

Correctness

BRISK is a heuristic; its matching quality is a benchmark result. The proof in proofs/correctness.md shows that:

  • The FAST score of the code is the largest threshold for which the point is still a FAST 9-16 corner: the point is a corner for TT exactly when T<sT < s.
  • The kept points are those with s>Ts > T that beat their neighbors in the layer and are not beaten by the layers above and below.
  • On a linear ramp au+bva u + b v with exact smoothed values, each long pair gives the part of (a,b)(a, b) along the direction of the pair, and the mean is M(a,b)M (a, b) for a fixed matrix MM. For the pattern above M≈diag⁡(0.5014,0.4986)M \approx \operatorname{diag}(0.5014, 0.4986), so α\alpha is within 0.16 degrees of the direction of (a,b)(a, b).
  • Multiplying the image by a positive number does not change the descriptor or the orientation, since every smoothed value is multiplied by it.
Proof: Correctness of BRISKfull

Pixels are (u,v)(u, v) with uu the column and vv the row. For a pixel pp of a layer, let δ0,…,δ15\delta_0, \dots, \delta_{15} be the differences I(ck)−I(p)I(c_k) - I(p) for the 16 pixels ckc_k of the circle of radius 3, in order around the circle. The point is a FAST 9-16 corner for the threshold TT when there is a start jj with δj+k>T\delta_{j + k} > T for k=0,…,8k = 0, \dots, 8, or with −δj+k>T-\delta_{j + k} > T for k=0,…,8k = 0, \dots, 8, indices modulo 16.

Lemma 1 (FAST score). Let s=max⁡(0,max⁡jmin⁡0≤k≤8δj+k,max⁡jmin⁡0≤k≤8(−δj+k))s = \max(0, \max_j \min_{0 \le k \le 8} \delta_{j + k}, \max_j \min_{0 \le k \le 8} (-\delta_{j + k})). For every T≥0T \ge 0, the point is a corner for TT if and only if T<sT < s.

Proof. If the point is a corner for TT with a bright run starting at jj, then min⁡kδj+k>T\min_k \delta_{j + k} > T, so s>Ts > T; a dark run is the same with −δ-\delta. Conversely, if T<sT < s, then s>0s > 0, and ss equals min⁡kδj+k\min_k \delta_{j + k} or min⁡k(−δj+k)\min_k (-\delta_{j + k}) for some jj. In the first case all nine δj+k≥s>T\delta_{j + k} \ge s > T, which is a bright run; the second case gives a dark run. The code takes the minimum over the nine values of the doubled list δ0,…,δ15,δ0,…,δ7\delta_0, \dots, \delta_{15}, \delta_0, \dots, \delta_7 starting at j=0,…,15j = 0, \dots, 15, which are exactly the cyclic runs. □\square

So ss is the largest threshold, in the sense of a supremum, for which the point is a corner, which is the FAST score that BRISK uses.

Lemma 2 (selection). A pixel pp of layer kk with score ss is returned by the detector if and only if s>Ts > T; every neighbor qq of pp in the layer has a score below ss, or the same score and comes after pp in raster order; and the largest score in the 3×33 \times 3 pixels of the layers k−1k - 1 and k+1k + 1 around the place of pp is at most ss.

Proof. The code skips pp exactly when s≤Ts \le T, or when some neighbor has a larger score or the same score and an earlier place in raster order (an offset (δv,δu)<(0,0)(\delta_v, \delta_u) < (0, 0) in the lexicographic order), or when the largest nearby score of an adjacent layer is larger than ss. All other pixels inside the margin are returned. □\square

Two neighbors with the same score cannot both be returned, since one of them comes first, so a plateau of equal scores gives at most one point per 3×33 \times 3 neighborhood of the plateau's first pixel.

Lemma 3 (the parabola). Let ℓ0<ℓ1<ℓ2\ell_0 < \ell_1 < \ell_2 be the log scales of the three layers and s0,s1,s2s_0, s_1, s_2 the scores with s1>s0s_1 > s_0, s1>s2s_1 > s_2 or with s1≥s0,s2s_1 \ge s_0, s_2 and not both equal. Then the parabola through the three points is concave, and its vertex lies in [ℓ0,ℓ2][\ell_0, \ell_2] before the clip, which the code computes as ℓ1−12N/D\ell_1 - \frac{1}{2} N / D with N=(ℓ1−ℓ0)2(s1−s2)−(ℓ1−ℓ2)2(s1−s0)N = (\ell_1 - \ell_0)^2 (s_1 - s_2) - (\ell_1 - \ell_2)^2 (s_1 - s_0) and D=(ℓ1−ℓ0)(s1−s2)−(ℓ1−ℓ2)(s1−s0)D = (\ell_1 - \ell_0)(s_1 - s_2) - (\ell_1 - \ell_2)(s_1 - s_0).

Proof. D=(ℓ1−ℓ0)(s1−s2)+(ℓ2−ℓ1)(s1−s0)D = (\ell_1 - \ell_0)(s_1 - s_2) + (\ell_2 - \ell_1)(s_1 - s_0) is a sum of nonnegative terms, and it is positive when not both differences are 0. The vertex formula is the standard one for the parabola through three points: write the parabola as s(ℓ)=s1+β(ℓ−ℓ1)+γ(ℓ−ℓ1)2s(\ell) = s_1 + \beta (\ell - \ell_1) + \gamma (\ell - \ell_1)^2; the two equations at ℓ0\ell_0 and ℓ2\ell_2 give γ=−D/((ℓ1−ℓ0)(ℓ2−ℓ1)(ℓ2−ℓ0))<0\gamma = -D / ((\ell_1 - \ell_0)(\ell_2 - \ell_1)(\ell_2 - \ell_0)) < 0, so the parabola is concave, and the vertex ℓ1−β/(2γ)\ell_1 - \beta / (2 \gamma) simplifies to ℓ1−12N/D\ell_1 - \frac{1}{2} N / D. Since the parabola is concave and s(ℓ1)≥s(ℓ0)s(\ell_1) \ge s(\ell_0), the vertex is not left of the midpoint of ℓ0\ell_0 and ℓ1\ell_1; in the same way it is not right of the midpoint of ℓ1\ell_1 and ℓ2\ell_2. So it lies in [ℓ0,ℓ2][\ell_0, \ell_2]. □\square

Lemma 4 (gain). If every pixel is multiplied by c>0c > 0, the orientation and the descriptor do not change.

Proof. Each smoothed value is a weighted mean ∑wqI(q)/∑wq\sum w_q I(q) / \sum w_q with weights that depend only on the positions, so it is multiplied by cc. In line L4 each term of gg is a difference of two smoothed values times a vector that depends only on the pattern, so gg is multiplied by cc, and atan2⁡\operatorname{atan2} does not change. With the same α\alpha, line L6 reads the same positions, and each comparison of line L7 compares two values both multiplied by c>0c > 0, so each bit is the same. When cc is a power of 2, every floating point step is scaled exactly, so the equality also holds bit for bit in the code. □\square

Lemma 5 (ramp). Suppose the smoothed values are exact on the ramp I(u,v)=au+bvI(u, v) = a u + b v, that is, I(p,σ)=apu+bpvI(p, \sigma) = a p_u + b p_v plus a constant. Then g=M(a,b)g = M (a, b) with M=1∣L∣∑(i,j)∈Leijeij⊤M = \frac{1}{|\mathcal{L}|} \sum_{(i, j) \in \mathcal{L}} e_{ij} e_{ij}^\top, where eije_{ij} is the unit vector from pip_i to pjp_j. MM does not depend on the scale tt.

Proof. For a long pair let Δ=pj−pi\Delta = p_j - p_i. Then I(pj)−I(pi)=(a,b)⋅ΔI(p_j) - I(p_i) = (a, b) \cdot \Delta, so g(pi,pj)=Δ(Δ⋅(a,b))/∥Δ∥2=eijeij⊤(a,b)g(p_i, p_j) = \Delta (\Delta \cdot (a, b)) / \lVert \Delta \rVert^2 = e_{ij} e_{ij}^\top (a, b). Taking the mean gives M(a,b)M (a, b). Scaling the pattern by tt does not change the unit vectors. □\square

For the pattern of the page, the reflection v↦−vv \mapsto -v maps each ring onto itself, so the off-diagonal entry of MM is 0, and a direct computation gives M≈diag⁡(0.5014,0.4986)M \approx \operatorname{diag}(0.5014, 0.4986). So the angle of M(a,b)M(a, b) differs from the angle of (a,b)(a, b) by at most about 0.16 degrees. In the code the smoothed values are means over pixels, which are exact on a ramp only when the window is symmetric about the point; the tests check the angle to within one degree.

Theorem. The detector returns exactly the points of Lemma 2, with a scale in the range of the adjacent layers by Lemma 3. For each returned point far enough from the border, the descriptor is the string of 512 comparisons of the short pairs of the pattern turned by the orientation of the long pairs. It does not change when the image is multiplied by a positive constant, and on a ramp the orientation follows the direction of the ramp as in Lemma 5.

Proof. Line L1 computes the scores by Lemma 1, and line L2 keeps the points by Lemma 2 and refines the scale by Lemma 3. Lines L3 to L5 compute gg and α\alpha as defined, and lines L6 and L7 set bit kk for the short pair kk as defined. Lemma 4 gives the invariance to a gain and Lemma 5 the behavior on a ramp. □\square

Complexity

The model is the word RAM.

  • Line L1 takes O(1)O(1) time per pixel on each layer. The layers cic_i and did_i have WH/4iW H / 4^i and WH/(2.25⋅4i)W H / (2.25 \cdot 4^i) pixels, so the sum is O(WH)O(W H).
  • Line L2 takes O(1)O(1) time per pixel, with 8 neighbors and 9 pixels in each of the two adjacent layers.
  • Lines L3 and L6 take O(q)O(q) time per keypoint for 60 smoothed values, where qq is the number of pixels under the largest Gaussian window. In the code qq grows with t2t^2; OpenCV approximates the Gaussians by box sums over an integral image, which makes the cost a constant.
  • Lines L4, L5 and L7 take a constant time, with 870 long and 512 short pairs.

The total time is O(WH+nq)O(W H + n q), and the space is O(WH)O(W H) for the layers and O(n)O(n) words for the descriptors, 64 bytes each. The paper reports that BRISK is much faster than SURF while matching about as well on its benchmarks.

Properties

  • Scale invariant. The keypoint scale comes from the maximum of the FAST score over the layers, and the pattern scales with tt.
  • Rotation invariant. The pattern turns by α\alpha, which is the direction of the mean gradient over the long pairs.
  • Contrast. The bits compare two smoothed values, so a positive gain does not change them, and a constant offset changes none of the exact comparisons, only the rounding.
  • Fixed pattern. There is no learning. The pattern is designed by hand, with dense short pairs near the center for the bits and long pairs across the whole pattern for the orientation.
  • Binary. 512 bits are 64 bytes; the Hamming distance takes 8 XOR and popcount operations.

Variants and improvements

  • AGAST. Mair and his coauthors build the segment test as a decision tree that adapts to the image, which is faster than FAST and gives the same corners.
  • SU-BRISK. A single-scale, upright form skips the scale space and the orientation, for speed when the camera does not turn or zoom.
  • FREAK. Alahi, Ortiz and Vandergheynst use a retina-like pattern with more points near the center, learn the pairs, and compare the descriptor from coarse to fine.
  • ORB. ORB gets its orientation from the intensity centroid and learns its tests; it is the more common choice today.

When to use it

Use BRISK for fast matching with binary descriptors when scale changes matter, for example in visual odometry with zoom or in mapping with large changes of distance. ORB is more common and usually just as good; SIFT and learned features such as SuperPoint match better when there is time.

Pitfalls

  • The units of the thresholds. The paper's 9.75t9.75 t and 13.67t13.67 t belong to the paper's pattern units; with the OpenCV radii above, the same split into 512 and 870 pairs comes from 5.85t5.85 t and 8.2t8.2 t. Mixing the two gives a wrong number of bits.
  • Plateaus of the score. At the corner of a sharp square, several pixels have the same FAST score. Without a rule for ties, a strict maximum test finds no keypoint at all.
  • Smoothing size. Without smoothing, aliasing on the outer rings makes the bits unstable; with too much, neighboring points read the same value.
  • Border. The outer ring at scale tt with its smoothing reaches about 16t16 t pixels; points nearer to the border have no descriptor.
  • Gradient on flat patches. When gg is near 0 the orientation is unstable, and so are the bits.

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.

brisk_features.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/brisk-features/. The authors are listed in prov/7MW0CV.jsonl.

"""BRISK: binary robust invariant scalable keypoints (Leutenegger, Chli and Siegwart, 2011).

An image is a list of H rows of W numbers; pixel (u, v) is img[v][u], with u
the column (to the right) and v the row (down). Angles are atan2(dv, du).

Detector (simplified, see the page): layers c_0, d_0, c_1, d_1, ... with the
scales 1, 1.5, 2, 3, 4, 6, ...; on each layer the FAST 9-16 score s, the
largest threshold for which the pixel is still a corner. A keypoint is a point
with s above a threshold that is larger than its 8 neighbors and than the
scores of the layers above and below near the same place; its scale is refined
by a parabola through the three scores.

Descriptor: the pattern of 60 points on rings with the radii
0.85 (0, 2.9, 4.9, 7.4, 10.8) and the counts 1, 10, 14, 15, 20, scaled by the
keypoint scale t. Each point is sampled with a Gaussian of sigma about
1.3 r sin(pi / n) for its ring, our choice in the spirit of the paper (sigma
grows with the spacing of the points). Short pairs (distance < 5.85 t) give
the 512 bits, long pairs (distance > 8.2 t) give the local gradient and so the
orientation. These two thresholds are the values of the OpenCV pattern; the
paper gives 9.75 t and 13.67 t in its own units.
"""

import math
from typing import List, Sequence, Tuple

Image = Sequence[Sequence[float]]

RADII = tuple(0.85 * r for r in (0.0, 2.9, 4.9, 7.4, 10.8))
COUNTS = (1, 10, 14, 15, 20)
D_MAX = 5.85
D_MIN = 8.2
OFFSETS = [(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)]


def pattern() -> List[Tuple[float, float, float]]:
    """The 60 points (x, y, sigma) of the pattern at scale 1."""
    pts = []
    for r, n in zip(RADII, COUNTS):
        sigma = 0.5 if n == 1 else 1.3 * r * math.sin(math.pi / n)
        for k in range(n):
            a = 2 * math.pi * k / n
            pts.append((r * math.cos(a), r * math.sin(a), sigma))
    return pts


def pairs(pts=None):
    """(short pairs, long pairs) as lists of index pairs (i, j) with i < j."""
    pts = pts or pattern()
    short, long_ = [], []
    for i in range(len(pts)):
        for j in range(i + 1, len(pts)):
            d = math.hypot(pts[j][0] - pts[i][0], pts[j][1] - pts[i][1])
            if d < D_MAX:
                short.append((i, j))
            elif d > D_MIN:
                long_.append((i, j))
    return short, long_


SHORT, LONG = pairs()


def sample(img: Image, x: float, y: float, sigma: float) -> float:
    """Gaussian weighted mean of the pixels within 3 sigma (at least 1) of (x, y)."""
    h, w = len(img), len(img[0])
    rad = max(1.0, 3.0 * sigma)
    num = den = 0.0
    for v in range(max(0, math.ceil(y - rad)), min(h - 1, math.floor(y + rad)) + 1):
        for u in range(max(0, math.ceil(x - rad)), min(w - 1, math.floor(x + rad)) + 1):
            d2 = (u - x) ** 2 + (v - y) ** 2
            if d2 <= rad * rad:
                wt = math.exp(-d2 / (2 * sigma * sigma))
                num += wt * img[v][u]
                den += wt
    return num / den


def sample_pattern(img: Image, u: float, v: float, t: float, alpha: float = 0.0) -> List[float]:
    """The smoothed intensities of the pattern at (u, v), scale t, turned by alpha."""
    c, s = math.cos(alpha), math.sin(alpha)
    return [sample(img, u + t * (c * x - s * y), v + t * (s * x + c * y), t * sg)  # @line L3
            for x, y, sg in pattern()]


def orientation(img: Image, u: float, v: float, t: float) -> float:
    """alpha = atan2(g_y, g_x), g the mean local gradient over the long pairs."""
    pts = pattern()
    vals = sample_pattern(img, u, v, t)
    gx = gy = 0.0
    for i, j in LONG:
        dx, dy = t * (pts[j][0] - pts[i][0]), t * (pts[j][1] - pts[i][1])
        k = (vals[j] - vals[i]) / (dx * dx + dy * dy)
        gx += dx * k
        gy += dy * k  # @line L4
    return math.atan2(gy / len(LONG), gx / len(LONG))  # @line L5


def describe(img: Image, u: float, v: float, t: float, alpha: float) -> int:
    """The 512-bit descriptor: bit k is 1 when I(p_j) > I(p_i) for the short pair k."""
    vals = sample_pattern(img, u, v, t, alpha)  # @line L6
    d = 0
    for k, (i, j) in enumerate(SHORT):
        if vals[j] > vals[i]:
            d |= 1 << k  # @line L7
    return d


def fast_score(img: Image, u: int, v: int) -> float:
    """The FAST 9-16 score: the pixel is a corner for a threshold t exactly when t < score."""
    p = img[v][u]
    ring = [img[v + dv][u + du] - p for du, dv in OFFSETS]
    ring += ring[:8]
    neg = [-x for x in ring]
    best = 0.0
    for j in range(16):
        best = max(best, min(ring[j:j + 9]), min(neg[j:j + 9]))
    return best


def is_corner(img: Image, u: int, v: int, t: float) -> bool:
    p = img[v][u]
    for sign in (1, -1):
        run = 0
        for k in range(32):
            q = img[v + OFFSETS[k % 16][1]][u + OFFSETS[k % 16][0]]
            run = run + 1 if sign * (q - p) > t else 0
            if run >= 9:
                return True
    return False


def downsample(img: Image, factor: float) -> List[List[float]]:
    """Mean of the source area of each target pixel (box filter), by factor 2 or 1.5."""
    h, w = len(img), len(img[0])
    nh, nw = int(h / factor), int(w / factor)
    out = []
    for v in range(nh):
        y0, y1 = v * factor, (v + 1) * factor
        row = []
        for u in range(nw):
            x0, x1 = u * factor, (u + 1) * factor
            num = 0.0
            for yy in range(int(y0), min(h, math.ceil(y1))):
                wy = min(y1, yy + 1) - max(y0, yy)
                for xx in range(int(x0), min(w, math.ceil(x1))):
                    wx = min(x1, xx + 1) - max(x0, xx)
                    num += wy * wx * img[yy][xx]
            row.append(num / (factor * factor))
        out.append(row)
    return out


def layers(img: Image, n: int = 4):
    """The layers c_0, d_0, c_1, d_1, ... with their scales 1, 1.5, 2, 3, ..."""
    out = []
    c, d = [list(map(float, row)) for row in img], downsample(img, 1.5)
    scale = 1.0
    while len(out) < n:
        out.append((c, scale))
        if len(out) < n:
            out.append((d, 1.5 * scale))
        c, d = downsample(c, 2.0), downsample(d, 2.0)
        scale *= 2.0
        if len(c) < 8 or len(c[0]) < 8:
            break
    return out


def detect(img: Image, threshold: float = 20.0, n_layers: int = 4, margin: int = 3):
    """Keypoints (u, v, t, score) in the coordinates of img."""
    ls = layers(img, n_layers)
    maps = []
    for lay, _ in ls:
        h, w = len(lay), len(lay[0])
        maps.append([[fast_score(lay, u, v) if 3 <= u < w - 3 and 3 <= v < h - 3 else 0.0
                      for u in range(w)] for v in range(h)])  # @line L1

    def score_near(k, x, y):
        """The largest score of layer k in the 3 x 3 pixels around the image point (x, y)."""
        m, sc = maps[k], ls[k][1]
        cu, cv = int(round((x + 0.5) / sc - 0.5)), int(round((y + 0.5) / sc - 0.5))
        best = 0.0
        for v in range(cv - 1, cv + 2):
            for u in range(cu - 1, cu + 2):
                if 0 <= v < len(m) and 0 <= u < len(m[0]):
                    best = max(best, m[v][u])
        return best

    out = []
    for k, (lay, sc) in enumerate(ls):
        m = maps[k]
        h, w = len(m), len(m[0])
        for v in range(margin, h - margin):
            for u in range(margin, w - margin):
                s = m[v][u]
                if s <= threshold:
                    continue
                # A neighbor with the same score wins when it comes first in raster order.
                if any(m[v + dv][u + du] > s or (m[v + dv][u + du] == s and (dv, du) < (0, 0))
                       for du in (-1, 0, 1) for dv in (-1, 0, 1) if du or dv):
                    continue
                x, y = (u + 0.5) * sc - 0.5, (v + 0.5) * sc - 0.5
                below = score_near(k - 1, x, y) if k > 0 else 0.0
                above = score_near(k + 1, x, y) if k + 1 < len(ls) else 0.0
                if below > s or above > s:
                    continue
                # Vertex of the parabola through (lo, below), (mid, s), (hi, above) in log scale.
                # A missing layer counts as score 0 at the scale 1.5 times smaller or larger.
                mid = math.log(sc)
                lo = math.log(ls[k - 1][1]) if k > 0 else mid - math.log(1.5)
                hi = math.log(ls[k + 1][1]) if k + 1 < len(ls) else mid + math.log(1.5)
                num = (mid - lo) ** 2 * (s - above) - (mid - hi) ** 2 * (s - below)
                den = (mid - lo) * (s - above) - (mid - hi) * (s - below)
                best = min(max(mid - 0.5 * num / den, lo), hi) if den > 0 else mid
                out.append((x, y, math.exp(best), s))  # @line L2
    return out


def brisk(img: Image, threshold: float = 20.0, n_layers: int = 4):
    """Keypoints (u, v, t, alpha) with their 512-bit descriptors; points too near the border are skipped."""
    h, w = len(img), len(img[0])
    out = []
    for u, v, t, _ in detect(img, threshold, n_layers):
        reach = t * (RADII[-1] + 3 * 1.3 * RADII[-1] * math.sin(math.pi / COUNTS[-1])) + 1
        if u - reach < 0 or v - reach < 0 or u + reach > w - 1 or v + reach > h - 1:
            continue
        alpha = orientation(img, u, v, t)
        out.append(((u, v, t, alpha), describe(img, u, v, t, alpha)))
    return out  # @line L8


def hamming(a: int, b: int) -> int:
    return (a ^ b).bit_count()
test_brisk_features.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/brisk-features/. The authors are listed in prov/7MW0CV.jsonl.

import math
import random

from brisk_features import (LONG, SHORT, brisk, describe, detect, downsample, fast_score, hamming, is_corner,
                            orientation, pattern, sample)


def blob_image(seed, n=30):
    rng = random.Random(seed)
    bl = [(rng.uniform(5, 59), rng.uniform(5, 59), 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(64)] for v in range(64)]


def test_pattern_and_pairs():
    pts = pattern()
    assert len(pts) == 60
    assert len(SHORT) == 512 and len(LONG) == 870
    assert len(SHORT) + len(LONG) < 60 * 59 // 2 == 1770
    radii = sorted({round(math.hypot(x, y), 9) for x, y, _ in pts})
    assert radii == [round(0.85 * r, 9) for r in (0.0, 2.9, 4.9, 7.4, 10.8)]
    for i, j in SHORT:
        assert math.dist(pts[i][:2], pts[j][:2]) < 5.85
    for i, j in LONG:
        assert math.dist(pts[i][:2], pts[j][:2]) > 8.2


def test_fast_score_is_the_largest_threshold():
    rng = random.Random(1)
    img = [[rng.choice((0, 40, 80, 120, 160, 200)) + rng.randint(0, 9) for _ in range(16)] for _ in range(16)]
    for v in range(3, 13):
        for u in range(3, 13):
            s = fast_score(img, u, v)
            for t in range(0, 220, 7):
                assert is_corner(img, u, v, t) == (t < s)
            if s > 0:
                assert is_corner(img, u, v, s - 0.5) and not is_corner(img, u, v, s)


def test_sampling_and_downsampling():
    flat = [[77] * 20 for _ in range(20)]
    assert abs(sample(flat, 9.3, 10.7, 1.4) - 77) < 1e-12
    rng = random.Random(2)
    img = [[rng.randint(0, 255) for _ in range(12)] for _ in range(12)]
    half = downsample(img, 2.0)
    for v in range(6):
        for u in range(6):
            want = (img[2 * v][2 * u] + img[2 * v][2 * u + 1] + img[2 * v + 1][2 * u] + img[2 * v + 1][2 * u + 1]) / 4
            assert abs(half[v][u] - want) < 1e-12
    third = downsample(img, 1.5)
    assert len(third) == 8
    assert abs(sum(map(sum, third)) * 2.25 - sum(map(sum, img))) < 1e-6


def test_ramp_orientation():
    ramp = [[3 * u + 2 * v for u in range(64)] for v in range(64)]
    assert abs(orientation(ramp, 32, 32, 1.0) - math.atan2(2, 3)) < math.radians(1)
    ramp = [[-u + 4 * v for u in range(64)] for v in range(64)]
    assert abs(orientation(ramp, 31.5, 30.0, 1.5) - math.atan2(4, -1)) < math.radians(1)


def test_gain_offset_and_length():
    img = blob_image(3)
    a = describe(img, 32, 31, 1.3, 0.4)
    assert a < 1 << 512
    assert describe([[2 * x for x in row] for row in img], 32, 31, 1.3, 0.4) == a
    assert hamming(describe([[x + 50 for x in row] for row in img], 32, 31, 1.3, 0.4), a) <= 3
    assert orientation([[2 * x for x in row] for row in img], 32, 31, 1.3) == orientation(img, 32, 31, 1.3)


def test_rotation_by_90_degrees():
    img = blob_image(7)
    rot = [[img[63 - u][v] for u in range(64)] for v in range(64)]
    for u, v, t in [(32, 32, 1.2), (30, 28, 1.5), (35, 33, 1.0)]:
        a1 = orientation(img, u, v, t)
        a2 = orientation(rot, 63 - v, u, t)
        diff = (a2 - a1 - math.pi / 2 + math.pi) % (2 * math.pi) - math.pi
        assert abs(diff) < math.radians(5)
        d1, d2 = describe(img, u, v, t, a1), describe(rot, 63 - v, u, t, a2)
        d3 = describe(img, u + 5, v - 4, t, orientation(img, u + 5, v - 4, t))
        assert hamming(d1, d2) < 40 < hamming(d1, d3)


def test_square_corners_are_found():
    img = [[200 if 20 <= u < 44 and 20 <= v < 44 else 30 for u in range(64)] for v in range(64)]
    kps = detect(img, threshold=20)
    for cu, cv in [(20, 20), (43, 20), (20, 43), (43, 43)]:
        assert any(abs(x - cu) <= 3 and abs(y - cv) <= 3 for x, y, _, _ in kps)
    for x, y, t, s in kps:
        assert s > 20 and 1.0 / 1.5 <= t <= 4.0
    out = brisk(img, threshold=20)
    assert len(out) == 4
    for (x, y, t, alpha), d in out:
        # The orientation points into the bright square.
        cx, cy = 31.5 - x, 31.5 - y
        diff = (alpha - math.atan2(cy, cx) + math.pi) % (2 * math.pi) - math.pi
        assert abs(diff) < math.radians(20)


def test_hamming():
    rng = random.Random(9)
    for _ in range(50):
        a, b = rng.getrandbits(512), rng.getrandbits(512)
        assert hamming(a, b) == sum(((a >> i) & 1) != ((b >> i) & 1) for i in range(512))

History

Leutenegger, Chli and Siegwart, at ETH Zurich, presented BRISK at ICCV 2011, the same conference where Rublee and his coauthors presented ORB. BRISK joined the AGAST corner test of Mair and his coauthors (2010) with a scale space search for the FAST score and a binary descriptor in the spirit of BRIEF, with a fixed pattern of rings. FREAK followed in 2012 with a retina-like pattern. BRISK is in OpenCV and was used in visual-inertial odometry, for example in the OKVIS system of Leutenegger and his coauthors.

References

  1. Stefan Leutenegger, Margarita Chli and Roland Y. Siegwart, BRISK, binary robust invariant scalable keypoints, IEEE International Conference on Computer Vision (ICCV), 2548-2555, 2011, the section on scale-space keypoint detection (octaves and intra-octaves, the FAST 9-16 score, the FAST 5-8 mask for the layer below c0, the fits in position and scale) and the section on keypoint description (the sampling pattern, short and long pairs, the gradient, the 512 bits)
  2. Elmar Mair, Gregory D. Hager, Darius Burschka, Michael Suppa and Gerhard Hirzinger, Adaptive and generic corner detection based on the accelerated segment test, European Conference on Computer Vision (ECCV), Lecture Notes in Computer Science 6312, 183-196, 2010, the whole paper (AGAST, the segment test with an adaptive decision tree)
  3. 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
  4. Alexandre Alahi, Raphael Ortiz and Pierre Vandergheynst, FREAK, fast retina keypoint, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 510-517, 2012, the whole paper (a retina-like pattern in the style of BRISK, orientation from symmetric pairs)

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example