Two Photos, Same Point: The Classic Edge-to-Corner-to-SIFT Matching Pipeline
Look at two photographs of the same building taken at different times, and your brain does something impressive in a fraction of a second: it pairs up the windows, the door frame, the sign on the wall. You can point to the same physical point in both images without thinking about it. A computer cannot do this at all, at least not out of the box. A pixel is just a brightness number, and that number changes with lighting, camera angle and time of day. The old problem the lecture this tutorial is built from opens with is: how do we make the computer see what our brain sees?
The classical answer is a chain of small, carefully designed steps, each one fixing a blind spot of the previous step. First we find where the image changes (gradients via Sobel). Then we clean those changes into thin, precise edges (Canny). Then we ask a harder question: which points can actually anchor a match across two photos? Edges fail, corners work (Harris). Corners only tell us where; we give them scale, rotation and a description (SIFT). Then we filter the raw matches twice, once per match and once globally (ratio test, then RANSAC), and finally we scale the whole trick up to millions of images (Bag of Visual Words). Here is the whole route before any math:
Each chapter of this tutorial is one stage of that chain. We will keep the mathematics at intuition level: enough to know why each formula exists, and what it trades off.
1. Why Raw Pixels Can't Be Matched: the Correspondence Problem and the Gradient as the First Anchor
The lecture introduces the matching challenge with two photographs of the same brick building. The wall, the windows and the corners are the same; the posters by the door have been swapped, and the light has shifted from a cool morning to a warm afternoon with long shadows.

Caption: The same building photographed twice. The structural elements a human would pair in a glance (walls, windows, arched door, corners) stayed the same; the poster contents and the lighting colour did not. The task ahead is to find which of these a program could grab onto.
The lecture's slide calls this the core problem in one line: pixels change (intensity, colour); geometry changes (perspective); find invariants. An invariant is a measurement that stays roughly the same across these changes, an anchor the computer can trust. Matching two photos, formally called solving the correspondence problem, is the search for such invariants. Your brain uses them effortlessly; the computer has to compute them explicitly.
The cheapest invariant: the gradient
The first invariant a program can compute is the gradient: the rate at which brightness changes as you move across the image. Where brightness is constant, the gradient is zero. Where an edge runs, the gradient is large. The Sobel operator computes this with two tiny 3×3 kernels, basically small weight patterns that get slid across the image, multiplying the kernel values with the underlying pixels and summing (that operation is a convolution):
$$Gx = \begin{bmatrix} -1 & 0 & +1 \ -2 & 0 & +2 \ -1 & 0 & +1 \end{bmatrix}, \qquad Gy = \begin{bmatrix} -1 & -2 & -1 \ 0 & 0 & 0 \ +1 & +2 & +1 \end{bmatrix}$$
Read the Gx pattern column by column: it compares the pixel's left neighbour (negative weights) with its right neighbour (positive weights), with the middle row doubled so the comparison is more robust to noise. Where brightness increases left to right, the +1 column lands on brighter pixels than the −1 column and the sum turns strongly positive. Where brightness decreases left to right, the sum turns negative. A flat region gives zero, because −1 + 0 + 1 cancels out. So Gx responds to vertical edges, which are exactly places where brightness changes left to right, and Gy responds to horizontal edges, where brightness changes top to bottom. The operator factors into a smoothing kernel [1, 2, 1] and a difference kernel [1, 0, −1], which is why Sobel is both cheap and slightly noise-resistant: it is the gradient of a lightly smoothed image, not a raw pixel difference Sobel.
Two directional answers are still not one answer, so Sobel combines them into a single vector field with magnitude and direction:
$$G = \sqrt{Gx^2 + Gy^2}, \qquad \Theta = \mathrm{atan2}(Gy, Gx)$$
The magnitude says how strongly the image changes at this pixel; the direction says which way it is changing. Both are needed by everything that follows. Here are the two outputs on real imagery: a dense magnitude map and a hue-encoded direction map of a synthetic circle.

