Algorithm Search⌘K

Algorithmcore

Speeded up robust features

Also called SURF.

A scale-invariant detector and descriptor that approximates Hessian filters and Haar wavelet responses with box filters on an integral image.

Time
O(W H + n) 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
Properties
deterministicnot exactheuristicrotation invariantscale invariant
Origin
Herbert Bay, Tinne Tuytelaars, Luc Van Gool, 2006

Speeded up robust features (SURF) find keypoints in an image and describe each one by 64 numbers. The detector looks for blobs, at the maxima of the determinant of the Hessian over space and scale, like the determinant of Hessian detector. The trick is that SURF replaces the Gaussian second derivatives by box filters, sums over rectangles that an integral image gives in four lookups. So each filter costs the same at every scale, and SURF never builds an image pyramid. The descriptor sums Haar wavelet responses, also box filters, over a grid of 4×44 \times 4 squares around the keypoint, turned to a dominant direction. Bay, Tuytelaars and Van Gool designed SURF in 2006 as a faster relative of SIFT with a shorter descriptor.

In plain words

A blob is a small bright spot on a dark ground, or a dark spot on a bright ground. To find blobs of every size, SURF slides patterns of black and white rectangles over the image, a small pattern for small blobs and larger ones for large blobs. A table of running sums gives the sum of any rectangle with four reads, so a large pattern costs no more than a small one. Where the pattern answers more strongly than at all nearby places and sizes, SURF puts a keypoint. Around each keypoint it measures how the brightness changes to the right and downward, finds the main direction of the change, and turns a square grid to that direction. In each of 16 squares it adds up the changes and their sizes. The 64 sums, scaled to length 1, describe the keypoint.

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 (to the right) and vv the row (down), and angles are measured from the uu axis toward the vv axis. The output is a set of keypoints (u,v,s,θ)(u, v, s, \theta), with a position, a scale ss and an orientation θ\theta, each with a vector of 64 values. The goal, as for SIFT, is that the same scene point in two views gives a keypoint in both, at corresponding positions and scales, with descriptors that are near in the Euclidean distance, which is the input to feature matching.

Box Hessian. The Hessian of the image smoothed at scale σ\sigma has the entries LuuL_{uu}, LvvL_{vv} and LuvL_{uv}. SURF approximates them by box filters DuuD_{uu}, DvvD_{vv} and DuvD_{uv} of odd size LL. For L=9L = 9 the filter DvvD_{vv} has three lobes, each 5 pixels wide and 3 pixels high, with the weights +1,−2,+1+1, -2, +1 along vv; DuuD_{uu} is the same filter turned by 90 degrees; and DuvD_{uv} has four squares of 3×33 \times 3 pixels with the weights +1+1 and −1-1, with a gap of one pixel between them. In general a lobe is l0=L/3l_0 = L / 3 pixels long and 2l0−12 l_0 - 1 pixels wide. The filter of size 9 matches a Gaussian with σ=1.2\sigma = 1.2, and a filter of size LL matches the scale s=1.2L/9s = 1.2 L / 9. Each response is divided by L2L^2, so that responses at different sizes can be compared. The blob response is

det⁡(Happrox)=DuuDvv−(0.9 Duv)2.\det(\mathcal{H}_{\text{approx}}) = D_{uu} D_{vv} - (0.9\, D_{uv})^2 .

The weight 0.90.9 corrects for the box shapes: it is the ratio ∥Luv(1.2)∥F∥Dvv(9)∥F/(∥Lvv(1.2)∥F∥Duv(9)∥F)≈0.912\lVert L_{uv}(1.2) \rVert_F \lVert D_{vv}(9) \rVert_F / (\lVert L_{vv}(1.2) \rVert_F \lVert D_{uv}(9) \rVert_F) \approx 0.912 of the Frobenius norms of the kernels.

Octaves. The first octave uses the sizes 9,15,21,279, 15, 21, 27. Each next octave doubles the step between the sizes and the sampling step in the image: 15,27,39,5115, 27, 39, 51 with a step of 2 pixels, then 27,51,75,9927, 51, 75, 99 with a step of 4 pixels.

The algorithm

  1. SURF(I)
  2. 1S ← the integral image of I
  3. 2for each octave, each filter size L and each sampled pixel (u, v), compute D_uu, D_vv, D_uv by box sums from S, divided by L^2
  4. 3d(u, v, L) ← D_uu D_vv - (0.9 D_uv)^2
  5. 4keep (u, v, L) if d > the threshold and d is larger than its 26 neighbors in (u, v, L); refine (u, v, L) by a quadratic fit; s ← 1.2 L / 9
  6. 5for each keypoint, take the Haar responses (dx, dy) of size 4s at the points of step s within a radius of 6s, weighted by a Gaussian with σ = 2.5s
  7. 6θ ← the direction of the largest sum of the responses whose angles lie in a window of π/3
  8. 7turn a square of side 20s to θ; in each of its 4 × 4 subregions, sum dx, dy, |dx| and |dy| of 5 × 5 Haar responses of size 2s, taken in the turned frame and weighted by a Gaussian with σ = 3.3s
  9. 8return the keypoints with their 64 sums, each vector divided by its length

