Local features: blobs, SIFT and SURF
| Problem | Find distinctive points in an image, with their size and orientation, and describe each so that the same point can be recognised in another image of the scene: shifted, rotated, scaled or differently lit |
| Devised by | Tony Lindeberg (1994, 1998), scale selection with the normalised Laplacian; David Lowe (1999, 2004), SIFT; Herbert Bay, Tinne Tuytelaars and Luc Van Gool (2006), SURF |
| Accuracy | Blob positions and scales agree with scikit-image’s blob_log; SIFT and SURF matches are 92–100% correct under rotation, scaling and contrast change (table below) |
| Cost | Blobs: one blur per scale; SIFT a few blurs per octave plus per keypoint; SURF a constant cost per sample from the integral image, several times faster than SIFT |
| Read first | Image filtering: convolution, Gaussian blur, Sobel gradients and sharpening |
| API | blob_detection, Blob, sift, SiftParams, SiftKeypoint, surf, SurfParams, SurfKeypoint, IntegralImage, match_descriptors |
Overview
To stitch panoramas, track objects or recognise a scene, one image’s points must be found again in another. Local features make this possible. A detector finds points that can be located reliably, such as the centres of blobs and corners, together with a characteristic scale. A descriptor then summarises the neighbourhood at that scale as a vector that changes little under rotation, scaling and changes of brightness. Matching compares descriptors. The Laplacian of Gaussian finds blobs and their sizes. SIFT combines a difference-of-Gaussian detector with a descriptor of gradient histograms. SURF approximates both with box filters on an integral image, for speed.
Where it is used
Local features turn a picture into landmarks that can be recognised again.
- Panoramas. Phone cameras stitch overlapping photographs by matching SIFT-like features.
- Robotics and augmented reality. Visual odometry and SLAM track a camera by following features from frame to frame.
- Object recognition and photogrammetry. Building 3-D models from photographs of a monument or a drone survey.
- Medical and remote sensing. Registering scans taken at different times.
History
Tony Lindeberg (1994, 1998) showed how to select a feature’s scale automatically: take the scale at which a derivative response, multiplied by the right power of , peaks. David Lowe’s scale-invariant feature transform (1999, refined 2004) combined this with a gradient-histogram descriptor. It worked so well that it dominated image matching for over a decade, and its patent (expired 2020) shaped the field. Herbert Bay, Tinne Tuytelaars and Luc Van Gool (2006) designed SURF for speed, replacing Gaussian derivatives with box filters computed in constant time from an integral image, a device from Frank Crow (1984) popularised by Paul Viola and Michael Jones (2001). Learned features from convolutional networks have since taken over many tasks. SIFT and SURF remain the reference hand-crafted methods.
The idea
Blobs and the normalised Laplacian
The aim of this entry is to find points in an image that can be found again in another image of the same scene, taken from a different distance or angle. Such features are the basis of image stitching, object recognition and 3D reconstruction. A good feature must be distinctive, and its detection must not depend on its size in the image. The simplest such feature is a blob: a roughly round region that is brighter or darker than its surroundings.
Blurring by a Gaussian of width and taking the Laplacian gives a strong negative response at the centre of a bright blob. The response is strongest when matches the blob’s size. Raw derivatives of blurred images shrink as grows, so the response is normalised by :
For a Gaussian blob of width , at its centre peaks exactly at ; for a disc of radius , at :
Figure 17.11. LoG response against scale.
blob_detection evaluates at geometrically spaced scales (the Laplacian by the 5-point stencil). It keeps points that are maxima of their neighbourhood in position and scale and exceed a
threshold. Of two detections overlapping by more than a given fraction of the smaller one’s area, it drops the weaker. Each blob’s radius is about :
Figure 17.12. Blobs.
SIFT
The scale-invariant feature transform turns blob detection into a complete pipeline. It finds blob-like keypoints together with their size and orientation, and then summarises the image around each one by a descriptor, a vector of numbers computed relative to that size and orientation. Because the descriptor is measured in the keypoint’s own frame, it comes out nearly the same when the image is scaled or rotated, and keypoints in two images can be paired by comparing descriptors.
- Scale space. Blur the image by Gaussians of widths , with for scales per octave. After each octave, halve the image and continue. Adjacent differences, the difference of Gaussians (DoG), approximate , the normalised Laplacian.
- Detection. Candidates are extrema of the DoG among their 26 neighbours in position and scale.
- Localisation. Fit a quadratic to the DoG around each candidate by Newton’s method: the offset , moving to the neighbouring sample if an offset exceeds one half. Reject candidates of low contrast, . Reject those on edges, where the ratio of principal curvatures of the spatial Hessian exceeds 10, tested as .
- Orientation. Histogram the gradient directions around the keypoint (36 bins, Gaussian-weighted, smoothed). Each peak within 80% of the highest gives a keypoint with that orientation.
- Descriptor. Rotate the neighbourhood to that orientation and divide it into cells, each holding an 8-bin histogram of gradient directions, with trilinear interpolation: 128 numbers. Normalise to unit length, clip at 0.2 to limit the influence of large gradients, and normalise again.
Normalising the image to first makes the thresholds independent of brightness and contrast. Unlike Lowe’s implementation, the image is not upsampled first, so features smaller than about two pixels are missed.
SURF and the integral image
SURF (“speeded-up robust features”) follows the same plan as SIFT but replaces the Gaussian filters by crude approximations that are extremely cheap to compute. The device behind it is the integral image , in which each entry holds the sum of all the pixels above and to the left. The sum over any rectangle is then obtained from the values at its four corners, by adding two and subtracting two, whatever the rectangle’s size. SURF approximates the Gaussian second derivatives by box filters (lobes of and ) and detects maxima of the approximate Hessian determinant
with 0.9 correcting the box approximation’s scale. Filters of size 9, 15, 21, 27 cover the first octave and grow from there. Since a box sum costs the same at any size, SURF grows the filter instead of shrinking the image. The orientation comes from Haar-wavelet responses in a circle of radius , summed in a sliding window of . The descriptor divides a square into subregions, each contributing , a 64-vector. The sign of the Laplacian is stored, so bright-on-dark features are never matched with dark-on-bright ones.
Matching
match_descriptors pairs each descriptor with its nearest neighbour in the other set, by Euclidean distance, and applies Lowe’s ratio test. A match is accepted only if the nearest is closer than ratio (0.75–0.8) times the second nearest, which
rejects descriptors that resemble several others. With mutual, the match must also be nearest in the other direction.
Figure 17.13. SIFT matches.
| second image | SIFT keypoints | SIFT matches | SIFT ms per image | SURF keypoints | SURF matches | SURF ms per image |
|---|---|---|---|---|---|---|
| rotated 0°, scaled 1, contrast × 0.6 | 184 / 184 | 182 (100% correct) | 21 | 103 / 103 | 103 (100% correct) | 3 |
| rotated 30°, scaled 1, contrast × 1 | 184 / 158 | 113 (100% correct) | 18 | 103 / 106 | 57 (100% correct) | 3 |
| rotated 0°, scaled 0.75, contrast × 1 | 184 / 91 | 66 (100% correct) | 15 | 103 / 91 | 39 (92% correct) | 3 |
| rotated 45°, scaled 0.8, contrast × 0.7 | 184 / 112 | 81 (99% correct) | 16 | 103 / 92 | 32 (94% correct) | 3 |
A match is counted correct if the keypoint lands within 3 pixels of where the known transformation sends it. Both detectors find fewer keypoints in the shrunken copies, since fine features fall below the smallest scale. SURF is 4–6 times faster here and less discriminating, with fewer and slightly less reliable matches.
Algorithm
Blob detection.
- For each scale of a geometric sequence: blur the image by ; apply the five-point Laplacian; multiply by . This gives a stack of response images.
- Find the points of the stack that exceed the threshold and are at least as large as all their 26 neighbours, 8 in their own image and 9 in each of the images at the adjacent scales.
- Sort the detections by response. Take each in turn and discard it if it overlaps an already accepted blob by more than the allowed fraction of the smaller one’s area.
SIFT.
- Scale space. For each octave, blur the image to a sequence of increasing widths and subtract neighbouring images to form the difference-of-Gaussians (DoG) stack. Halve the image for the next octave.
- Extrema. Find the points of each DoG stack that are larger, or smaller, than all 26 neighbours.
- Refine. For each candidate, fit a quadratic to the DoG values around it and solve for the offset of the true extremum. If the offset exceeds half a sample in any direction, move to the neighbouring sample and try again, up to five times. Reject the candidate if its contrast is low or if it lies on an edge.
- Orientation. Build the histogram of gradient directions around the keypoint, and create one keypoint for each sufficiently high peak.
- Descriptor. Compute the histogram in the rotated frame, normalise, clip and renormalise.
SURF.
- Compute the integral image.
- For each filter size, compute the box-filter approximations of , and at every pixel, and the determinant response.
- Find the maxima above the threshold among the 26 neighbours in position and filter size, and interpolate their position and scale.
- Assign an orientation from the Haar-wavelet responses, and compute the 64-number descriptor.
Matching two sets of descriptors.
- For each descriptor of the first set, find its nearest and second-nearest neighbours in the second set, by Euclidean distance.
- Accept the match if the nearest distance is below
ratiotimes the second nearest. - With
mutual, also require that the first descriptor be the nearest neighbour of its match in the opposite direction.
Implementation
let laplacian = array![[0.0, 1.0, 0.0], [1.0, -4.0, 1.0], [0.0, 1.0, 0.0]];
// Scale-normalised, sign-flipped so bright blobs are positive maxima.
let stack: Vec<Array2<f64>> = sigmas
.iter()
.map(|&s| {
let lap = correlate2d(&gaussian_blur(image, s)?, &laplacian, Border::Replicate)?;
Ok(lap.mapv(|v| -s * s * v))
})
.collect::<Result<_, ErrorsJSL>>()?;
let x = solve3(h, [-g[0], -g[1], -g[2]])?;
if x.iter().all(|v| v.abs() < 0.5) {
let contrast = v + 0.5 * (g[0] * x[0] + g[1] * x[1] + g[2] * x[2]);
if contrast.abs() * (s as f64) < p.contrast_threshold {
return None;
}
let (tr, det) = (dxx + dyy, dxx * dyy - dxy * dxy);
let r = p.edge_threshold;
if det <= 0.0 || r * tr * tr >= (r + 1.0) * (r + 1.0) * det {
return None;
}
return Some(Candidate { layer, row, col, dx: x[0], dy: x[1], ds: x[2], contrast });
}
let dxx = (integral.box_sum(r - l + 1, c - b, 2 * ls - 1, w) - 3.0 * integral.box_sum(r - l + 1, c - l / 2, 2 * ls - 1, ls)) * inv_area;
let dyy = (integral.box_sum(r - b, c - l + 1, w, 2 * ls - 1) - 3.0 * integral.box_sum(r - l / 2, c - l + 1, ls, 2 * ls - 1)) * inv_area;
let dxy = (integral.box_sum(r - l, c + 1, ls, ls) + integral.box_sum(r + 1, c - l, ls, ls) - integral.box_sum(r - l, c - l, ls, ls) - integral.box_sum(r + 1, c + 1, ls, ls)) * inv_area;
response[(ar, ac)] = dxx * dyy - 0.81 * dxy * dxy;
laplacian[(ar, ac)] = if dxx + dyy >= 0.0 { 1 } else { -1 };
let mut out = Vec::new();
for (i, q) in a.iter().enumerate() {
let (j, d1, d2) = nearest(q, b);
// With a single candidate there is no second neighbour to compare against.
let passes = d2.is_infinite() || d1 < ratio * d2;
if passes && (!mutual || nearest(&b[j], a).0 == i) {
out.push(DescriptorMatch { index_a: i, index_b: j, distance: d1 });
}
}
Ok(out)
- Only bright blobs are detected. A dark blob gives a negative centre and a weak positive ring, about 13% of the response, so keep the threshold above that.
SiftParamsandSurfParamsdefault to the papers’ values;SurfParams::uprightskips orientation (U-SURF) when images are not rotated.- Matching is brute force, distance computations; for thousands of descriptors a k-d tree or approximate search would be faster.
In practice
//! Blob detection, SIFT and SURF keypoints, and descriptor matching.
use lib_jsl_dsp::discrete::image::feature_extraction::blob_detection::blob_detection;
use lib_jsl_dsp::discrete::image::feature_extraction::match_descriptors;
use lib_jsl_dsp::discrete::image::feature_extraction::sift::{SiftParams, sift};
use lib_jsl_dsp::discrete::image::feature_extraction::surf::{SurfParams, surf};
use ndarray::Array2;
fn main() {
// Two Gaussian spots of standard deviation 3 and 6.
let spots = Array2::from_shape_fn((80, 80), |(r, c)| {
let g = |r0: f64, c0: f64, s: f64| (-((r as f64 - r0).powi(2) + (c as f64 - c0).powi(2)) / (2.0 * s * s)).exp();
g(20.0, 20.0, 3.0) + g(50.0, 55.0, 6.0)
});
for b in blob_detection(&spots, 1.0, 12.0, 12, 0.1, 0.5).unwrap() {
println!("blob at ({}, {}), σ = {:.2}, radius {:.1}", b.row, b.col, b.sigma, b.radius());
}
// A textured image and the same shifted by (5, 3) pixels with its contrast halved.
let texture = |r: f64, c: f64| (r / 4.0).sin() * (c / 5.0).cos() + 0.5 * ((r + c) / 7.0).sin() + 0.3 * ((r * c).abs().sqrt() / 2.0).cos();
let a = Array2::from_shape_fn((96, 96), |(r, c)| texture(r as f64, c as f64));
let b = Array2::from_shape_fn((96, 96), |(r, c)| 0.5 * texture(r as f64 - 5.0, c as f64 - 3.0) + 0.2);
let (ka, kb) = (sift(&a, &SiftParams::default()).unwrap(), sift(&b, &SiftParams::default()).unwrap());
let da: Vec<Vec<f64>> = ka.iter().map(|k| k.descriptor.clone()).collect();
let db: Vec<Vec<f64>> = kb.iter().map(|k| k.descriptor.clone()).collect();
let m = match_descriptors(&da, &db, 0.8, true).unwrap();
let shifts: Vec<(f64, f64)> = m.iter().map(|mm| (kb[mm.index_b].y - ka[mm.index_a].y, kb[mm.index_b].x - ka[mm.index_a].x)).collect();
let good = shifts.iter().filter(|(dy, dx)| (dy - 5.0).abs() < 1.0 && (dx - 3.0).abs() < 1.0).count();
println!("SIFT: {} and {} keypoints, {} matches, {} with the true shift (5, 3)", ka.len(), kb.len(), m.len(), good);
let (sa, sb) = (surf(&a, &SurfParams::default()).unwrap(), surf(&b, &SurfParams::default()).unwrap());
println!("SURF: {} and {} keypoints, descriptors of length {}", sa.len(), sb.len(), sa.first().map_or(0, |k| k.descriptor.len()));
}
blob at (50, 55), σ = 6.09, radius 8.6
blob at (20, 20), σ = 3.09, radius 4.4
SIFT: 40 and 45 keypoints, 29 matches, 28 with the true shift (5, 3)
SURF: 25 and 26 keypoints, descriptors of length 64
The blob scales are the nearest of the 12 sampled scales to the true 3 and 6. All but one SIFT match recovers the shift, despite the halved contrast.
Strengths
- Repeatable keypoints with their own scale and orientation; descriptors invariant to rotation, scale and affine changes of brightness, and robust to moderate viewpoint change.
- SURF trades a little distinctiveness for speed.
Weaknesses
- Not invariant to strong perspective change; repetitive texture produces ambiguous matches that the ratio test must reject.
- Many parameters and many steps; matches still need geometric verification (for example RANSAC) in practice.
Exercises
- Show that for , the normalised Laplacian at the origin, , is maximised at .
- Show that using the heat equation .
- Derive the sub-pixel offset from a second-order Taylor expansion.
- Show that when the eigenvalues of are in the ratio .
- Write the box sum of a rectangle in terms of four integral-image values.
Hints and answers
- For a 2-D Gaussian, . Since with , the normalised response is ; setting its derivative with respect to to zero gives .
- The heat equation gives .
- Expand and set the gradient to zero: .
- With eigenvalues , .
- For the rectangle with corners to (inclusive of the lower-right corner), the sum is .
Further reading
- T. Lindeberg, “Feature detection with automatic scale selection”, International Journal of Computer Vision 30 (1998) 79–116.
- D. G. Lowe, “Distinctive image features from scale-invariant keypoints”, International Journal of Computer Vision 60 (2004) 91–110.
- H. Bay, A. Ess, T. Tuytelaars and L. Van Gool, “Speeded-up robust features (SURF)”, Computer Vision and Image Understanding 110 (2008) 346–359.
- R. Szeliski, Computer Vision: Algorithms and Applications, 2nd ed., Springer, 2022, chapter 7.