BookNotesSlidesP-sets Syllabusdraft · v0.2.64.1
◀▲⌂▶
💬Comments welcome. To leave a note, select any text and click the note / highlight button that pops up — or open the panel with the tab at the top-right (‹). Notes are visible only inside our private review group.
Course notes · 15 sections from the book · 9 optionalPDFessentials+ usefuleverythingthe full book ↗
💡 In a hurry? Jump to this chapter’s 3 big lessons ↓

Lecture Notes 12 — Harris corners, descriptors⧉

Course notes cut from Computational Photography, an AI-powered Slopendium for this lecture. Each section links back to its home in the book; sections marked optional go beyond what the lecture needs.

Contents · 11 sections on this page, from 7 chapters of the book

Convolution⧉

Gradient and oriented filters⧉

optional

Not every useful kernel blurs. The most important non-blurring kernel measures change (how fast the image brightens or darkens as you step across it) and that turns out to be the foundation of edge detection.

With pixel spacing $h$, a forward difference is $I_x[i]=(I[i+1]-I[i])/h$. The weights $[-1,+1]/h$ act as a correlation stencil at offsets $0,1$. Under this chapter’s convolution convention, the same operation has $g[-1]=1/h$ and $g[0]=-1/h$. State the offsets as well as the weights: a two-tap stencil has no central sample. A ramp increasing to the right must produce a positive derivative.

A grayscale image is a two-dimensional function (a brightness landscape with hills and valleys) so its derivative is not a single number but a gradient: a vector that, like the slope of a hill, points in the direction of steepest brightening and is perpendicular to the contours of constant brightness (Figure 6.2.17, right). Its two components are exactly the horizontal and vertical partials, $I_x$ and $I_y$, which is why we estimate each with its own finite-difference kernel.

💡 Big lesson (L6.6) — differentiation is convolution

Finite differences are convolutions with signed kernels under a declared indexing convention. In the continuous setting, $\partial_x(g*I)=(\partial_x g)*I$: convolving with a derivative-of-Gaussian differentiates a smoothed image. Gradient components are linear; gradient magnitude, thresholding, and a complete edge detector generally are not.

fig-derivative-gradient
Figure 6.2.17 (reproduced). From derivative to gradient. Left, in 1-D the derivative is the slope of the tangent to the curve. Right, in 2-D the gradient $\nabla f = (f_x, f_y)$ is a vector that points in the direction of steepest ascent (uphill) and is normal to the contours of constant value, the natural generalization of the slope to a brightness landscape. An image's gradient is computed component-wise: a horizontal finite difference for $I_x$, a vertical one for $I_y$.

Differencing increases the contribution of rapidly varying noise. Sobel combines a difference along one axis with smoothing along the other. The following displayed matrix is a correlation stencil, using image coordinates with $x$ rightward and $y$ downward:

$$ \text{Sobel}_x = \begin{bmatrix} -1 & 0 & +1 \\ -2 & 0 & +2 \\ -1 & 0 & +1 \end{bmatrix}, $$

Divide its response by $8h$ to estimate a derivative in intensity per unit distance on a linear ramp. For convolution, flip the displayed stencil, which negates it. Its transpose gives the vertical stencil under the same convention.

The smoothing is what Sobel buys. Scaled by 1/4, it gives a step edge the same height of response as the plain difference $[-1,\,1]$, but it averages three rows, weighted 1, 2, 1, before differencing. On independent pixel noise of standard deviation $s$, the plain difference has noise $\sqrt2\,s$ and the scaled Sobel $\sqrt{12}/4\,s\approx0.87\,s$, about 1.6 times less. The price is resolution: Sobel's response to an edge is two pixels wide (Figure 6.2.18).

fig-finite-difference-vs-sobel
Figure 6.2.18 (reproduced). The plain difference and Sobel on a noisy photograph, an arcade at ISO 6400. Both filters are scaled to give the same step response, so the edges have the same height in both; in the flat regions the Sobel output is visibly quieter. The noise measured in a flat patch of each derivative image is printed on its panel beside the value predicted from the filter weights.

Stacking the two partials into a vector gives the image gradient $\nabla I = (I_x, I_y)$, the brightness-landscape gradient of Figure 6.2.17 applied to a real image. Two numbers fall out of it, both central to vision:

$$ \|\nabla I\| = \sqrt{I_x^2 + I_y^2} \quad\text{(edge strength)}, \qquad \theta = \operatorname{atan2}(I_y, I_x) \quad\text{(gradient orientation)}. $$

The magnitude is large at strong intensity changes, which can be object boundaries, texture, or noise. The gradient angle points across an edge; its tangent is perpendicular, $\theta+\pi/2$ modulo $\pi$. Thresholding magnitude gives a simple detector. Canny adds smoothing, non-maximum suppression, and hysteresis.

fig-gradient-sobel
Figure 6.2.19 (reproduced). Gradient via Sobel. From left: the input image; the horizontal Sobel response $I_x$ (vertical edges light up); the vertical Sobel response $I_y$ (horizontal edges light up); and the gradient magnitude $\sqrt{I_x^2 + I_y^2}$, an edge-strength map that is bright on contours and dark in smooth regions. The Sobel kernel pairs a finite-difference derivative on one axis with a small smoothing on the other for noise robustness.

Blur, gradients, and sharpening all share the same comfortable assumption: one kernel, applied the same way everywhere. Before we lean on it, ask how well that assumption actually holds for the blur a real camera produces, because that is where the clean theory meets messy optics. (The linear sharpening above is only the start; its nonlinear, edge-aware forms are the Chapter 8.8, Sharpening chapter, and undoing a blur exactly, deconvolution, comes later still.)

fig-gabor-bank
Figure 6.2.20 (reproduced). An oriented filter at one scale and orientation, and the bank it belongs to. The kernel is a Gaussian envelope times a cosine (even: bars and lines) or a sine (odd: edges) across the chosen orientation. Either response alone depends on where the feature sits within the filter's cycle; the energy √(even² + odd²) does not, which is what makes the pair a detector of oriented structure rather than of one particular phase. Interactive: set the orientation and wavelength or click a filter in the bank, and switch between the even response, the odd response and their energy.
fig-conv-layer
Figure 6.2.21 (reproduced). The first layer of a convolutional network, as kernels of the kind this chapter builds by hand. Eight small RGB kernels (three edge detectors, a blur, a center-surround, two color opponents and an oriented stripe) and the feature map each produces, with the ReLU that the layer passes on. The switch between correlation and convolution is the point: a library's "convolution" layer computes the correlation, and flipping the kernels mirrors the response of every asymmetric one. The kernels here are hand-built, not taken from a trained network. Interactive: choose correlation or convolution, turn ReLU off to see the signed maps, and click a map to enlarge it.