The Haar response dxdx of size hh is the sum of an h×hh \times h square on the right half minus the left half, and dydy the bottom half minus the top half. Each is two box sums. In line L7 the responses are taken with the axes of the image at the turned sample points and then turned into the frame of the keypoint, as Bay and his coauthors do; this is cheaper than turning the wavelets.

The sign of Duu+DvvD_{uu} + D_{vv}, the sign of the Laplacian, tells bright blobs on a dark ground from dark blobs on a bright ground. SURF stores it with each keypoint, and a matcher compares only keypoints with the same sign.

Example

A disk. A 64×6464 \times 64 image is 20 everywhere except a disk of radius 5 at (32,30)(32, 30) with the value 200. At the center, the filter of size 9 lies inside the disk, on a constant region, so all its responses are 0. The larger filters give d=2007.0d = 2007.0 for L=15L = 15, 2165.12165.1 for L=21L = 21 and 1483.71483.7 for L=27L = 27, so the response peaks at L=21L = 21, the middle layers of the first octave. This point is a maximum among its 26 neighbors, and the quadratic fit gives the scale s≈2.55s \approx 2.55, close to the scale 5/2≈3.55 / \sqrt{2} \approx 3.5 at which a Gaussian blob detector answers most strongly to a disk of radius 5. The sum Duu+DvvD_{uu} + D_{vv} is negative, so the sign of the Laplacian marks a bright blob. With the threshold 1, the detector also returns four much weaker points on the diagonals, about 11 pixels from the center, with a positive Laplacian; there, the dark ground next to the disk looks like a dark blob to the large filters.

A ramp. On the image I(u,v)=3u+2vI(u, v) = 3u + 2v, every Haar response of size hh is (3,2)(3, 2) times the same positive number, so every window that contains any response gives a sum in the direction (3,2)(3, 2), and θ=atan2⁡(2,3)≈33.7°\theta = \operatorname{atan2}(2, 3) \approx 33.7°.

The weight 0.9. With the Gaussian σ=1.2\sigma = 1.2 sampled on the 9×99 \times 9 grid, the ratio of the Frobenius norms above is 0.91270.9127, which Bay and his coauthors round to 0.90.9.

Correctness

SURF is a heuristic; its claim of repeatability under changes of view is a benchmark result, not a theorem. The proof in proofs/correctness.md shows what the code computes:

  • Each box sum from the integral image equals the sum of the pixels in the box, and the decomposition of each box filter into one or two large boxes equals the filter mask.
  • Transposing the image swaps DuuD_{uu} and DvvD_{vv} and keeps DuvD_{uv}, so the determinant map is transposed exactly. This is the discrete form of rotation invariance by 90 degrees.
  • Line L4 returns exactly the strict local maxima above the threshold.
  • On a ramp, the orientation is the direction of the ramp. Away from the border, the descriptor does not change when a constant is added to the image, has length 1, and does not change when the image is multiplied by a positive constant.
Proof: Correctness of SURFfull

Let II be an image with WW columns and HH rows, extended by 0 outside. The integral image is S(u,v)=∑u′<u,v′<vI(u′,v′)S(u, v) = \sum_{u' < u, v' < v} I(u', v') for 0≤u≤W0 \le u \le W and 0≤v≤H0 \le v \le H. For a box R=[u0,u1)×[v0,v1)R = [u_0, u_1) \times [v_0, v_1) write Σ(R)\Sigma(R) for the sum of II over RR.

Lemma 1 (box sums). For 0≤u0≤u1≤W0 \le u_0 \le u_1 \le W and 0≤v0≤v1≤H0 \le v_0 \le v_1 \le H, Σ(R)=S(u1,v1)−S(u0,v1)−S(u1,v0)+S(u0,v0)\Sigma(R) = S(u_1, v_1) - S(u_0, v_1) - S(u_1, v_0) + S(u_0, v_0). For any box, Σ(R)\Sigma(R) equals the same formula applied to RR clipped to the image.

Proof. The construction gives S(u+1,v+1)=S(u+1,v)+∑u′≤uI(u′,v)S(u + 1, v + 1) = S(u + 1, v) + \sum_{u' \le u} I(u', v), so by induction on vv, SS is the sum over u′<uu' < u, v′<vv' < v. In the formula, a pixel with u′<u0u' < u_0 or v′<v0v' < v_0 is counted in S(u1,v1)S(u_1, v_1) and in exactly one or in all three of the other terms with signs that cancel: if u′<u0u' < u_0 and v0≤v′<v1v_0 \le v' < v_1 it is in S(u1,v1)S(u_1, v_1) and S(u0,v1)S(u_0, v_1); if u′<u0u' < u_0 and v′<v0v' < v_0 it is in all four, with the signs +,−,−,++, -, -, +. The case v′<v0v' < v_0, u0≤u′<u1u_0 \le u' < u_1 is symmetric. A pixel in RR is only in S(u1,v1)S(u_1, v_1). So the formula is Σ(R)\Sigma(R). Pixels outside the image are 0, so clipping RR to the image does not change Σ(R)\Sigma(R). □\square