Caption: Gradient magnitude $G = \sqrt{Gx^2 + Gy^2}$ on a real scene: the brick wall grid, the bike-rack arch and the bicycle handlebars light up wherever brightness changes. Note the lines are thick and the map is dense, not a set of clean single-pixel edges. That is raw material, not a finished product. Sobel
Caption: Gradient direction $\Theta = \mathrm{atan2}(Gy, Gx)$ around a circle, hue-encoded. Every edge pixel carries a direction, and the colour wheel wraps all the way around. That wrap-around is exactly why the next chapter's algorithm quantises directions into four buckets instead of working with continuous angles. Sobel
Sobel is a good start and nothing more. The lecture states three limitations that motivate everything after it. First, edges come out thick, several pixels wide, not single-pixel lines. Second, the operator is still noise-sensitive; its smoothing window is only three taps wide. Third, it does no thresholding: it returns a continuous magnitude map for every pixel, and never tells you which pixels count as edges. The lecture's own transition line: "Sobel gives us good gradients, but we need an entire pipeline to turn gradients into clean, precise edges. Enter Canny."
So the gradient is the first "where does the image change" signal a computer can compute. But a raw Sobel map is thick, noisy and un-thresholded; the entire edge story that follows is about cleaning that map up.
2. Cleaning Up the Gradient: Canny's Five Steps and Why It's Still the Gold Standard
Canny's edge detector is from 1986 and remains the default answer for clean edges. The lecture teaches it as a five-step pipeline: smooth, compute the gradient, thin the edges with non-maximum suppression, apply a dual threshold, and track edges with hysteresis. One honest caveat before we walk it: the 1986 paper itself is an argument about operator design, not a numbered five-step flow. John Canny set up three criteria (detect all real edges, localise them precisely, respond once per edge) and derived an optimal filter from them. The familiar five-step recipe is the post-1986 textbook repackaging of that argument. The paper's Figure 1 shows the core of the design reasoning: a noisy step edge, a crude difference-of-boxes operator firing multiple spurious peaks, and the first derivative of a Gaussian firing one clean peak.

Caption: Canny 1986, Fig. 1. The noisy step edge (top) processed by a difference-of-boxes operator (middle) produces broken, multi-peak responses, while the first derivative of a Gaussian (bottom) produces one clean peak at the true edge. This is operator design, not yet a five-step diagram. Canny 1986
Canny's own conclusion from this figure is the engineering claim every implementation relies on: the theoretically optimal operator looks almost indistinguishable from a Gaussian's first derivative in practice, and the Gaussian is far cheaper to compute in two dimensions Canny 1986. With that grounding, here are the five steps as the lecture packages them.
Step 1, Gaussian smoothing. Blur the image first so isolated noise pixels stop creating fake edges. The lecture treats the details (kernel size, σ) as the previous week's material and moves on.
Step 2, gradient computation. This is exactly the Sobel operator from the last chapter, giving magnitude and direction per pixel.
Step 3, non-maximum suppression (NMS). This is the step the lecture calls Canny's core innovation. The problem: after Sobel and smoothing, every edge is a band 5 to 10 pixels wide, because pixels near an edge all have elevated gradient. The fix: along the gradient direction, keep only the pixel with the largest gradient magnitude, the ridge of the band, and suppress the rest.

Caption: Non-maximum suppression on a one-dimensional gradient-magnitude curve. The peak is marked Keep (local maximum); every pixel on the slopes is marked Suppress. The result is a ridge of a single pixel instead of a thick band.
The direction matters because "the local maximum" has to be taken along the gradient direction, not around the pixel. So the continuous direction Θ is quantised into four buckets, and each pixel is compared only with its two neighbours along its bucket:
| Angle range | Quantised direction | Compare with |
|---|---|---|
| −22.5° to 22.5° | 0° | left and right neighbours |
| 22.5° to 67.5° | 45° | one diagonal pair |
| 67.5° to 112.5° | 90° | top and bottom neighbours |
| 112.5° to 157.5° | 135° | the other diagonal pair |
If the current pixel's magnitude is not greater than both neighbours, it is suppressed. A note for honesty's sake: this four-bucket quantisation is a textbook engineering trick added after the paper; Canny's original formulation marks the local maximum of the filter output along the gradient direction without committing to bins Canny 1986.
Steps 4 and 5, dual threshold and hysteresis. After NMS you still need to decide which ridge pixels are real edges. A single threshold forces an impossible trade-off, as the lecture table puts it: set it too high and noise is suppressed but real edges break into gaps; set it too low and contours stay complete but false edges flood in. Canny's answer is two thresholds plus connectivity. Pixels above the high threshold are strong edges, kept unconditionally as anchors. Pixels between low and high are weak edges, kept only if they touch a strong edge. Pixels below the low threshold are discarded. Then hysteresis propagates: every strong pixel acts as a seed, weak pixels connected to it (in an 8-neighbour sense) are promoted to strong, and isolated weak pixels are dropped as noise. Strength alone is not enough; connectivity decides. The lecture's one-liner: strong edges are seeds, weak edges near seeds grow, isolated weak edges die.