Sparse matching⧉

in the book↗

The previous part transported pixels along maps that were given or hand-drawn. This part estimates the maps, and the cheapest, most robust way to start is not to match every pixel but to match a sparse handful of points you can find again. The pipeline has three stages, in order: detect distinctive points, describe each neighborhood with a vector, then match those vectors across images. Two design goals govern the whole pipeline and pull in opposite directions. Detection must be repeatable: the same physical point should fire in both images despite a change of viewpoint, zoom, and lighting. If a corner is found in one image but not the other, there is no chance to match it. Description must be distinctive yet invariant: unique enough that the right match stands out unambiguously, but stable enough to survive the change between the two images. Repeatability and distinctiveness are the two halves of the contract, and almost every design decision below is a negotiation between them.

💡 Big lesson (L12.1): the structure tensor, three jobs

The same $2\times2$ matrix $M=\sum_W \nabla I\,\nabla I^{\top}$ answers three questions across this part, and the unity is the point. Is this a good point to detect? Yes, where $M$ has two large eigenvalues, a corner: that is Harris / Shi–Tomasi, here. Is this patch's motion solve well-conditioned? The very same matrix, now required invertible: that is KLT (Chapter 12.4, Feature tracking). What is the local flow constraint? $M$ is the normal-equations matrix $A^\top A$: that is Lucas–Kanade (Chapter 12.8, Optical flow). Detect with it, track with it, solve flow with it: one matrix, read three ways. Corners are special for a deep reason: the same both-directions-vary condition that localises a point is also what makes its motion recoverable. So "good to detect" and "good to track" are not two coincidentally-aligned criteria; they are one statement about $M$.

Where to look: corners, and the structure tensor⧉

in the book↗

Why corners? Because a point can only be localized where the intensity changes in both directions. Walk through the three cases (Figure 12.3.1). A flat patch can be slid in any direction and looks identical, so there is nothing to lock onto, and its position is hopeless. An edge is worse than it looks: you can slide it along itself and see no change, so its position along the edge is unrecoverable. This is the aperture problem of Chapter 12.8, Optical flow, now seen in detection. Only a corner, where two differently oriented edges meet, pins down uniquely, because every small shift changes the appearance.

The quantitative test for "varies in both directions" is the structure tensor $M$, also called the second-moment matrix or, in this context, the Harris matrix. Imagine shifting a window $W$ by a small $(\Delta x,\Delta y)$ and measuring the resulting sum-of-squared-differences; a first-order Taylor expansion turns that error surface into a quadratic form whose matrix is exactly

$$ M=\sum_{\mathbf x\in W} w(\mathbf x)\begin{pmatrix}I_x^2 & I_xI_y\\ I_xI_y & I_y^2\end{pmatrix}, $$

the gradient outer products $\nabla I\,\nabla I^{\top}$ accumulated over the window with weights $w$ (a Gaussian, in practice, for a smooth falloff). The two eigenvalues $\lambda_1\ge\lambda_2$ of $M$ measure how strongly the intensity varies along its two principal directions, and they read off the three cases cleanly: flat means both eigenvalues tiny ($M$ near zero, the error surface nearly flat); edge means one large eigenvalue and one near zero ($M$ rank-deficient, the error surface a trough); corner means both eigenvalues large ($M$ well-conditioned, the error surface a steep bowl). Drawn as an error ellipse with axes $\lambda_1^{-1/2},\lambda_2^{-1/2}$, the partition is one picture: an unbounded tangent direction for an ideal edge, little constraint in either direction for a flat patch, and bounded uncertainty in both directions for a sufficiently informative corner.

fig-structure-tensor-ellipse
Figure 12.3.1 (reproduced). One matrix, the flat/edge/corner partition. The second-moment matrix $M=\sum_W \left(\begin{smallmatrix}I_x^2 & I_xI_y\\ I_xI_y & I_y^2\end{smallmatrix}\right)$ drawn as an error ellipse (axes scaled by $\lambda_1^{-1/2},\lambda_2^{-1/2}$) over three patches. Flat (both eigenvalues tiny): a large, near-circular ellipse, since the SSD error stays low for shifts in every direction, so the point is unlocalisable. Edge (one large eigenvalue, one near-zero): a long thin slit, error rising across the edge but staying flat along it (the aperture problem). Corner (both eigenvalues large): a small round-ish ellipse, every shift incurring cost, so the point is pinned. The eigenvalues of one $2\times2$ matrix sort every patch into these three.

The quadratic is only the first term of a Taylor expansion, so we compare it with the error it stands for. Figure 12.3.2 computes both at any pixel of a photograph: the exact sum of squared differences for every shift of the window, and $(\Delta x,\Delta y)\,M\,(\Delta x,\Delta y)^{\top}$.