Lemma 2 (box filters). For an odd size L=3l0L = 3 l_0, the values computed in line L2 equal the correlation of II at (u,v)(u, v) with the masks defined on the page, divided by L2L^2.

Proof. For DuuD_{uu}, let AA be the box of all three lobes, u−L−12≤u′≤u+L−12u - \frac{L - 1}{2} \le u' \le u + \frac{L - 1}{2} and ∣v′−v∣≤l0−1|v' - v| \le l_0 - 1, and MM the middle lobe, ∣u′−u∣≤l0−12|u' - u| \le \frac{l_0 - 1}{2} with the same rows. Since L=3l0L = 3 l_0, AA is the union of three lobes of width l0l_0 each, and MM is the middle one. So Σ(A)−3Σ(M)\Sigma(A) - 3 \Sigma(M) gives each pixel of the outer lobes the weight +1+1 and each pixel of MM the weight 1−3=−21 - 3 = -2, which is the mask. DvvD_{vv} is the same with uu and vv swapped. DuvD_{uv} is the sum of four boxes of l0×l0l_0 \times l_0 pixels with the weights +1,−1,−1,+1+1, -1, -1, +1, which is the mask by definition. By Lemma 1 each box sum is correct, and the code divides by L2L^2. □\square

Lemma 3 (transpose). Let IT(u,v)=I(v,u)I^T(u, v) = I(v, u) be the transposed image. Then Duu[IT](v,u)=Dvv[I](u,v)D_{uu}[I^T](v, u) = D_{vv}[I](u, v), Dvv[IT](v,u)=Duu[I](u,v)D_{vv}[I^T](v, u) = D_{uu}[I](u, v) and Duv[IT](v,u)=Duv[I](u,v)D_{uv}[I^T](v, u) = D_{uv}[I](u, v), so the determinant maps satisfy d[IT](v,u,L)=d[I](u,v,L)d[I^T](v, u, L) = d[I](u, v, L).

Proof. The mask of DvvD_{vv} is the transpose of the mask of DuuD_{uu}, and the mask of DuvD_{uv} is its own transpose: the weight of the offset (δu,δv)(\delta_u, \delta_v) is +1+1 when δuδv>0\delta_u \delta_v > 0 and −1-1 when δuδv<0\delta_u \delta_v < 0, which is symmetric in the two offsets. Correlating ITI^T with a mask at (v,u)(v, u) equals correlating II with the transposed mask at (u,v)(u, v). By Lemma 2 the computed values are the correlations. The determinant DuuDvv−(0.9Duv)2D_{uu} D_{vv} - (0.9 D_{uv})^2 is symmetric in DuuD_{uu} and DvvD_{vv}. □\square

The integer box sums are exact, and the same division by L2L^2 is applied, so the equality holds exactly in floating point too.

Lemma 4 (local maxima). Line L4 keeps a sample (u,v,L)(u, v, L) of a middle layer if and only if d(u,v,L)d(u, v, L) is larger than the threshold and larger than each of its 26 neighbors in the 3×3×33 \times 3 \times 3 block of samples of its octave.

Proof. The code skips a sample if dd is at most the threshold, or if some neighbor has d′≥dd' \ge d. So it keeps exactly the samples with dd above the threshold and d>d′d > d' for all 26 neighbors. The middle layers and the inner samples have all 26 neighbors in the octave, so no neighbor is missing. The quadratic fit only moves the kept point and does not add or remove points. □\square

Lemma 5 (Haar responses). Let dxdx and dydy be the Haar responses of size hh at a point whose boxes lie inside the image. Adding a constant aa to II does not change them, and multiplying II by c>0c > 0 multiplies them by cc. On the ramp I(u,v)=αu+βvI(u, v) = \alpha u + \beta v, (dx,dy)=κ(α,β)(dx, dy) = \kappa (\alpha, \beta) with κ=h3/4>0\kappa = h^3 / 4 > 0, the same for every point.

Proof. Each response is the difference of two boxes with the same number of pixels, so a constant cancels, and both terms scale with cc. On the ramp, let r=h/2r = h / 2. The response dxdx pairs each pixel (u′,v′)(u', v') of the left half with the pixel (u′+r,v′)(u' + r, v') of the right half. Each pair differs by αr\alpha r, and there are rr pairs in each of the hh rows, so dx=αr⋅rh=αh3/4dx = \alpha r \cdot r h = \alpha h^3 / 4. In the same way dy=βh3/4dy = \beta h^3 / 4. □\square

Lemma 6 (orientation on a ramp). If all Haar responses within the radius 6s6s lie inside the image and (α,β)≠0(\alpha, \beta) \ne 0, line L6 returns θ=atan2⁡(β,α)\theta = \operatorname{atan2}(\beta, \alpha).

