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.
- Solves
- Feature matching
- 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
- Model
- Real RAM
- Properties
- deterministicnot exactheuristicrotation invariantscale invariant
- Evidence
- Proof sketchCode in 1 languages
- 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 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 with columns and rows. A pixel is , with the column (to the right) and the row (down), and angles are measured from the axis toward the axis. The output is a set of keypoints , with a position, a scale and an orientation , 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 has the entries , and . SURF approximates them by box filters , and of odd size . For the filter has three lobes, each 5 pixels wide and 3 pixels high, with the weights along ; is the same filter turned by 90 degrees; and has four squares of pixels with the weights and , with a gap of one pixel between them. In general a lobe is pixels long and pixels wide. The filter of size 9 matches a Gaussian with , and a filter of size matches the scale . Each response is divided by , so that responses at different sizes can be compared. The blob response is
The weight corrects for the box shapes: it is the ratio of the Frobenius norms of the kernels.
Octaves. The first octave uses the sizes . Each next octave doubles the step between the sizes and the sampling step in the image: with a step of 2 pixels, then with a step of 4 pixels.
The algorithm
SURF(I)- 1
S ← the integral image of I - 2
for 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 - 3
d(u, v, L) ← D_uu D_vv - (0.9 D_uv)^2 - 4
keep (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 - 5
for 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 - 6
θ ← the direction of the largest sum of the responses whose angles lie in a window of π/3 - 7
turn 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 - 8
return the keypoints with their 64 sums, each vector divided by its length
The Haar response of size is the sum of an square on the right half minus the left half, and 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 , 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 image is 20 everywhere except a disk of radius 5 at 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 for , for and for , so the response peaks at , the middle layers of the first octave. This point is a maximum among its 26 neighbors, and the quadratic fit gives the scale , close to the scale at which a Gaussian blob detector answers most strongly to a disk of radius 5. The sum 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 , every Haar response of size is times the same positive number, so every window that contains any response gives a sum in the direction , and .
The weight 0.9. With the Gaussian sampled on the grid, the ratio of the Frobenius norms above is , which Bay and his coauthors round to .
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 and and keeps , 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 be an image with columns and rows, extended by 0 outside. The integral image is for and . For a box write for the sum of over .
Lemma 1 (box sums). For and , . For any box, equals the same formula applied to clipped to the image.
Proof. The construction gives , so by induction on , is the sum over , . In the formula, a pixel with or is counted in and in exactly one or in all three of the other terms with signs that cancel: if and it is in and ; if and it is in all four, with the signs . The case , is symmetric. A pixel in is only in . So the formula is . Pixels outside the image are 0, so clipping to the image does not change .
Lemma 2 (box filters). For an odd size , the values computed in line L2 equal the correlation of at with the masks defined on the page, divided by .
Proof. For , let be the box of all three lobes, and , and the middle lobe, with the same rows. Since , is the union of three lobes of width each, and is the middle one. So gives each pixel of the outer lobes the weight and each pixel of the weight , which is the mask. is the same with and swapped. is the sum of four boxes of pixels with the weights , which is the mask by definition. By Lemma 1 each box sum is correct, and the code divides by .
Lemma 3 (transpose). Let be the transposed image. Then , and , so the determinant maps satisfy .
Proof. The mask of is the transpose of the mask of , and the mask of is its own transpose: the weight of the offset is when and when , which is symmetric in the two offsets. Correlating with a mask at equals correlating with the transposed mask at . By Lemma 2 the computed values are the correlations. The determinant is symmetric in and .
The integer box sums are exact, and the same division by is applied, so the equality holds exactly in floating point too.
Lemma 4 (local maxima). Line L4 keeps a sample of a middle layer if and only if is larger than the threshold and larger than each of its 26 neighbors in the block of samples of its octave.
Proof. The code skips a sample if is at most the threshold, or if some neighbor has . So it keeps exactly the samples with above the threshold and 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.
Lemma 5 (Haar responses). Let and be the Haar responses of size at a point whose boxes lie inside the image. Adding a constant to does not change them, and multiplying by multiplies them by . On the ramp , with , 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 . On the ramp, let . The response pairs each pixel of the left half with the pixel of the right half. Each pair differs by , and there are pairs in each of the rows, so . In the same way .
Lemma 6 (orientation on a ramp). If all Haar responses within the radius lie inside the image and , line L6 returns .
Proof. By Lemma 5 each weighted response is with , so all of them have the angle . Every window centered at the angle of a response contains all responses, so every window sum is a positive multiple of , and the longest one has this direction too.
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 .
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 , so by Lemma 5 adding a constant keeps all 64 sums and multiplying by multiplies all of them by ; 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 .
Complexity
The model is the real RAM.
- Line L1 takes time.
- Lines L2 to L4 take time per sample, since each box sum takes four reads, whatever the filter size. The first octave has samples, and each next octave has a quarter as many, so the detector takes time for any number of octaves.
- Lines L5 to L7 take 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 time for a fixed number of samples.
The total time is and the space is . 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 .
- Rotation invariant. The descriptor is turned to . 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 . 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 and by the sign of , and the sums of and by the sign of , which gives 128 values and is more distinctive.
- SURF-36. A 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 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 , not . Mixing them breaks the sizes of the orientation and descriptor windows.
- Normalization. Without the division by , 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 and 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 finds almost everything in .
- Gaussian weights. The Gaussian for the orientation has 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.
# 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
- 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)
- 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)
- 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
- 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.
| 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 RH1WJP Edit this page History Report an error Markdown