fig-harris-error-surface
Figure 12.3.2 (reproduced). The exact error surface against the structure tensor's quadratic (interactive). Click a pixel of the photograph, or press "a corner", "an edge" or "a flat patch" (the photograph's largest $R$, its most negative $R$, its smallest $\operatorname{tr}M$). Top: the exact $E(\Delta x,\Delta y)=\sum_W w\,[I(\mathbf x+(\Delta x,\Delta y))-I(\mathbf x)]^2$ for whole-pixel shifts, and the quadratic $(\Delta x,\Delta y)\,M\,(\Delta x,\Delta y)^{\top}$, drawn on one height scale for the whole photograph (its strongest corner's $E$), so a corner is a bowl, an edge a trough and a flat patch nearly flat, in both; drag either surface to orbit them together. Bottom: the window ($w$ a Gaussian of standard deviation $\sigma$), the levels of this window's $E$ (solid) against the ellipses of $M$ at the same levels (dashed), and $\lambda_1$, $\lambda_2$ and $R=\det M-k(\operatorname{tr}M)^2$. Near zero shift the two agree. Further out the exact error levels off, because once the window has slid off the structure that made it rise there is nothing more to lose, while the quadratic keeps climbing; widen "shifts up to" to watch them part.

Two responses turn the eigenvalues into a detector. Harris (Harris & Stephens 1988 Harris & Stephens 1988) avoids computing eigenvalues, which were expensive in 1988, and uses the cheap determinant-and-trace combination

$$ R=\det M-k\,(\operatorname{tr}M)^2=\lambda_1\lambda_2-k(\lambda_1+\lambda_2)^2, $$

with $k\approx 0.04$–$0.06$. $R$ is large and positive only when both eigenvalues are large (a corner), strongly negative on edges (one eigenvalue dominates), and near zero on flat regions. The pipeline is then mechanical: compute gradients, form the three products $I_x^2, I_y^2, I_xI_y$, Gaussian-smooth each, combine into $R$, threshold, and non-maximum-suppress so each corner fires exactly once (Figure 12.3.3). A useful property falls out for free: because $R$ is built from gradients it is invariant to an intensity offset ($I\to I+b$), and because the structure-tensor ellipse merely rotates with the image, $R$ is invariant to image rotation; only the absolute scaling of the threshold and, as we will see, the image scale give it trouble.

Shi–Tomasi (Shi & Tomasi 1994 Shi & Tomasi 1994, "good features to track") takes the more direct route and scores a corner by the smaller eigenvalue itself,

$$ \min(\lambda_1,\lambda_2) > \tau : $$

a point is a good corner exactly when its weaker direction is still strong, i.e. both directions are well-constrained. This is the same criterion that makes a feature trackable (it is precisely the condition that $M$ be well-conditioned for the KLT motion solve in Chapter 12.4, Feature tracking), which is why Shi & Tomasi derived "what is a good feature to detect" from "what is a good feature to track." Harris versus Shi–Tomasi is two readings of the same matrix: Shi–Tomasi is slightly more reliable, Harris slightly cheaper, and in practice they pick nearly the same points.

fig-harris-real
Figure 12.3.3 (reproduced). Harris corner detection on a real photograph, stage by stage. (1) the input image. (2) the structure tensor $M=\sum_W\nabla I\,\nabla I^{\top}$ visualized over the image (the windowed second-moment of gradients). (3) the Harris response $R=\det M-k(\operatorname{tr}M)^2$ as a heatmap: hot where both eigenvalues are large (corners and texture junctions), strongly negative along edges, near zero on flat regions. (4) the detected corners surviving thresholding and non-maximum suppression, overlaid as points: they land on actual corners (window frames, façade junctions, rooflines meeting) and never on a single straight edge or a flat patch. The heatmap makes the eigenvalue story visible: corners are the isolated hot peaks the response picks out. (Harris & Stephens 1988.)

Apply nonmaximum suppression after a corner response and retain spatial coverage, not only the strongest cluster. Thresholds depend on image scale, derivative filters, encoding and noise. Large tensor eigenvalues describe local translation sensitivity; they do not guarantee a correct correspondence across viewpoints.

Invariance: surviving scale and rotation⧉

optional

Harris solves where to look within a single image, but a corner detected at one zoom or one orientation must be found, and described the same way, in an image where the object is bigger or rotated. Across far views this is the crux: the two photos differ in scale (you stood closer, or zoomed) and in rotation (you tilted the camera, or the object turned). Plain Harris fails the scale test outright. Blur an image down and a corner becomes a smooth bump that the detector reads as flat, or as an edge. Repeatability across far views therefore demands that detector and descriptor be covariant with scale and rotation: find the same physical point, and measure its neighborhood in a frame that rotates and scales with the point itself.

Scale is SIFT's signature contribution (Lowe 2004 Lowe 2004). The idea is to give each keypoint its own characteristic scale, found automatically and consistently across images. Build a scale-space, the image repeatedly blurred by a Gaussian of growing $\sigma$, so that fine structure dissolves as you climb, and look for a function of $\sigma$ that peaks at the size of the structure under the point. A center-surround / band-pass response does exactly this: it is near zero when the window is much smaller or much larger than the feature and peaks when they match. SIFT computes it cheaply as the Difference-of-Gaussians,

$$ D(x,y,\sigma)=\big(G_{k\sigma}-G_{\sigma}\big)*I, $$

a close and inexpensive approximation to the scale-normalized Laplacian. A keypoint is then a point that is a local extremum of $D$ in all three coordinates jointly, a maximum or minimum over $(x,y)$ and over neighboring scales $\sigma$ (Figure 12.3.4). The scale at which the extremum occurs is the feature's characteristic scale: describe the neighborhood at that scale, and the descriptor no longer cares how zoomed-in the photo was. (In practice the scale-space is organized into octaves, halving the resolution each octave, and the raw extrema are refined to sub-pixel, sub-scale precision by fitting a quadratic, with weak or edge-like extrema discarded by a DoG-value threshold and a principal-curvature ratio test, the Harris idea reused to reject points strung out along an edge.)

fig-scale-space-dog
Figure 12.3.4 (reproduced). A keypoint is an extremum in space and scale. A Difference-of-Gaussian stack: the image is blurred by Gaussians of increasing $\sigma$ (climbing the page) and adjacent blur levels are subtracted to give a band-pass response $D(x,y,\sigma)=(G_{k\sigma}-G_\sigma)*I$ at each scale. A keypoint (circled) is a point that is a local maximum or minimum among its neighbors in $(x,y)$ and across the two adjacent scales, a peak in the full $(x,y,\sigma)$ volume. The scale at which the peak occurs sets the circle's size: that characteristic scale is what makes the later descriptor zoom-invariant.

Rotation is handled by an analogous canonical-frame trick. Around the keypoint, at its scale, build a histogram of local gradient orientations (weighted by gradient magnitude) and read off its peak: the dominant orientation. Then measure the descriptor relative to that orientation, as if the patch had been rotated to a canonical upright pose. Rotate the object in the world and its dominant orientation rotates with it, so the descriptor comes out unchanged. Illumination invariance is bought the same cheap way it was for Harris: use gradients, which are blind to an additive brightness offset, and normalize the final vector to remove a multiplicative gain. With characteristic scale and dominant orientation in hand, every keypoint comes with a stable local coordinate frame $(x,y,\sigma,\theta)$, and the descriptor's only remaining job is to summarize what the neighborhood looks like in that frame.

Describing a neighborhood: SIFT and its zoo⧉

optional

The simplest possible descriptor is the raw patch, a small window of pixel values around the keypoint, matched by SSD or NCC. It is invariant to nothing on its own; bolted onto the canonical frame above (resample the window at the keypoint's scale, rotate it to the dominant orientation, normalize its intensities) it becomes serviceable, and this is essentially the Multiscale Oriented Patches descriptor. But raw patches are brittle: a one-pixel misregistration or a small non-rigid deformation changes every value, so the SSD jumps. The standard improvement is to describe the patch by its gradients, histogrammed over cells, which makes it distinctive yet tolerant of those small shifts.

That is SIFT (Lowe 2004 Lowe 2004), the Scale-Invariant Feature Transform, and here it is concretely (Figure 12.3.5). Take a $16\times16$ window around the keypoint, sampled at the feature's scale and rotated to its dominant orientation. Divide it into a $4\times4$ grid of cells. In each cell, accumulate the gradient orientations into an 8-bin histogram, each gradient weighted by its magnitude and by a Gaussian centered on the keypoint (so the window edges count less), and spread across bins by trilinear interpolation (so a gradient near a cell or bin boundary does not flip discontinuously). Concatenate the $4\times4$ cells $\times\,8$ orientations into a single 128-dimensional vector. Finally, $L_2$-normalize it, then clamp every component to a ceiling (0.2) and renormalize, which blunts the influence of a few very large gradients from, say, a strong specular edge. The important design choice is the histogram: by binning gradients within a cell rather than recording their exact positions, SIFT tolerates small spatial shifts and deformations while remaining highly distinctive, the resolved tension between invariance and discriminability. Empirically it survives viewpoint changes up to roughly $60^\circ$ of out-of-plane rotation and dramatic illumination shifts, which is why it dominated matching, stitching, and recognition for a decade.

fig-sift-descriptor
Figure 12.3.5 (reproduced). Building the 128-D SIFT vector. Left: the gradient field in a window around the keypoint, rotated to the keypoint's dominant orientation so the descriptor is rotation-invariant, with a Gaussian weighting (faded toward the edges). Middle: the window split into a $4\times4$ grid of cells; within each cell the gradients are accumulated into an 8-bin orientation histogram (drawn as a small star of bars, weighted by gradient magnitude). Right: the $4\times4\times8=128$ histogram values concatenated into one vector, $L_2$-normalized with a clamp for contrast invariance. Histogramming gradients per cell is what buys tolerance to small shifts while staying distinctive.

SIFT is accurate but not cheap, and a zoo of successors trades accuracy for speed along a single set of trade-offs: speed, robustness, and invariance (Figure 12.3.6). SURF (Bay et al. 2006) Bay et al. 2006 (SURF) approximates SIFT's Gaussian derivatives with box filters evaluated in $O(1)$ via the integral image, buying a large speed-up for a small robustness cost. FAST (Rosten & Drummond 2006) Rosten & Drummond 2006 (FAST) is only a corner detector; it tests pixels on a circle for a contiguous arc brighter or darker than the center, extremely fast, with no descriptor of its own. The binary descriptors are the real-time workhorses: BRIEF (Calonder et al. 2010) Calonder et al. 2010 (BRIEF) encodes a patch as a string of bits, each one the answer to "is pixel $p$ brighter than pixel $q$?" for a fixed set of test pairs, and ORB (Rublee et al. 2011) Rublee et al. 2011 (ORB) wraps FAST detection plus a rotation-aware BRIEF into a complete, patent-free, SIFT-free pipeline; BRISK Leutenegger, Chli & Siegwart 2011 (BRISK) adds a scale-space and a structured sampling pattern. Binary descriptors are tiny and are matched not by Euclidean distance but by Hamming distance: a XOR and a popcount, almost free on modern hardware. At the other end, KAZE Alcantarilla, Bartoli & Davison 2012 (KAZE) / AKAZE Alcantarilla, Nuevo & Bartoli 2013 (AKAZE) build their scale-space with nonlinear (edge-preserving) diffusion instead of Gaussian blur, respecting object boundaries for better localization at higher cost. In short, SIFT remains the accuracy benchmark; binary descriptors are what you reach for when you need thousands of matches per frame on a phone.

fig-descriptor-zoo
Figure 12.3.6 (reproduced). The descriptor zoo, on the axes that matter. SIFT, SURF, ORB, and BRIEF placed on a speed ↔ robustness ↔ invariance layout. SIFT: a 128-D float vector, the most invariant but the slowest. SURF: box-filter / integral-image approximation of SIFT, faster, with some loss in invariance. ORB / BRIEF: binary strings of pixel-pair intensity comparisons, matched by Hamming distance, tiny and very fast, ORB adding rotation and FAST detection for a full SIFT-free pipeline. Float-versus-binary is the headline split; each point on the diagram is a different bet on how much robustness to spend for speed.

Canonical scale and orientation reduce sensitivity to those transformations but do not guarantee invariance under severe perspective change, blur or occlusion. For descriptors, use Euclidean distance for an appropriately normalized SIFT vector and Hamming distance for binary descriptors such as ORB. Compare performance under the image changes expected in the application.

Matching: nearest neighbor in descriptor space⧉

in the book↗

With every keypoint reduced to a vector, matching is conceptually trivial: a keypoint in image A matches the keypoint in image B whose descriptor is nearest (Figure 12.3.7). The distance is Euclidean for float descriptors (SIFT, SURF) and Hamming for binary ones (ORB, BRIEF). Done naively, this is exhaustive: compare every descriptor in A against every descriptor in B, which is fine for a single pair of images but becomes the bottleneck once you match against a large database (Photo Tourism reconstructs cities from tens of thousands of photos, each with hundreds of features). The standard remedy is approximate nearest-neighbor search (k-d trees with best-bin-first, or modern hashing) which trades a small chance of missing the true nearest neighbor for an enormous speed-up; the details live in Chapter 12.7, Fast matching.

A caveat is that the raw nearest-neighbor matches are not ready to use. Repeated texture (a row of identical windows, a brick wall), occlusion, and ordinary descriptor collisions all manufacture matches that are confident but wrong, and a single wrong correspondence can wreck a least-squares fit of the transform you ultimately want. The fix is two-stage and is the subject of the next section: Lowe's ratio test prunes ambiguous matches before fitting (accept a match only if the nearest descriptor is decisively closer than the second nearest), and then RANSAC Fischler & Bolles 1981 fits a geometric transform robustly despite whatever outliers survive. That is Chapter 12.5, Robustness: the ratio test and RANSAC, which this section feeds, and from there the clean correspondences flow into panorama stitching (Chapter 20.2, Automatic panorama stitching from multiple views and feature matching) and 3-D reconstruction (Part 36, 3D and depth). The entire hand-designed pipeline, detector, descriptor, and matcher, is exactly the kind of three-stage system that later learned methods replace, swapping each stage for a learned operator (SuperPoint DeTone et al. 2018 (SuperPoint), SuperGlue Sarlin et al. 2020 (SuperGlue), and the pointmap regressors of Chapter 12.6, Deep learning approaches to sparse matching); but the problem it solves is the one stated here, and SIFT remains the baseline they are measured against.

fig-descriptor-matching
Figure 12.3.7 (reproduced). Nearest-neighbor matching, before and after the ratio test. Two views of the same scene with their keypoints, joined by lines to their nearest neighbor in descriptor space. Left (raw): many lines, with repeated texture and occlusion producing confident-but-wrong matches alongside the good ones. Right (after the ratio test): the survivors, where the nearest descriptor was decisively closer than the second-nearest ($d_1/d_2$ small); the ambiguous matches on repeated structure are gone, leaving a clean, consistent set. The rejected matches are exactly the handoff to the robustness section that fits a transform to what remains.

Feature tracking⧉

Good features to track = where the structure tensor is well-conditioned⧉

optional

Here is the hinge the whole section turns on. The update $\Delta\mathbf{u}=M^{-1}\mathbf{b}$ is only meaningful when $M$ is invertible and well-conditioned, meaning you can actually trust the inverse. And the conditioning of $M$ is read straight off its eigenvalues $\lambda_1\ge\lambda_2$, the same eigenvalues that, in the Harris derivation, sort a patch into flat, edge, or corner. So the question "is this a good feature to track?" is literally "is the tracking matrix well-conditioned?", which is in turn literally "is this a corner?" One question in three forms.

Walk through the three cases. They are exactly the Harris partition, now read as trackability:

The selection rule falls right out of this. Shi & Tomasi's (1994) "good features to track" criterion is the simple, principled test

$$ \min(\lambda_1,\lambda_2) > \lambda_{\min}, $$

read as: require the smaller eigenvalue to be large enough, that is, demand that both directions be well-constrained, not just one. This is nothing but the conditioning of $M$ stated directly, and it is the same $\min(\lambda_1,\lambda_2)$ corner response cross-referenced in Chapter 12.3, Sparse matching. The Harris response $R=\det M - k\,(\operatorname{tr} M)^2$ is a determinant-and-trace proxy for the same quantity. What matters is the direction of the logic: the detector and the tracker agree by construction, because Shi & Tomasi derived "what makes a good feature to detect" from "what makes a good feature to track", not the other way round (Figure 12.4.3).

In practice the recipe is exactly the Harris pipeline: compute $M$ over a window at every pixel (image gradients → pointwise products → Gaussian-weighted sum), score each pixel by $\min(\lambda_1,\lambda_2)$, non-maximum-suppress, and keep the top-$N$ well-spread points. Those are the features you then KLT-track.

One real tension governs the window size, and it is the recurring small-versus-large-aperture trade of every patch method. A small window localises precisely but sees little texture, so $M$ is poorly conditioned and noise fools it. A large window is better conditioned but spans multiple motions: across a depth discontinuity or an object boundary, a single displacement $\mathbf{u}$ no longer fits the whole window. The sweet spot trades localization against conditioning.

fig-good-features-to-track
Figure 12.4.3 (reproduced). Shi–Tomasi points land only on corners. A photograph with selected features overlaid: markers cluster on corners and texture junctions, never on the flat sky or along a single straight edge (the railing, the roofline). A few windows are annotated with their local eigenvalue pair $(\lambda_1,\lambda_2)$: large-and-large at the kept corners, large-and-near-zero on the rejected edges, near-zero-and-near-zero on the rejected flat regions. The overlay makes "good feature to track" visibly identical to "well-conditioned $M$" identical to "corner."

The minimum eigenvalue measures the weakest direction's absolute information, while the eigenvalue ratio measures conditioning. They are related but different: a matrix proportional to the identity can be perfectly conditioned and still carry almost no information if both eigenvalues are tiny. With a fixed noise and derivative convention, a minimum-eigenvalue threshold rejects that case. Large values also do not rule out a wrong correspondence on repeated texture.

Robustness: the ratio test and RANSAC⧉

in the book↗

A candidate correspondence can select the wrong repeated window, miss an occlusion, or match unrelated texture. These outliers can dominate a least-squares geometric fit. Descriptor ambiguity tests and geometric consensus address different parts of the problem.

Two classic filters make matching usable, and they attack the problem from opposite ends. One prunes matches before any geometry is fit, by spotting which matches are ambiguous. The other fits a transform despite the outliers that survive pruning, by replacing the fragile least-squares average with a robust consensus vote. Neither alone is enough; together they turn a 50%-garbage match set into a clean geometric model.

The ratio test: reject ambiguous matches before fitting⧉

in the book↗

The instinct, when you have a keypoint in image A and a set of candidates in image B, is to keep the match if the nearest descriptor is close. Lowe's ratio test (Lowe 2004 Lowe 2004) says that is the wrong question. Closeness in absolute terms is unreliable because a descriptor on a high-contrast corner is close to its true partner, a descriptor on flat texture is far from everything, and a single threshold on distance cannot serve both. The right question is about ambiguity: is the nearest match decisively better than the second-nearest one?

So for each keypoint, find its two nearest neighbors in descriptor space, at distances $d_1\le d_2$, and accept the match only if

$$ \frac{d_1}{d_2} < \rho, \qquad \rho \approx 0.7\text{–}0.8. $$

The logic is clean. A distinctive point (a unique corner of a window frame) has one obviously-best partner and everything else far away, so $d_1\ll d_2$ and the ratio is small: keep it. A point on repeated texture (one brick among a hundred) has a best match that is barely better than the next brick over, so $d_1\approx d_2$, the ratio is near $1$, and the match is thrown out (Figure 12.5.1). The test measures exactly the failure mode that breaks matching: it does not ask "is this match good?" but "is there a competitor that makes this match untrustworthy?" That is why it works where an absolute-distance threshold does not, because repeated structure produces near-ties, and near-ties are precisely what the ratio catches.

The ratio threshold is empirical and descriptor-dependent. Handle fewer than two candidates and zero second-neighbor distance explicitly. If a search returns squared distances, compare their ratio with the square of the distance-ratio threshold. Mutual nearest-neighbor checks impose another useful consistency condition but do not replace geometry.

fig-ratio-test
Figure 12.5.1 (reproduced). Ambiguity, not distance, is the test. Left: one query keypoint and its two nearest descriptors in the other image, with distances $d_1$ (nearest) and $d_2$ (second-nearest). A distinctive match has $d_1\ll d_2$, with one clear winner, and passes ($d_1/d_2<\rho$, kept). An ambiguous match (a point on repeated texture) has $d_1\approx d_2$, with two near-tied candidates, and fails (rejected). Right: histograms of the ratio $d_1/d_2$ for true versus false matches, which separate cleanly around $\rho\approx0.8$: true matches pile up at small ratios, false matches spread toward $1$. The threshold slices between the two populations.

Rejecting ambiguity costs some correct matches too. A real window corner may have a nearly identical neighbor on the same façade, so its descriptor does not identify a unique partner even when the best candidate happens to be right. Lowering the ratio threshold generally rejects more such cases. This is a precision/recall choice before geometric fitting, not proof that the remaining pairs are correct.

Deep learning approaches to sparse matching⧉

optional

The classical pipeline, a hand-designed detector, a hand-designed descriptor, and a nearest-neighbor matcher, is exactly the kind of three-stage hand-built system that deep learning tends to replace end to end. Each stage was an act of human intuition: Harris Harris & Stephens 1988 decided a corner was where the structure tensor had two large eigenvalues; SIFT Lowe 2004 decided a neighborhood was best summarized by gradient-orientation histograms; the matcher decided two points correspond when their descriptors are nearest in Euclidean distance. Every one of those decisions is a candidate for the L7.6 move: replace the hand-designed operator with one trained from data, and the history of learned matching is the story of that move being applied to more of the pipeline.

It arrives in three waves, each absorbing more of the pipeline. First, learned local features that play SIFT's role: a single network detects and describes, trained for repeatability and matchability rather than designed by intuition (LIFT Yi et al. 2016 (LIFT), SuperPoint, D2-Net Dusmanu et al. 2019 (D2-Net), R2D2 Revaud et al. 2019 (R2D2)). Second, learned matching that reasons about the whole set of features at once instead of deciding each point independently: SuperGlue and the faster LightGlue Lindenberger, Sarlin & Pollefeys 2023 (LightGlue) cast matching as an attention-based assignment, while detector-free matchers like LoFTR skip keypoints entirely. Third, the 3-D-aware turn, where DUSt3R and MASt3R Leroy et al. 2024 (MASt3R) regress dense pointmaps straight from an image pair, so correspondence, camera pose, and depth all fall out together and matching stops being a separate stage at all. Front end, then middle, then the whole thing folded into geometry. The task is fixed; the pipeline is progressively learned.

💡 Big lesson ((L7.6), recurrence)

A learned operator swaps a hand-designed prior for one learned from data, and here it walks the whole pipeline. Classical sparse matching is three hand-built operators in series: a detector, a descriptor, a matcher (plus a robust back end). Wave one neuralizes the front end: keypoints and descriptors are now network outputs, trained for the very property (repeatability, matchability) the hand designs only approximated. Wave two neuralizes the middle: the matcher becomes a network that sees all the features at once and respects their mutual geometric consistency, instead of a per-point nearest-neighbor lookup. Wave three dissolves the pipeline into geometry: predict the scene's 3-D points per pixel and the correspondence is whatever pixels land on the same point. The deeper you go, the more of the classical chain is absorbed; what survives untouched is the problem Lowe and Harris posed. (L7.6 first appears in Chapter 7.3, Deep learning; this is a recurrence, the same move that powers RAFT in Chapter 12.8, Optical flow and the learned point trackers in Chapter 12.4, Feature tracking.)

Learned local features: SIFT's job, done by a network⧉

optional

The first wave replaces SIFT's two separate stages, the Difference-of-Gaussian detector and the gradient-histogram descriptor, with a single convolutional network that does both. The architecture is now standard: a shared encoder processes the image once, then splits into two heads. A detector head emits a keypoint score map (where the keypoints are), and a descriptor head emits a dense descriptor field (one descriptor vector per location). The two heads are trained together, so the points the detector likes are exactly the points the descriptor can match well, a cooperation the hand-built pipeline never had, since SIFT's detector and descriptor were designed independently. LIFT (Yi et al., 2016) first showed the whole detect-orient-describe pipeline could be learned end-to-end; SuperPoint (DeTone et al., 2018) DeTone et al. 2018 (SuperPoint) made it fast and self-supervised; D2-Net (Dusmanu et al., 2019) and R2D2 (Revaud et al., 2019) refined what "a good keypoint" should mean (Figure 12.6.1).

The obvious difficulty is supervision: there is no ground-truth "corner" to train against. Nobody can label, pixel by pixel, which points are truly repeatable across viewpoint and lighting, so a network has nothing to imitate. SuperPoint's answer, homographic adaptation, became the template for later work. Take an image, warp it by many known random homographies, run the current detector on each warped copy, then un-warp the detections back to the original frame and demand that they agree. A point that fires consistently across many synthetic warps is, by construction, repeatable under those transforms; a point that fires in only one warp is noise. Repeatability-under-known-transforms becomes the training signal, manufactured from the warps themselves, with no human annotation. R2D2 pushes the idea further by training the descriptor for reliability alongside the detector's repeatability, explicitly learning that a point can be easy to find yet hard to match (a repeated texture), and that those points should be down-weighted.

Little about the interface changes. The task is identical to SIFT's (emit repeatable, matchable points), and only the operators move from hand-design to data: what counts as a keypoint, and what the descriptor encodes. Because the output is still a set of (location, descriptor) pairs, these networks are drop-in front ends: their points feed the very same ratio-test-then-RANSAC back end from Chapter 12.5, Robustness: the ratio test and RANSAC, with no change downstream. That drop-in property is why they were adopted quickly: you could swap SuperPoint for SIFT in an existing structure-from-motion pipeline and keep everything else.

fig-learned-feature-pipeline
Figure 12.6.1 (reproduced). One network does SIFT's two jobs. A shared CNN encoder ingests the image once and splits into two heads: a detector head producing a keypoint score map (bright where a repeatable point should fire) and a descriptor head producing a dense descriptor field (a vector per location), the two trained to cooperate. The inset shows the self-supervision method, homographic adaptation: warp the image by a known homography, detect on the warped copy, un-warp the detections back, and demand they agree with the detections on the original; repeatability under known warps is the manufactured training label.

Fast matching⧉

Approximate nearest neighbors for sparse descriptors⧉

optional

Start with the sparse case: you have two sets of descriptors, say a few thousand SIFT Lowe 2004 vectors per image or a database of a billion, and for each query vector you want the closest one in Euclidean (or Hamming) distance. The textbook data structure is the kd-tree, which recursively splits the point set on alternating coordinate axes and, at query time, descends to the leaf containing the query and then backtracks into neighboring cells that might hold something closer. In low dimensions this backtracking is bounded and the search is logarithmic. In high dimensions it is a catastrophe: the query's true nearest neighbor can sit just across almost any of the splitting planes, so the tree must backtrack through exponentially many cells. By the time you reach the 128 dimensions of SIFT, the kd-tree has quietly become a slow brute-force scan (Figure 12.7.1). This is the curse of dimensionality, and it is the wall every method here is built to get around, not by searching faster, but by searching less, and accepting an approximate nearest neighbor in exchange.

Three families do the work. The first is randomized kd-trees, productized as FLANN (Muja & Lowe 2009, "Fast Library for Approximate Nearest Neighbors", and note whose name is on it: Lowe, the author of SIFT, building the search his own descriptors needed). The trick is to build several kd-trees, each choosing its split dimension randomly from several high-variance coordinate dimensions, and at query time search all of them but only to a bounded number of leaves: you stop early, before backtracking explodes, and take the best candidate found across the trees. You give up the guarantee of finding the true nearest neighbor; you gain a search that stays fast in high dimensions, with recall you dial in by how many leaves you allow. The second is locality-sensitive hashing (LSH) Indyk & Motwani 1998 (LSH): design a hash function with the property that nearby points are likely to collide into the same bucket, then, to answer a query, hash it and scan only the handful of points in its bucket. Where a hash table normally scatters similar keys, LSH deliberately clusters them, so a query only has to scan one small bucket. The third, and the one that scales to billions, is product quantization (PQ) (Jégou, Douze & Schmid 2011): split each vector into chunks, quantize each chunk against its own small codebook, and store every vector as a short tuple of codebook indices. A billion 128-dimensional floats will not fit in memory; a billion 16-byte PQ codes will. Because distances decompose chunk-by-chunk, comparing a query against a code becomes a few table look-ups instead of a 128-term dot product. This is the lineage behind modern vector-search systems such as FAISS Johnson, Douze & Jégou 2021 (FAISS) and ScaNN Guo et al. 2020 (ScaNN).

The point of all three is the trade-off itself, not any single setting. Each knob trades recall (did you find the true nearest neighbor?) against speed and memory, and the right operating point is an application decision, not an algorithm one. A one-off structure-from-motion reconstruction run overnight can afford near-exact search; a phone retrieving an image against a million-item index, in the time it takes to lift it, cannot, and will happily accept ninety-percent recall for a hundred-fold speed-up. When a system today says it does "vector search," this is what it is doing.

fig-ann-tradeoff
Figure 12.7.1 (reproduced). Why exact nearest neighbor fails in high dimensions, and what approximate search buys. Left: a 2-D sketch, a query point and its true nearest neighbor, with the kd-tree cells drawn in. An exact search must backtrack across many cells because the true neighbor can lie just across any splitting plane, and the number of cells to check explodes with dimension; an approximate method checks only a few buckets or leaves and returns a point that is near-est, not provably nearest. Right: the accuracy-versus-speed curve this implies, exact search pinned at one extreme (perfect recall, ruinous cost), with LSH / PQ / randomized kd-trees strung along the trade-off, each dialling recall down for speed and memory. The figure's whole message is that the curve, not any single point on it, is the object of study.

Automatic panorama stitching from multiple views and feature matching⧉

in the book↗
📎 Problem set

PS7 builds the automatic panorama: Harris, descriptors, the 2NN test, RANSAC, and blending. → Chapter 1.5, Problem sets (appendix).

The manual stitcher needs corresponding scene points. Automatic feature matching supplies candidates, then geometric estimation tests which can be explained by a common map. Preserve that verification step even when a descriptor match looks confident.

A wide panorama requires enough overlap and distinctive content to connect the images. Repeated windows, blank walls and moving subjects can defeat an otherwise appropriate estimator.

The same pipeline runs in many places: phone panorama modes, 360° cameras that stitch several fisheye views, robotic heads that shoot gigapixel mosaics tile by tile, aerial and satellite mosaics, and whole-slide scanners in microscopy. In the book's terms a panorama is multiple-exposure imaging along the field-of-view axis, as a bracket extends range and a focal stack extends depth of field; varying position rather than direction leads instead to light fields and 3-D reconstruction, where one homography no longer explains the images.

Why not brute force, and the two sub-problems⧉

optional

Exhaustively sampling eight homography coefficients is impractical. Sparse features provide an initialization from selected points. Direct alignment is another useful method: with a good initialization, iterative image-based optimization can estimate or refine a transform without an exhaustive search (Chapter 12.1, Brute force).

Interest points concentrate the match search on localized structure. Flat regions offer little local position information, while edges constrain motion mostly across the edge. Feature matching can still fail on repeated patterns or large appearance changes.

That plan decomposes into two sub-problems, the chapter's skeleton:

In a classical detector/descriptor pipeline, features are computed independently and then matched. Joint learned matchers can exchange information between images, so independence is a property of this baseline, not a rule for every algorithm.

fig-feature-pipeline
Figure 20.2.1 (reproduced). The whole automatic system on one strip. Five boxes, left to right: detect distinctive points independently in each image (Harris corners, or scale-invariant feature transform (SIFT) keypoints); describe each point's neighborhood with an invariant descriptor (a normalized patch, or the 128-D SIFT vector); match descriptors across images by nearest neighbor and prune ambiguous matches with the ratio test $d_1/d_2<\rho$; robustly fit the homography $H$ from the surviving, still-outlier-ridden matches with RANSAC; then warp and blend into the panorama. The dense brute-force alternative (discretize the homography's eight coefficients and search by full-image SSD) is shown crossed out beside it: combinatorially hopeless and not robust to motion.

The feature pipeline, recalled⧉

optional

The detect → describe → match → robustly-fit pipeline is built in full in Part 12, Matching pixels across space and time, and there is no profit in re-deriving it here. Chapter 12.3, Sparse matching, develops the detectors and descriptors: the structure tensor $M=\sum w\,\nabla I\,\nabla I^\top$ and its eigenvalue partition into flat / edge / corner, the Harris response $R=\det M-k(\operatorname{tr}M)^2$ and Shi–Tomasi, the scale axis that Harris lacks, and SIFT: Difference-of-Gaussians scale-space, the 26-neighbor space-and-scale extremum, a canonical orientation, and the $4\times4\times8=128$-dimensional descriptor, together with the broader detector/descriptor zoo. Chapter 12.5, Robustness: the ratio test and RANSAC, develops the clean-up: Lowe's ratio test and RANSAC. For panorama stitching we simply use that pipeline, so a one-paragraph recall is enough before we turn to the homography-specific orchestration that this chapter owns.

Here is the pipeline as it runs on a pair of overlapping frames, with each stage a pointer into that part (Figure 20.2.1):

After feature initialization, direct photometric refinement can use additional image information when exposure and visibility are modeled appropriately.

fig-pano-harris
Figure 20.2.2 (reproduced). Harris, component by component (interactive). The structure-tensor pipeline shown live on an image you can upload: luminance → gradient magnitude → the corner-response heatmap $R=\det M-k(\operatorname{tr}M)^2$ → the corners surviving threshold and non-maximum suppression, with the detector's $k$, scale $\sigma$, threshold, and corner-count knobs exposed.
fig-pano-2nn
Figure 20.2.3 (reproduced). Why the ratio test works (interactive). Two overlapping crops of one photograph, the second warped by a known rotation and scale, have their Harris corners matched by normalized-patch descriptors, and each match is checked against the known warp: green right, red wrong. Left: the matches spread by their best-match distance $d_1$; right: by the ratio $d_1/d_2$ to the second-nearest neighbor. A match is kept left of the dashed threshold, black rings mark the ones a threshold gets wrong, and each plot gives its accuracy and the best accuracy any threshold could reach; "best thresholds" moves both sliders to those cuts. On the facade, whose repeated windows make wrong matches as close as right ones, the best distance cut reaches about 72%, hardly better than rejecting every match (70%), and the ratio about 90%: a match to the wrong window has a second-nearest neighbor, the right window or another one, almost as close, so its ratio is near 1. Change the overlap, the warp or the photograph, or pool all six samples.

A synthetic warp provides exact correspondence truth but omits many real capture changes. Evaluate ratio and distance thresholds on repeated texture, exposure differences and non-overlap. The ratio test rejects ambiguity in descriptor space; it can also reject correct matches or retain a wrong distinctive one.

Recap: big lessons in this lecture

💡 Big lesson (L6.6) — differentiation is convolution

Finite differences are convolutions with signed kernels under a declared indexing convention. In the continuous setting, $\partial_x(g*I)=(\partial_x g)*I$: convolving with a derivative-of-Gaussian differentiates a smoothed image. Gradient components are linear; gradient magnitude, thresholding, and a complete edge detector generally are not.

💡 Big lesson (L12.1): the structure tensor, three jobs

The same $2\times2$ matrix $M=\sum_W \nabla I\,\nabla I^{\top}$ answers three questions across this part, and the unity is the point. Is this a good point to detect? Yes, where $M$ has two large eigenvalues, a corner: that is Harris / Shi–Tomasi, here. Is this patch's motion solve well-conditioned? The very same matrix, now required invertible: that is KLT (Chapter 12.4, Feature tracking). What is the local flow constraint? $M$ is the normal-equations matrix $A^\top A$: that is Lucas–Kanade (Chapter 12.8, Optical flow). Detect with it, track with it, solve flow with it: one matrix, read three ways. Corners are special for a deep reason: the same both-directions-vary condition that localises a point is also what makes its motion recoverable. So "good to detect" and "good to track" are not two coincidentally-aligned criteria; they are one statement about $M$.

💡 Big lesson ((L7.6), recurrence)

A learned operator swaps a hand-designed prior for one learned from data, and here it walks the whole pipeline. Classical sparse matching is three hand-built operators in series: a detector, a descriptor, a matcher (plus a robust back end). Wave one neuralizes the front end: keypoints and descriptors are now network outputs, trained for the very property (repeatability, matchability) the hand designs only approximated. Wave two neuralizes the middle: the matcher becomes a network that sees all the features at once and respects their mutual geometric consistency, instead of a per-point nearest-neighbor lookup. Wave three dissolves the pipeline into geometry: predict the scene's 3-D points per pixel and the correspondence is whatever pixels land on the same point. The deeper you go, the more of the classical chain is absorbed; what survives untouched is the problem Lowe and Harris posed. (L7.6 first appears in Chapter 7.3, Deep learning; this is a recurrence, the same move that powers RAFT in Chapter 12.8, Optical flow and the learned point trackers in Chapter 12.4, Feature tracking.)