Proof. By Lemma 5 each weighted response is gkκ(α,β)g_k \kappa (\alpha, \beta) with gk>0g_k > 0, so all of them have the angle atan2⁡(β,α)\operatorname{atan2}(\beta, \alpha). Every window centered at the angle of a response contains all responses, so every window sum is a positive multiple of (α,β)(\alpha, \beta), and the longest one has this direction too. □\square

Theorem. SURF returns as keypoints exactly the samples of the middle layers that are strict local maxima of the box determinant above the threshold, refined by the quadratic fit. The determinant map of the transposed image is the transposed map. For a keypoint whose descriptor window lies inside the image, the descriptor has length 1 (unless all its responses are 0) and does not change when a constant is added to the image or when the image is multiplied by c>0c > 0.

Proof. Lines L1 to L3 compute the determinant by Lemmas 1 and 2, and line L4 keeps the maxima by Lemma 4. Lemma 3 gives the transpose property. In line L7 each turned response is a linear function of (dx,dy)(dx, dy), so by Lemma 5 adding a constant keeps all 64 sums and multiplying by cc multiplies all of them by cc; the orientation of line L6 depends only on the directions and the relative lengths of the sums, so it does not change either. Line L8 divides by the length, which gives length 1 and removes the factor cc. □\square

Complexity

The model is the real RAM.

  • Line L1 takes O(WH)O(W H) time.
  • Lines L2 to L4 take O(1)O(1) time per sample, since each box sum takes four reads, whatever the filter size. The first octave has 4WH4 W H samples, and each next octave has a quarter as many, so the detector takes O(WH)O(W H) time for any number of octaves.
  • Lines L5 to L7 take O(1)O(1) time per keypoint, with 109 samples for the orientation and 400 for the descriptor, each a few box sums. The sliding window over the orientations takes O(1)O(1) time for a fixed number of samples.

The total time is O(WH+n)O(W H + n) and the space is O(WH+n)O(W H + n). Because the integral image makes the cost of a filter independent of its size, large scales cost no more than small ones. This is the main source of the speed of SURF over SIFT, which smooths the image with ever larger Gaussians.

Properties

  • Scale invariant. The keypoint scale follows the blob size, and the sampling grid of the orientation and the descriptor scales with ss.
  • Rotation invariant. The descriptor is turned to θ\theta. The upright form U-SURF skips the orientation and is faster and more distinctive when the camera stays upright.
  • Contrast invariant. The Haar responses do not change when a constant is added, and the final division removes a gain.
  • Approximate. The box filters approximate Gaussian derivatives; they are not rotation invariant at angles other than multiples of 90 degrees, and the responses of the box filters are not exactly scale normalized.
  • Short descriptor. 64 values, against 128 for SIFT, make the matching faster.

Variants and improvements

  • U-SURF. The upright form sets θ=0\theta = 0. Bay and his coauthors report that it is faster and works well for rotations up to about 15 degrees.
  • SURF-128. It splits the sums of dxdx and ∣dx∣|dx| by the sign of dydy, and the sums of dydy and ∣dy∣|dy| by the sign of dxdx, which gives 128 values and is more distinctive.
  • SURF-36. A 3×33 \times 3 grid of subregions gives a shorter descriptor.
  • M-SURF. The descriptor of KAZE uses overlapping subregions and two Gaussian weightings, which reduces the effects at the borders of the subregions.
  • Binary descriptors. ORB and BRISK use binary tests and the Hamming distance, and are much faster to compute and match.

When to use it

SURF is a good choice when SIFT-like float descriptors are wanted at a lower cost, for image stitching, recognition of objects and registration. SURF is patented, and OpenCV keeps it in its nonfree module, which led many users to ORB. On a phone or an embedded device, ORB is much faster: the ORB paper reports 15.3 ms for ORB, 217.3 ms for SURF and 5228.7 ms for SIFT on images of 640×480640 \times 480 pixels on one test computer. When accuracy matters more than speed, SIFT or RootSIFT often matches better; KAZE keeps edges sharper in its scale space.

Pitfalls

  • Filter size and scale. The scale is s=1.2L/9s = 1.2 L / 9, not LL. Mixing them breaks the sizes of the orientation and descriptor windows.
  • Normalization. Without the division by L2L^2, larger filters always answer more strongly, and the scale selection fails.
  • Border. A filter that leaves the image sees zeros (or copied edge pixels), and the responses near the border are not reliable. Keep the keypoints at least half the largest filter size away from the border.
  • Integer sizes. Haar sizes of 4s4s and 2s2s must be rounded to even integers, and the sample points to pixels. These roundings make the descriptor change a little under rotation, even by 90 degrees.
  • Thresholds. The threshold on the determinant depends on the range of the pixel values; a value that works for images in [0,1][0, 1] finds almost everything in [0,255][0, 255].
  • Gaussian weights. The Gaussian for the orientation has σ=2.5s\sigma = 2.5s in the ECCV paper; implementations differ in this and other small choices, so descriptors from different libraries do not match each other.

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.