Caption: Dual threshold and hysteresis in one grid. Red pixels are strong edges (anchors, above T_high). Green pixels are weak edges connected to a strong edge, marked "Weak to Keep". Orange pixels with a cross are weak edges isolated from any strong edge, marked "Weak to Discard". The magnitude colour bar on the right shows the T_low and T_high cut lines.
Canny's paper describes exactly this rule: any part of a contour above the high threshold is output immediately, along with the whole connected segment that lies above the low threshold, and the ratio between the two thresholds in practice sits near two or three to one Canny 1986. In OpenCV the whole pipeline collapses to one call, cv2.Canny(gray, threshold1, threshold2), where the two numbers are the low and high thresholds OpenCV.
The lecture opened with a concrete goal: count coins in a photo by computer. Clean edges are what make that possible: you trace each closed contour (the lecture's analogy is a blind person running a hand along a wall: find where a boundary starts, follow it pixel by pixel until you return to the start, and that is one coin), then count the contours. Canny wins because it packages answers to one problem: remove noise, find where change is strongest, thin every edge to one pixel, then use connectivity rather than strength to keep only coherent contours. And now the tutorial turns to a much harder question than counting: can clean edges anchor a match between two photos?
3. Why Clean Edges Can't Anchor a Match: the Aperture Problem, and Corners as the Fix
Look at an edge through a small window, like looking through a keyhole. You can tell that something is changing brightness perpendicular to the edge, because that is what makes the edge visible at all. But slide your gaze along the edge, parallel to it, and the intensity barely changes. An edge point therefore cannot be told apart from its neighbours along the edge. This is the aperture problem, and it is fatal for matching: if you cannot say where on the edge you are, you cannot pair that edge point with its counterpart in the other photo. The lecture's figure makes the ambiguity visceral with question marks on every along-edge motion.

Caption: The aperture problem side by side with its fix. Left: a window on a diagonal edge sees motion along the edge as ambiguous, with question marks in both directions; the edge cannot be localised along itself. Right: the same window centred on a corner sees change in two perpendicular directions at once, which pins down a unique position.
The right half of that figure is the whole message of this chapter. A corner is where two edges meet, so it changes in two directions simultaneously. Change in two directions means a full two-dimensional constraint on position: nudge the window off the corner in any direction and the image content changes. That is precisely what a matcher needs. The lecture summarises the hierarchy in a table:
| Region | Directions of change | Localisability |
|---|---|---|
| Flat region | 0 | Poor |
| Edge | 1 | Cannot localise along the edge |
| Corner | 2 | Precise and unique |
Two hard requirements follow. A good feature must be repeatable, detectable across viewpoints and lighting, like a landmark you recognise from any direction; and it must be distinctive, not confusable with neighbouring points, like a landmark unlike anything nearby. Corners satisfy both. Edges satisfy neither, because of the aperture problem.
Why does this matter historically? Every detector that went before Harris had real weaknesses, and the 1988 Harris and Stephens paper demonstrates the alternates on a single test image: Moravec's detector sampled only four discrete directions and responded too readily to edges; Beaudet and Kitchen-Rosenfeld offered other viewpoints. None of them had a clean mathematical story.

Caption: Harris and Stephens 1988, Fig. 4: four corner operators on one test image. The panels compare Moravec (a), Beaudet (b), Kitchen-Rosenfeld (c) and Harris (d). This is a qualitative demonstration on a single image, not a scored benchmark: it motivates why an analytic definition of "corner" is worth the trouble. Harris 1988
So the score so far: an edge only tells you something changed, not where along it you are; only a point that changes in two directions at once pins down a location. The next chapter defines "corner" mathematically, which is exactly what Harris did.
4. Defining "Corner" Mathematically: the Structure Tensor, the det − k·trace² Shortcut, and Turning the R-Map into Keypoints
How do you turn the phrase "changes in two directions" into a test a computer can run on every pixel? Harris's idea, following Moravec, starts with a thought experiment: take a small window around the pixel, nudge it by a tiny shift (u, v), and measure how much the intensity inside the window changes. If the window sits on a flat region, a nudge changes almost nothing. On an edge, a nudge across the edge changes a lot, but a nudge along the edge changes almost nothing. On a corner, any nudge changes something. The quantity to compute is E(u, v), the summed squared intensity change for a shift (u, v).
The jump many learners trip on is how a window-shift experiment becomes a matrix with eigenvalues. Walk it one hop at a time. First hop: for small shifts, a first-order Taylor expansion says the brightness at the shifted position is approximately the brightness at the original position plus the shift times the local gradients: $I(x+u, y+v) \approx I(x, y) + u \cdot I_x + v \cdot I_y$, where $I_x$ and $I_y$ are exactly the Sobel gradients from chapter 1. Second hop: the squared change inside the window, summed over all pixels, collapses into a quadratic form in the shift:
$$E(u, v) \approx [u; v], M, \begin{bmatrix} u \ v \end{bmatrix}, \qquad M = \begin{bmatrix} \sum I_x^2 & \sum I_x I_y \ \sum I_x I_y & \sum I_y^2 \end{bmatrix}$$
The matrix M is the structure tensor. It summarises, inside the window, how much gradient energy there is and how correlated the two gradient directions are. Third hop: the eigenvalues of M tell you the change magnitude along the two principal axes of the window, which is the flat/edge/corner test. If both eigenvalues are small, nothing changes in any direction: flat. If one is large and the other small, change happens along one axis only: edge. If both are large, change happens in every direction: corner. The lecture bridges this with a picture before any of the algebra:

Caption: Structure tensor intuition as shapes. A flat patch maps to a tiny dot (both eigenvalues small); an edge maps to a thin ellipse in one principal direction (one eigenvalue large, one small); a corner maps to a near-circle (both large). The eigenvalues of the structure tensor describe how much the window "stretches" in each direction.
Checking eigenvalues per pixel would require solving a characteristic equation for every pixel, which is expensive. Harris's clever shortcut, already visible in the 1988 paper, uses two cheaper quantities. The determinant of M equals the product of the eigenvalues and the trace equals their sum, so both can be computed directly from the matrix entries without solving for eigenvalues. The Harris response is:
$$R = \det(M) - k \cdot \mathrm{trace}(M)^2$$
where det(M) = λ1·λ2 and trace(M) = λ1 + λ2. The classification falls out of the sign of R: large positive R means corner (both eigenvalues large), negative R means edge (one dominant), and R near zero means flat. The paper's Figure 5 draws the whole story in one picture: the (α, β) plane of the two eigenvalues, with heavy lines partitioning it into corner, edge and flat regions, and fine contours of equal R inside Harris 1988.

Caption: Harris 1988, Fig. 5, the α-β principal curvature plane. The heavy lines from the origin are the decision boundaries: the upper-left wedge is the edge region, the upper-right wedge is the corner region, and the area near the origin is flat. The fine lines are contours of equal Harris response R; R is positive in the corner region, negative in the edge region, and small in the flat region. One picture explains why a single scalar R replaces the whole eigen-decomposition. Harris 1988
One parameter needs an honest footnote. The 1988 paper leaves k free; the common range k ∈ [0.04, 0.06] is a later convention, and OpenCV defaults to 0.04 Harris 1988. The eigenvalue logic itself also reappears later: SIFT's edge-rejection filter is Harris's eigenvalue-ratio idea written on a different matrix, which you will meet in the next chapter.
From a smeared response map to clean keypoints
The raw R-map is not directly usable. A single corner lights up many neighbouring pixels, because the structure tensor sums gradients over a window and nearby windows see almost the same content. Three engineering steps clean it up, and they map onto three knobs of OpenCV's cv2.goodFeaturesToTrack(gray, maxCorners, qualityLevel, minDistance). First, non-maximum suppression on the R-map: keep only the local maximum response, so each real corner is represented by exactly one pixel. Second, a quality threshold: only keep corners whose response beats qualityLevel times the strongest response in the image, which removes weak, noise-driven candidates. Third, a minimum distance constraint: sort candidates by response, greedily pick the strongest, then suppress everything within a radius minDistance of it. The point of the radius is to stop feature clustering. As the lecture puts it, features often cluster in high-texture areas, leaving the rest of the image "blind"; the radius spreads anchors evenly. The lecture's defaults are qualityLevel = 0.01 and minDistance = 8–15. Here is the whole cleanup in one demo:

Caption: Harris post-processing on a building scene: the raw R-map is a smear of responses (corners spread to neighbours); after NMS each corner is a single pixel; after thresholding with qualityLevel = 0.01, 371 strong corners remain. The caption labels are lecture-demo values (7556 points after NMS, 371 after thresholding).
The minDistance effect is easy to see as a parameter sweep: with qualityLevel fixed and maxCorners capped at 500, increasing the radius from 1 to 40 spreads the same number of corners out, until the constraint gets so strong that only 211 candidates survive.
| minDistance | corners detected |
|---|---|
| 1 | 500 |
| 8 | 500 |
| 20 | 500 |
| 40 | 211 |
So Harris turns "looks like a corner" into one cheap scalar per pixel, R = det − k·trace², and then into a clean, evenly spread set of anchor points. But notice what each anchor carries: only a location. No scale, no orientation, no description of what the neighbourhood looks like. That is exactly the gap SIFT fills. The lecture frames the whole next chapter with a pair of questions: Harris finds where; who says what?
5. From "Where" to "What": How SIFT Survives Scale, Rotation and Lighting, and Builds a 128-D Fingerprint
A keypoint and a descriptor are different things, and keeping them separate is the key to understanding SIFT. A keypoint is an anchor with a location, a scale and an orientation: the lecture's analogy is a home address, which tells you where something is. A descriptor is a vector that describes the patch around the keypoint, the lecture's analogy being a fingerprint: it tells you what the neighbourhood looks like, in a form that can be compared across images. Harris produces keypoint locations only. SIFT produces both, and solves three problems Harris leaves wide open, one per gap:
| Harris's gap | Symptom | SIFT's fix |
|---|---|---|
| No scale | near and far views see different content | DoG scale space; the keypoint carries its own σ |
| No orientation | a rotated view misaligns patches | dominant orientation; rotate and align before describing |
| No descriptor | position alone cannot verify a match | a 128-D gradient histogram fingerprint |
Scale: Difference-of-Gaussians scale space
The same corner looks different when you zoom: close up it is a large structure, far away it shrinks to a speck. A matchable keypoint has to be detected at its natural scale. SIFT builds a Gaussian pyramid: the image is blurred with Gaussians at increasing σ, layer by layer. Then adjacent layers are subtracted. The result at each level is a Difference of Gaussians (DoG) image, $D(x, y, \sigma) = L(x, y, k\sigma) - L(x, y, \sigma)$, and the whole stack is the scale space.

Caption: DoG scale space. Left: a Gaussian pyramid built at scales σ, kσ, k²σ, k³σ. Middle: a subtraction operator. Right: the resulting DoG pyramid with one fewer layer. A candidate keypoint (the orange dot) is checked against its 26 neighbours in a 3×3×3 block of the DoG volume, marked here as the orange cube around an extremum.
Why subtract instead of doing something fancier? A keypoint is declared wherever the DoG volume has a 3-D extremum: a pixel that is larger (or smaller) than all of its neighbours in space and scale. The neighbourhood is 3×3×3, which means 26 neighbours: 8 in the same layer, 9 in the layer above, 9 below. An extremum in scale space means "this blob of texture is most pronounced at this exact blur level", and that blur level becomes the keypoint's σ. Two blobs of the same physical feature at different distances get matched at their own natural scales, which is the entire trick.

Caption: The 26-neighbour check as a 3D structure: three scale layers (bottom σ_{i−1}, middle σ_i, top σ_{i+1}), each a 3×3 grid of pixels. The red candidate in the middle layer is compared against 8 spatial neighbours in its layer, 9 in the layer above and 9 below, 26 in total.
Why is DoG a good idea at all? The theoretically attractive blob detector is the Laplacian of Gaussian (LoG), but it needs a separate convolution at every scale. SIFT exploits a physics identity: the heat-diffusion equation $\partial G / \partial \sigma = \sigma \nabla^2 G$ means the difference between two adjacent Gaussian layers is a scaled Laplacian of Gaussian, and those layers are already computed for the pyramid. Subtraction is nearly free. DoG is a cheap LoG, and the lecture calls this the key engineering decision that makes SIFT practical. With σ = 1.6 and k = √2 the approximation error is negligible Lowe 2004.
Raw DoG extrema are mostly junk; the lecture puts it at about 90% noise and edge responses. Lowe filters them with two sieves. The contrast sieve discards extrema whose DoG value is too small, |D(x̂)| < 0.03, on the grounds that a weak extremum is probably noise. The edge sieve attacks the aperture problem from chapter 3: an extremum sitting on an edge is not localisable. It builds the 2×2 Hessian of the DoG at the keypoint and tests the ratio of its principal curvatures, $\mathrm{Tr}(H)^2 / \mathrm{Det}(H) < (r+1)^2 / r$ with r = 10. High ratio means one curvature dominates, so the structure is edge-like and the candidate dies. The lecture adds a satisfying observation: this ratio test is the exact same logic as Harris's R, just written as a ratio of a matrix's eigenvalues rather than a det minus k·trace² Lowe 2004.
Rotation: the dominant orientation
A rotated camera rotates every patch, and a descriptor compared against a rotated patch will not match unless we normalise the rotation away. SIFT's answer: compute a 36-bin histogram of gradient directions over a large circular neighbourhood around the keypoint (36 bins, 10° each, weighted by gradient magnitude). The peak of that histogram is the keypoint's dominant orientation. Then, before anything is described, the coordinate frame is rotated so that this dominant orientation points "up". Up becomes relative to the feature's own structure, so a rotated view and an upright view describe the same thing in the same coordinates.

Caption: Making rotation disappear. Left: the keypoint neighbourhood with per-pixel gradient arrows. Middle: the 36-bin orientation histogram with one protruding dominant bar. Right: the same striped patch before (original, framed in blue) and after (aligned, framed in green) the coordinate frame is rotated to the dominant orientation.
Lighting: gradient histograms, and the 128-D fingerprint
Raw pixel values are hopeless under lighting change: add a constant to the illumination and every pixel changes. Pixel differences are still sensitive to absolute brightness. But gradient directions are stable: an edge is still oriented the same way whether it is brightly lit or in shadow. So SIFT describes a patch by counting gradient directions, not by storing pixels. Around the keypoint, each pixel's gradient direction is quantised into one of 8 bins (45° each), and its magnitude is accumulated into that bin. The result is a compact histogram of local texture that shrugs off brightness shifts.
The final descriptor assembly strings these histograms together. Take the oriented, scale-normalised 16×16 patch, divide it into a 4×4 grid of cells (each 4×4 pixels), build an 8-bin gradient-direction histogram per cell, and concatenate: 4 × 4 × 8 = 128 numbers. That vector is the 128-D SIFT descriptor. It is L2-normalised, clipped so no single component exceeds 0.2, and re-normalised; the clip stops a few enormous gradients (camera saturation, harsh shading) from dominating the fingerprint while keeping the overall orientation distribution intact Lowe 2004.

Caption: The 128-D descriptor in four columns: a 16×16 pixel patch, its per-pixel gradient directions and magnitudes, the 4×4 spatial grid pooling into 16 cells, and the final 128-D vector shown as a bar chart. Every one of the 128 numbers is a count of gradient directions inside one cell; never a raw pixel value.
The whole SIFT trick fits in one sentence, from the lecture: scale-space keypoints plus dominant orientation plus local gradient histograms give a 128-D fingerprint robust to lighting, rotation and scale. In practice it is one call in modern OpenCV: cv2.SIFT_create() followed by kp, des = sift.detectAndCompute(gray, None), where des has shape (N, 128) OpenCV. That ease of use is recent: SIFT sat behind a US patent (granted 2004) until it expired in 2020, at which point OpenCV moved SIFT out of the contrib module into the main repository, and cv2.SIFT_create() became a plain install away Lowe 2004. So: a keypoint tells you where; the fingerprint records what the neighbourhood looks like in a way that survives zoom, rotation and relighting. Now we finally have something to match.
6. Which Matches Can You Trust? The Ratio Test, Then RANSAC's Geometric Veto
Given two images, each with thousands of SIFT keypoints and 128-D descriptors, how do you pair them? The naive approach is brute force: for every descriptor in image A, find its nearest neighbour in image B by Euclidean distance. That is O(M·N) distance computations, roughly 10⁶ for 1k points per image, and it produces many false matches, especially on repetitive texture where many descriptors look alike. The lecture flags the scalability wall bluntly: 10⁶ queries against 10⁶ images would be 10¹² comparisons, which is why large-scale systems need something smarter (the next chapter).
Filter one, per match: Lowe's ratio test
The ratio test is the cheapest reliable filter, and its logic is subtle. For each query descriptor q, find its two nearest neighbours in the other image, m₁ at distance d₁ and m₂ at distance d₂. Keep the first match only if:
$$\frac{d_1}{d_2} < 0.75$$
Why the ratio rather than the raw distance? A small raw distance just means "this point is close to something"; in a dense, crowded descriptor space, near matches are cheap. The ratio asks a sharper question: is the best match clearly better than the second best? The second-nearest neighbour is a local measure of how crowded the descriptor space is around q. Ratio near 0 means the best match is uniquely good, a decisive winner. Ratio near 1 means the two candidates are basically tied, which is exactly what happens on repetitive texture where every wrong neighbour is just as close as the right one; such matches are discarded. The geometry is easy to picture:

Caption: The ratio test geometry. The query descriptor q in Image A has a nearest neighbour m₁ at distance d₁ and a second-nearest neighbour m₂ at distance d₂ in Image B. The match is kept when d₁/d₂ < 0.75, the lecture's default: the best match is clearly best.
The empirical justification comes from Lowe's own experiments. On a database of 40,000 keypoints, the distribution of the ratio for correct matches peaks near 0.4, while for incorrect matches it rises steeply near 1. The two curves meet in a gap around 0.75 to 0.8, and the cutoff sits in that gap:

Caption: Lowe 2004, Fig. 11: probability density of the descriptor-distance ratio for correct matches (solid, peaking near 0.4) versus incorrect matches (dashed, rising near 0.95). The decision threshold sits in the gap between the curves, which is why a ratio near 0 is strong evidence of a correct match. Lowe 2004
At the paper's operating point of 0.8 this rejects about 90% of false matches while losing under 5% of correct ones Lowe 2004. Both thresholds are real: 0.8 is the paper's value, 0.75 is the stricter default the lecture and OpenCV tutorials use, and any value in the gap is defensible. The canonical OpenCV recipe:
bf = cv2.BFMatcher()
knn_matches = bf.knnMatch(des1, des2, k=2)
good = []
for m, n in knn_matches:
if m.distance < 0.75 * n.distance:
good.append(m)
Filter two, globally: RANSAC's geometric veto
The ratio test inspects each match in isolation. It cannot see that a set of individually plausible matches disagrees about the overall scene geometry: repetitive texture defeats it (descriptors too similar), and so do locally similar patches that are not the same 3-D point. The lecture's key insight: all correct matches must satisfy the same global geometric transform. Between two views of a planar scene (or a purely rotated camera), that transform is a homography, a 3×3 matrix mapping points from one image to the other. It has 8 degrees of freedom (9 entries minus a scale ambiguity); each matched point pair provides 2 equations, so 4 point pairs determine it uniquely, as long as the 4 points are not collinear.
Why can't you just fit the homography with least squares? Because surviving matches still contain outliers, and one gross outlier can drag the whole fit off. This is the canonical failure Fischler and Bolles drew in the RANSAC paper: six points sit cleanly on y = x, a seventh at (10, 2) is a gross error, and the fitted line abandons the true slope to accommodate it.

Caption: Fischler and Bolles 1981, Fig. 1: six points on the ideal line y = x plus one gross outlier at (10, 2). The solid line is the ideal model; the dashed line is what the iterative "throw out the worst residual" heuristic converges to, wrongly tilted because the outlier survives the deletion loop. This is the failure mode RANSAC exists to avoid. Fischler-Bolles
RANSAC, Random Sample Consensus, takes the opposite strategy: fit from a tiny random sample, then let the data vote. The algorithm, as the lecture lays it out:
Each trial samples 4 random pairs, solves for a candidate H, and counts how many matches agree with it: those whose reprojection error, the distance between the predicted and observed position of the point, stays under a threshold such as 5 pixels. After N trials, take the H with the largest inlier set and re-fit it using all inliers. In OpenCV this is one call: H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0), where the mask flags inliers and outliers OpenCV.
The genuinely surprising claim is that random sampling is enough even when most matches are wrong. It is a probability calculation. If the inlier ratio is w and we sample n = 4 points, the chance a single sample is all-inlier is wⁿ. After N independent trials, the chance of at least one all-inlier sample is:
$$P = 1 - (1 - w^n)^N, \qquad N = \frac{\log(1-P)}{\log(1-w^n)}$$
The lecture's numbers, at roughly 98% confidence: a 50% inlier rate needs about 72 iterations, 30% needs 468, and even the awful case of 20% inliers needs only about 2498 iterations. The lecture flags honestly that the table uses practical values and the exact formula gives slightly different numbers, and it lands the punchline: even ~2500 iterations take milliseconds, so RANSAC is very efficient even when most of the input is garbage. The underlying theory is straight from Fischler and Bolles, who recommend trying two or three times the expected iteration count to be safe Fischler-Bolles. One more honesty note: Lowe's own paper solved geometric consistency with a Hough transform plus an affine fit, and the lecture pipeline substitutes RANSAC over a full homography, which is the variant OpenCV implements.
The payoff is a match set that is both individually unique and collectively consistent; the lecture's own closing demo overlays the survivors on the two building photos:

Caption: The lecture's "Final: SIFT + Ratio + RANSAC" result: dense green match lines linking corresponding points between the two views of the same brick building under different lighting. After both filters, the surviving matches all agree on one geometry.
A final sanity check any practitioner should run: warp image A into image B's coordinate frame with cv2.warpPerspective using the estimated H, blend half and half with cv2.addWeighted, and look. If the structures line up, the homography is right. Finally, know where the whole pipeline breaks, which the lecture lists as the typical failure cases: textureless regions (white walls, sky) where no corners exist to begin with; repetitive texture (window grids, brick) where descriptors are not distinctive and both filters fail; large deformation (clothing, facial expressions) where a single homography cannot describe the geometry; heavy occlusion where too little of the scene remains visible; and extreme lighting with blown-out highlights or deep shadows.

Caption: The lecture's "Nightmare 1": a checkerboard of stripes with a phase shift down the middle. Every stripe looks like every other stripe, so descriptors are near-identical, the ratio test sees ties everywhere, and no single consistent geometry exists. Repetitive patterns defeat both filters at once.
So matching is filtered twice: once per match by the ratio test, asking whether the best match is clearly unique, and once globally by RANSAC, asking whether the survivors obey one geometric transform. Random sampling works because even a handful of correct matches suffices to test a candidate transform, and the iteration formula tells you how many tries to budget.
7. Beyond Two Images: Panoramas, Localization, and Searching Millions of Photos with Bag of Words
Pairwise matching tops out at a few images. The pipeline pays off first in two classical applications. Panorama stitching matches the overlap region of two photographs, fits a homography with RANSAC, warps one image into the other's frame, and blends the seam; the lecture's demo shows street photos becoming one stitched panorama through exactly the keypoint, match, RANSAC + warp stages covered in this tutorial. Visual localization does the same matching against a database of geotagged reference images and reads the camera's position off the matched geometry; the lecture's demo estimates a live query frame's 6-DoF pose as x: 114.23°E, y: 22.31°N, z: 12 m, roll 0.5°, pitch −1.2°, yaw 88.4°. Both work because the chapter-5 descriptor was designed to survive viewpoint change.
From matching to retrieval: Bag of Visual Words
Now the scaling problem. Pairwise matching a query image against a million-image database one pair at a time is hopeless. The trick is to stop treating features as individuals and treat images as documents. That is the Bag of Visual Words idea from Sivic and Zisserman's "Video Google" paper, which borrowed the whole text-retrieval stack: images are documents, local descriptors are words, and searching images becomes searching a document collection by keyword, the way a search engine does Sivic 2003.
Building the system takes three stages. Vocabulary building: run SIFT over millions of descriptors from many images, cluster them with K-means into K cluster centres, and declare each centre a visual word; the set of centres is the codebook, and K ≈ 10⁴ is the lecture's default (the paper itself describes K-means without committing to a specific K). Encoding: map every descriptor of an image to the nearest visual word ID and count how often each word appears. Each image becomes one fixed-length histogram over the K words, with spatial positions deliberately thrown away; that is what "bag" means. Retrieval: build an inverted index, a lookup structure with an entry per visual word listing every image that contains it, like the index at the back of a book. A query is encoded the same way, and retrieval only examines images sharing at least one word with the query, so the cost is linear in shared word occurrences, not in the number of images Sivic 2003. Very common words that appear in almost every image are down-weighted (the visual version of a stop list), so retrieval is dominated by distinctive words. The lecture's pipeline diagram shows the whole flow:

Caption: The lecture's four-stage Bag of Visual Words pipeline: SIFT descriptors extracted from many images, K-means clustering into a visual vocabulary of K words, encoding each image as a histogram of word counts, and top-K retrieval in milliseconds with similarity scores (0.94 for the correct match in the lecture demo).
Pure histogram ranking can still be fooled: two images sharing many words may arrange them in completely different layouts. Sivic and Zisserman therefore add a spatial consistency re-ranking pass: after the inverted-index lookup, the matched regions must also agree on their relative layout. Each match votes for its candidate frame if neighbouring matches support the same arrangement, and matches without geometric support are rejected. This is a Hough-style vote on layout, explicitly not RANSAC, and it is what the double cross marks on the rejected correspondences in the figure below mean.

Caption: Spatial consistency check for matched regions between two frames. Matching ellipses connect corresponding affine regions; the two X marks sit on correspondences that fail the layout vote and are rejected. A geometric second pass prunes what the histogram ranking could not. Sivic 2003
The modern note: ORB
SIFT was patented until 2020, which for years made it awkward to ship in commercial products. ORB, proposed in 2011 by Rublee and co-workers, is the most successful patent-free alternative: it combines oFAST, a FAST corner detector with orientation added via the intensity centroid and with Harris's cornerness measure used to order the points, and rBRIEF, a rotated binary descriptor with learned test patterns. Its advantage is raw speed: on the paper's Pascal benchmark at 640×480, ORB took 15.3 ms per frame versus 5228.7 ms for SIFT, roughly two orders of magnitude faster, with matching quality that holds up in practice and a BSD license in OpenCV ORB. The figure below is the paper's own demonstration of ORB matching two photographs of the same magazine covers shot from very different viewpoints:

Caption: ORB matching two views of the same magazine covers under strong viewpoint change, from Rublee et al. 2011. Green lines are valid matches; red circles mark unmatched points. The speed numbers and the licence details come from the paper text, not from this figure. ORB
The local-feature paradigm this whole tutorial walked through is not a museum piece; recent work still extends it, for example matching features across different imaging modalities. But the core chain you now hold is the substrate underneath all of it. Everything started with a 3×3 gradient kernel asking where brightness changes, and ended with a search engine for images. Between those two points lie the answers to a sequence of questions that this tutorial has walked one at a time: pixels change, so find invariants; gradients are messy, so clean them into edges; edges slide, so keep corners; corners are points, so give them scale, orientation and a fingerprint; matches need trust, so filter per match and veto globally; and a thousand images need indexing, so turn descriptors into words.
References
Core sources referenced in this tutorial. Reading the originals is recommended for deeper study:
- Sobel operator (Wikipedia) — https://en.wikipedia.org/wiki/Sobel_operator
- Canny, "A Computational Approach to Edge Detection" (IEEE TPAMI 1986) — https://doi.org/10.1109/TPAMI.1986.4767851
- Harris & Stephens, "A Combined Corner and Edge Detector" (AVC 1988) — https://www.bmva-archive.org.uk/bmvc/1988/avc-88-023.pdf
- Lowe, "Distinctive Image Features from Scale-Invariant Keypoints" (IJCV 2004) — https://www.cs.ubc.ca/~lowe/papers/ijcv04.pdf
- Lowe, IJCV 2004, ratio-test section (Section 7.1, Fig. 11) — https://www.cs.ubc.ca/~lowe/papers/ijcv04.pdf
- Fischler & Bolles, "Random Sample Consensus: A Paradigm for Model Fitting" (CACM 1981) — https://www.sri.com/wp-content/uploads/2021/12/ransac-publication.pdf
- Sivic & Zisserman, "Video Google" (ICCV 2003) + Rublee et al., "ORB: An Efficient Alternative to SIFT or SURF" (ICCV 2011) — https://www.robots.ox.ac.uk/~vgg/publications/2003/Sivic03/
- OpenCV 4.x Python tutorials (features2d) — https://docs.opencv.org/4.x/dc/d0d/tutorial_py_features_harris.html