surf.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/surf/. The authors are listed in prov/RH1WJP.jsonl.

"""Speeded up robust features (SURF): Fast-Hessian detector and 64-value descriptor.

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 (Bay, Tuytelaars and Van Gool): box filters of odd size L = 9, 15,
21, 27, ... approximate the second derivatives of a Gaussian with scale
s = 1.2 L / 9. Each response is divided by L^2, and the blob response is
det = Dxx Dyy - (0.9 Dxy)^2. Keypoints are local maxima over 3 x 3 x 3
neighbors in (u, v, L) above a threshold, refined by a quadratic fit.

Orientation: Haar responses of size 4s at the points of step s within a
radius of 6s, weighted by a Gaussian with sigma 2.5s; the longest sum of the
responses in a sliding window of pi/3 gives the direction.

Descriptor: a square of side 20s turned to the orientation, 4 x 4 subregions
of 5 x 5 samples; Haar responses of size 2s, weighted by a Gaussian with
sigma 3.3s, turned into the frame of the keypoint; each subregion gives
(sum dx, sum dy, sum |dx|, sum |dy|), and the 64 values are scaled to length 1.

Outside the image a box sum counts 0 (zero padding).
"""

import math
from typing import List, Optional, Sequence, Tuple

Image = Sequence[Sequence[float]]


def integral_image(img: Image) -> List[List[float]]:
    """ii[v][u] = sum of img over rows < v and columns < u."""
    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 box(ii, u0: int, v0: int, u1: int, v1: int):
    """Sum over columns u0 <= u < u1 and rows v0 <= v < v1, clipped to the image."""
    h, w = len(ii) - 1, len(ii[0]) - 1
    u0, u1 = max(0, min(w, u0)), max(0, min(w, u1))
    v0, v1 = max(0, min(h, v0)), max(0, min(h, v1))
    if u0 >= u1 or v0 >= v1:
        return 0
    return ii[v1][u1] - ii[v0][u1] - ii[v1][u0] + ii[v0][u0]


def hessian_boxes(ii, u: int, v: int, size: int) -> Tuple[float, float, float]:
    """Box filter approximations (Dxx, Dyy, Dxy) of size x size at (u, v), divided by size^2."""
    l0 = size // 3
    half = (size - 1) // 2
    # Dxx: lobes +1, -2, +1 along u, each l0 wide and 2 l0 - 1 high.
    whole = box(ii, u - half, v - l0 + 1, u + half + 1, v + l0)
    mid = box(ii, u - (l0 - 1) // 2, v - l0 + 1, u + (l0 - 1) // 2 + 1, v + l0)
    dxx = whole - 3 * mid
    whole = box(ii, u - l0 + 1, v - half, u + l0, v + half + 1)
    mid = box(ii, u - l0 + 1, v - (l0 - 1) // 2, u + l0, v + (l0 - 1) // 2 + 1)
    dyy = whole - 3 * mid
    # Dxy: four l0 x l0 squares, +1 on the top-left and bottom-right, -1 on the others.
    dxy = (box(ii, u - l0, v - l0, u, v) + box(ii, u + 1, v + 1, u + l0 + 1, v + l0 + 1)
           - box(ii, u + 1, v - l0, u + l0 + 1, v) - box(ii, u - l0, v + 1, u, v + l0 + 1))
    a = float(size * size)
    return dxx / a, dyy / a, dxy / a  # @line L2


def hessian_det(ii, u: int, v: int, size: int, w: float = 0.9) -> float:
    dxx, dyy, dxy = hessian_boxes(ii, u, v, size)
    return dxx * dyy - (w * dxy) ** 2  # @line L3


def filter_sizes(octave: int, layers: int = 4) -> List[int]:
    """Sizes 9, 15, 21, 27 for octave 0; 15, 27, 39, 51 for octave 1; and so on."""
    return [3 * ((2 ** (octave + 1)) * (i + 1) + 1) for i in range(layers)]


def _solve3(a, b):
    """Solve the 3 x 3 system a x = b by Cramer's rule; None if singular."""
    def det3(m):
        return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
                - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
                + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]))
    d = det3(a)
    if abs(d) < 1e-300:
        return None
    out = []
    for k in range(3):
        m = [row[:] for row in a]
        for i in range(3):
            m[i][k] = b[i]
        out.append(det3(m) / d)
    return out


def detect(img: Image, threshold: float = 1.0, octaves: int = 2, ii=None) -> List[Tuple[float, float, float, int]]:
    """Fast-Hessian keypoints (u, v, s, sign of the Laplacian)."""
    if ii is None:
        ii = integral_image(img)  # @line L1
    h, w = len(img), len(img[0])
    keypoints = []
    for o in range(octaves):
        sizes = filter_sizes(o)
        step = 2 ** o
        margin = (sizes[-1] - 1) // 2 + step
        us = list(range(margin, w - margin, step))
        vs = list(range(margin, h - margin, step))
        if len(us) < 3 or len(vs) < 3:
            continue
        maps = [[[hessian_det(ii, u, v, L) for u in us] for v in vs] for L in sizes]
        for k in range(1, len(sizes) - 1):
            for j in range(1, len(vs) - 1):
                for i in range(1, len(us) - 1):
                    d = maps[k][j][i]
                    if d <= threshold:
                        continue
                    if any(maps[k + dk][j + dj][i + di] >= d
                           for dk in (-1, 0, 1) for dj in (-1, 0, 1) for di in (-1, 0, 1)
                           if (dk, dj, di) != (0, 0, 0)):
                        continue  # @line L4
                    # Quadratic fit in (u, v, L) as in Brown and Lowe.
                    f = lambda dk, dj, di: maps[k + dk][j + dj][i + di]
                    g = [(f(0, 0, 1) - f(0, 0, -1)) / 2, (f(0, 1, 0) - f(0, -1, 0)) / 2,
                         (f(1, 0, 0) - f(-1, 0, 0)) / 2]
                    hxx = f(0, 0, 1) + f(0, 0, -1) - 2 * d
                    hyy = f(0, 1, 0) + f(0, -1, 0) - 2 * d
                    hss = f(1, 0, 0) + f(-1, 0, 0) - 2 * d
                    hxy = (f(0, 1, 1) - f(0, 1, -1) - f(0, -1, 1) + f(0, -1, -1)) / 4
                    hxs = (f(1, 0, 1) - f(1, 0, -1) - f(-1, 0, 1) + f(-1, 0, -1)) / 4
                    hys = (f(1, 1, 0) - f(1, -1, 0) - f(-1, 1, 0) + f(-1, -1, 0)) / 4
                    off = _solve3([[hxx, hxy, hxs], [hxy, hyy, hys], [hxs, hys, hss]], [-x for x in g])
                    if off is None or max(abs(x) for x in off) > 0.5:
                        off = [0.0, 0.0, 0.0]
                    u = us[i] + off[0] * step
                    v = vs[j] + off[1] * step
                    size = sizes[k] + off[2] * (sizes[k + 1] - sizes[k])
                    dxx, dyy, _ = hessian_boxes(ii, us[i], vs[j], sizes[k])
                    keypoints.append((u, v, 1.2 * size / 9.0, 1 if dxx + dyy >= 0 else -1))
    return keypoints


def haar(ii, u: float, v: float, size: int) -> Tuple[float, float]:
    """Haar wavelet responses (dx, dy) of side size (even) centered near (u, v)."""
    cu, cv, r = int(round(u)), int(round(v)), size // 2
    dx = box(ii, cu, cv - r, cu + r, cv + r) - box(ii, cu - r, cv - r, cu, cv + r)
    dy = box(ii, cu - r, cv, cu + r, cv + r) - box(ii, cu - r, cv - r, cu + r, cv)
    return dx, dy


def _haar_size(t: float) -> int:
    return max(2, 2 * int(round(t / 2.0)))


def orientation(ii, u: float, v: float, s: float) -> float:
    """Dominant direction of the Haar responses around (u, v) at scale s."""
    hs = _haar_size(4 * s)
    resp = []
    for j in range(-6, 7):
        for i in range(-6, 7):
            if i * i + j * j >= 36:
                continue
            g = math.exp(-(i * i + j * j) / (2 * 2.5 * 2.5))
            dx, dy = haar(ii, u + i * s, v + j * s, hs)
            if dx or dy:
                resp.append((g * dx, g * dy, math.atan2(g * dy, g * dx)))  # @line L5
    if not resp:
        return 0.0
    best, best_angle = -1.0, 0.0
    for _, _, a0 in resp:
        sx = sy = 0.0
        for dx, dy, a in resp:
            d = (a - a0 + math.pi) % (2 * math.pi) - math.pi
            if abs(d) <= math.pi / 6:
                sx += dx
                sy += dy
        n = sx * sx + sy * sy
        if n > best:
            best, best_angle = n, math.atan2(sy, sx)
    return best_angle  # @line L6


def describe(ii, u: float, v: float, s: float, theta: float = 0.0) -> List[float]:
    """The 64-value SURF descriptor of a keypoint with orientation theta (0 gives U-SURF)."""
    c, sn = math.cos(theta), math.sin(theta)
    hs = _haar_size(2 * s)
    desc = [0.0] * 64
    for l in range(20):
        for k in range(20):
            x, y = (k - 9.5) * s, (l - 9.5) * s
            pu, pv = u + c * x - sn * y, v + sn * x + c * y
            dx, dy = haar(ii, pu, pv, hs)
            g = math.exp(-((k - 9.5) ** 2 + (l - 9.5) ** 2) / (2 * 3.3 * 3.3))
            rx, ry = g * (c * dx + sn * dy), g * (-sn * dx + c * dy)
            b = 4 * (4 * (l // 5) + k // 5)
            desc[b] += rx
            desc[b + 1] += ry
            desc[b + 2] += abs(rx)
            desc[b + 3] += abs(ry)  # @line L7
    n = math.sqrt(sum(x * x for x in desc))
    return [x / n for x in desc] if n > 0 else desc  # @line L8


def surf(img: Image, threshold: float = 1.0, octaves: int = 2, upright: bool = False):
    """Detect keypoints and return a list of ((u, v, s, theta, laplacian sign), descriptor)."""
    ii = integral_image(img)
    out = []
    for u, v, s, sign in detect(img, threshold, octaves, ii):
        theta = 0.0 if upright else orientation(ii, u, v, s)
        out.append(((u, v, s, theta, sign), describe(ii, u, v, s, theta)))
    return out


def nearest(desc: List[float], others: List[List[float]]) -> Optional[int]:
    """Index of the descriptor nearest to desc in Euclidean distance."""
    best, arg = math.inf, None
    for i, o in enumerate(others):
        d = sum((a - b) ** 2 for a, b in zip(desc, o))
        if d < best:
            best, arg = d, i
    return arg
test_surf.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/surf/. The authors are listed in prov/RH1WJP.jsonl.

import math
import random

from surf import box, describe, detect, filter_sizes, hessian_boxes, hessian_det, integral_image, nearest, orientation, surf


def random_image(rng, w, h):
    return [[rng.randint(0, 255) for _ in range(w)] for _ in range(h)]


def blobs(seed, n=25):
    rng = random.Random(seed)
    bl = [(rng.uniform(10, 54), rng.uniform(10, 54), rng.uniform(2, 5), rng.uniform(-80, 80)) for _ in range(n)]
    return [[100 + 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 direct_masks(img, u, v, size):
    """The box filters from their weights, pixel by pixel, with zero padding."""
    h, w = len(img), len(img[0])
    l0, half = size // 3, (size - 1) // 2
    sxx = syy = sxy = 0
    for dv in range(-half, half + 1):
        for du in range(-half, half + 1):
            x, y = u + du, v + dv
            p = img[y][x] if 0 <= x < w and 0 <= y < h else 0
            if abs(dv) <= l0 - 1:
                sxx += p * (-2 if abs(du) <= (l0 - 1) // 2 else 1)
            if abs(du) <= l0 - 1:
                syy += p * (-2 if abs(dv) <= (l0 - 1) // 2 else 1)
            if 1 <= abs(du) <= l0 and 1 <= abs(dv) <= l0:
                sxy += p * (1 if du * dv > 0 else -1)
    a = float(size * size)
    return sxx / a, syy / a, sxy / a


def test_integral_image_box_sums():
    rng = random.Random(1)
    img = random_image(rng, 13, 9)
    ii = integral_image(img)
    for _ in range(200):
        u0, u1 = sorted(rng.randint(-3, 16) for _ in range(2))
        v0, v1 = sorted(rng.randint(-3, 12) for _ in range(2))
        want = sum(img[v][u] for v in range(max(v0, 0), min(v1, 9)) for u in range(max(u0, 0), min(u1, 13)))
        assert box(ii, u0, v0, u1, v1) == want


def test_box_filters_match_their_masks():
    rng = random.Random(2)
    img = random_image(rng, 40, 40)
    ii = integral_image(img)
    for size in (9, 15, 21, 27):
        for _ in range(6):
            u, v = rng.randint(-2, 41), rng.randint(-2, 41)
            assert hessian_boxes(ii, u, v, size) == direct_masks(img, u, v, size)


def test_filter_sizes_and_the_weight():
    assert filter_sizes(0) == [9, 15, 21, 27]
    assert filter_sizes(1) == [15, 27, 39, 51]
    assert filter_sizes(2) == [27, 51, 75, 99]
    # The weight 0.9 balances the Frobenius norms of the Gaussian and box kernels at sigma 1.2.
    s, r = 1.2, range(-4, 5)
    g = lambda x, y: math.exp(-(x * x + y * y) / (2 * s * s))
    lyy = [(y * y / s ** 4 - 1 / s ** 2) * g(x, y) for y in r for x in r]
    lxy = [(x * y / s ** 4) * g(x, y) for y in r for x in r]
    dyy = [0 if abs(x) > 2 else (-2 if abs(y) <= 1 else 1) for y in r for x in r]
    dxy = [0 if x == 0 or y == 0 or abs(x) > 3 or abs(y) > 3 else (1 if x * y > 0 else -1) for y in r for x in r]
    fro = lambda m: math.sqrt(sum(t * t for t in m))
    assert abs(fro(lxy) * fro(dyy) / (fro(lyy) * fro(dxy)) - 0.912) < 0.005


def test_transpose_keeps_the_determinant():
    rng = random.Random(3)
    img = random_image(rng, 30, 30)
    tr = [[img[u][v] for u in range(30)] for v in range(30)]
    ii, it = integral_image(img), integral_image(tr)
    for size in (9, 15, 21):
        for _ in range(10):
            u, v = rng.randint(0, 29), rng.randint(0, 29)
            assert hessian_det(ii, u, v, size) == hessian_det(it, v, u, size)


def test_bright_disk_is_detected_at_its_center():
    img = [[200 if (u - 32) ** 2 + (v - 30) ** 2 <= 25 else 20 for u in range(64)] for v in range(64)]
    kps = detect(img, threshold=1.0)
    best = min(kps, key=lambda k: (k[0] - 32) ** 2 + (k[1] - 30) ** 2)
    assert abs(best[0] - 32) <= 1 and abs(best[1] - 30) <= 1
    assert best[3] == -1  # a bright blob has a negative Laplacian
    assert 1.5 < best[2] < 4.5


def test_ramp_orientation():
    img = [[3.0 * u + 2.0 * v for u in range(64)] for v in range(64)]
    ii = integral_image(img)
    assert abs(orientation(ii, 32, 32, 2.0) - math.atan2(2.0, 3.0)) < 1e-9
    img = [[-1.0 * u + 4.0 * v for u in range(64)] for v in range(64)]
    ii = integral_image(img)
    assert abs(orientation(ii, 30, 33, 1.6) - math.atan2(4.0, -1.0)) < 1e-9


def test_descriptor_norm_offset_and_gain():
    img = blobs(4)
    ii = integral_image(img)
    d = describe(ii, 32, 32, 2.0, 0.7)
    assert len(d) == 64 and abs(sum(x * x for x in d) - 1.0) < 1e-12
    rng = random.Random(5)
    raw = random_image(rng, 64, 64)
    a = describe(integral_image(raw), 30, 31, 1.5, -1.0)
    b = describe(integral_image([[x + 40 for x in row] for row in raw]), 30, 31, 1.5, -1.0)
    c = describe(integral_image([[3 * x for x in row] for row in raw]), 30, 31, 1.5, -1.0)
    assert a == b
    assert all(abs(x - y) < 1e-12 for x, y in zip(a, c))


def test_rotation_by_90_degrees():
    img = blobs(7)
    rot = [[img[63 - u][v] for u in range(64)] for v in range(64)]
    ii, ir = integral_image(img), integral_image(rot)
    for u, v in [(32, 32), (28, 35), (36, 30), (30, 30)]:
        d1 = describe(ii, u, v, 2.0, orientation(ii, u, v, 2.0))
        # The pixel (u, v) of img is the pixel (63 - v, u) of rot.
        d2 = describe(ir, 63 - v, u, 2.0, orientation(ir, 63 - v, u, 2.0))
        d3 = describe(ii, u + 9, v - 7, 2.0, orientation(ii, u + 9, v - 7, 2.0))
        assert math.dist(d1, d2) < 0.3
        assert math.dist(d1, d2) < math.dist(d1, d3)


def test_shifted_copy_matches_itself():
    img = blobs(8)
    shifted = [[img[v - 3][u - 4] if v >= 3 and u >= 4 else 100 for u in range(64)] for v in range(64)]
    a = surf(img, threshold=5.0, octaves=1)
    b = surf(shifted, threshold=5.0, octaves=1)
    inner = [(k, d) for k, d in a if 20 <= k[0] <= 40 and 20 <= k[1] <= 40]
    assert inner
    for k, d in inner:
        j = nearest(d, [e for _, e in b])
        assert abs(b[j][0][0] - k[0] - 4) < 1e-9 and abs(b[j][0][1] - k[1] - 3) < 1e-9

History

Bay, Tuytelaars and Van Gool presented SURF at ECCV 2006, and with Ess they gave the longer journal version in 2008. They combined three known parts: the integral image that Viola and Jones had used for the Haar features of their face detector, the determinant of the Hessian as a blob measure from the scale space work of Lindeberg, and the grid of local sums of the SIFT descriptor. SURF became one of the most used local features in the late 2000s. Faster binary features such as BRIEF, ORB and BRISK followed in 2010 and 2011, and the nonlinear scale space of KAZE in 2012 used a SURF-like descriptor.

References

  1. Herbert Bay, Tinne Tuytelaars and Luc Van Gool, SURF, speeded up robust features, European Conference on Computer Vision (ECCV), Lecture Notes in Computer Science 3951, 404-417, 2006, the sections on the Fast-Hessian detector (box filters of size 9 for sigma 1.2, the weight 0.9, the filter sizes per octave) and on the descriptor (orientation within 6s, Gaussian 2.5s, the 4 x 4 subregions and the 64 values)
  2. Herbert Bay, Andreas Ess, Tinne Tuytelaars and Luc Van Gool, Speeded-up robust features (SURF), Computer Vision and Image Understanding 110(3), 346-359, 2008, the sections on interest point detection (integral images, the Hessian with box filters, the scale space, the localization) and on description and matching (orientation, the Haar sums, the sign of the Laplacian)
  3. Paul Viola and Michael Jones, Rapid object detection using a boosted cascade of simple features, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), vol. 1, 511-518, 2001, the section on the integral image
  4. David G. Lowe, Distinctive image features from scale-invariant keypoints, International Journal of Computer Vision 60(2), 91-110, 2004, Section 4 (the quadratic fit of the keypoint position and scale) and Section 6 (the SIFT descriptor that SURF follows)

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.

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