Feature Detection & Tracking

A camera can follow a corner, but not a point on an edge or a blank wall. Shift an image 2 px right and 1 px down. In a window on a corner, Lucas–Kanade finds (2.00, 1.00) px in 4 steps. On an edge it finds only the 1 px across the edge. On a blank wall it finds nothing. One 2 × 2 matrix, G, says which.

Put the window on the edge, then on the wall, then on the corner. Then drag the shift. Then we build it piece by piece: gradients, the matrix G, corner scores, FAST, scale, descriptors, matching and the tracker itself.

You need Lecture 5 (pixels, the camera frame and K), a matrix times a vector, the slope of a function and a little Python. We build the rest from zero.

Lecture 6 of 14 in our follow-along of MIT 16.485, Visual Navigation for Autonomous Vehicles (VNAV, taught by Luca Carlone). Every idea is re-taught here in our own words and devices. Previous: Lecture 5, image formation. Next: Lecture 7, two-view geometry.

Track a window

2.0 px
1.0 px

Illustrative toy image, 160 × 120 pixels, with noise of 1 grey level. Window 15 × 15 pixels. Real Lucas–Kanade runs in your browser; OpenCV's calcOpticalFlowPyrLK gives (2.00, 1.00) px on the same corner.

Chapter 0

The Re-Finding Problem

Pick a patch in one frame and count how many places in the next frame look the same

A drone films a street. Between two frames it moves a little, so every point in the image slides a few pixels. To work out how the drone moved, it must find the same scene points again in the new frame. Lecture 7 turns those pairs into motion. This lecture finds the pairs.

We cannot find every pixel again. Take a small square of pixels, a patch, and look for its best copy in the next frame. A patch of blank wall looks the same everywhere. A patch on an edge looks the same at every spot along the edge. Only a patch on a corner has one best copy.

Find your patch again

Frame 2 is frame 1 moved 5 px right and 3 px down. Tap frame 1 to choose a patch, or use the buttons. Purple dots in frame 2 are every place where the patch fits as well as the right answer.

Illustrative toy frames. Patch 9 × 9 pixels, search ±16 px. A place "fits" if its sum of squared differences is below 1,296, eight times what noise alone gives at the right place.

Count the fits. The corner patch fits in 1 place out of the 1,089 we search: the right one. The edge patch fits in 33 places, a line along the edge. The wall patch fits in all 1,089. A good feature, a point we can find again, is a patch with one clear best copy.

So the work splits in two. Detection picks the patches worth following. Tracking or matching finds each one in the next image. Both rest on how the brightness changes inside the patch.

Symptom: the drone's motion estimate jumps or drifts when it flies past a white wall or a long fence.

Measure: how many tracked points sit on corners. On a blank wall it can drop to a handful.

Fix: detect corners only, keep a minimum count spread over the image, and add another sensor such as an IMU (Lecture 11).

The road

  1. Gradients: how fast brightness changes, across and down.
  2. Structure tensor: one 2 × 2 matrix G per window (the hero's ellipse).
  3. Corner scores: Harris and Shi–Tomasi turn G into one number.
  4. FAST: a corner test with no gradients at all.
  5. Scale: find each blob at its own size.
  6. Descriptors: a fingerprint for each feature, SIFT and ORB.
  7. Matching: pair fingerprints and drop the doubtful pairs.
  8. Lucas–Kanade: solve for the shift with G (the hero's estimate).
  9. Showcase: track a whole street.
  10. Field guide: the formulas, the code and the credit.
A camera looks at a uniform white wall and moves 10 px to the right. What can a patch tracker report for points on the wall?

Chapter 1

Image Gradients: Which Way Is Brighter

Zoom into the pixels and watch an arrow at each one point toward brighter pixels

An image is a grid of numbers. Call the brightness of the pixel in column u and row v I(u, v), from 0 (black) to 255 (white). As in Lecture 5, u counts to the right and v counts down from the top-left corner.

The question for every pixel: how fast does brightness change if I step right, and if I step down? Those two slopes are the image gradient. We estimate each slope from the two neighbours, one step on each side. This is a central difference.

Say it aloud

I-u equals the brightness one pixel to the right minus the brightness one pixel to the left, over two. I-v is the same with the pixel below minus the pixel above.

Iu
I-u the slope to the right: grey levels gained per pixel stepped right.
Iv
I-v the slope downward: grey levels gained per pixel stepped down.
I(u, v)
I of u, v the brightness of the pixel in column u, row v, from 0 to 255.
In plain words

Take the right neighbour minus the left neighbour. The two are two pixels apart, so halve it. That is I-u. Do the same with the pixel below and the pixel above for I-v. The arrow (I-u, I-v) points the way brightness rises fastest.

With numbers

With made-up numbers: a 3 × 3 patch with rows (10, 10, 10), (10, 80, 80), (10, 80, 80). At the centre, I-u = (80 − 10) / 2 = 35 and I-v = (80 − 10) / 2 = 35. The arrow (35, 35) points right and down at 45°, toward the bright corner.

Read the arrows

Each square is one pixel of the toy image, with its grey level. Each purple arrow is that pixel's gradient. Choose a place and a way to estimate the slope.

The toy image of the hero, noise of 1 grey level. We divide Sobel by 8 so both estimates are in grey levels per pixel; we checked both against cv2.Sobel.

On the wall, the arrows are tiny and point anywhere: that is noise. On an edge, every arrow points the same way, across the edge. At a corner, the arrows point two ways. One arrow cannot tell an edge pixel from a corner pixel. The pattern of arrows over the whole patch can, and Chapter 2 measures it.

The Sobel filter averages the slope over three rows with weights 1, 2, 1. On the same 3 × 3 patch it gives (26.25, 26.25) instead of (35, 35): the same direction, smoothed, so noise matters less.

Symptom: gradient arrows on a flat wall are large and point in random directions.

Measure: the size of the arrows on a patch you know is flat. With noise of 1 grey level, each central-difference slope wobbles by about 0.7 grey levels per pixel.

Fix: smooth first (Sobel, or a small Gaussian blur), and judge a patch by many arrows, not one.

Brightness is 0 above a horizontal edge and 255 below it. Which slope is large on the edge?

Chapter 2

The Structure Tensor: One Matrix per Window

Close a corner from a straight edge to a sharp point and watch the matrix G grow a second direction

Here is Chapter 0's test as algebra. Slide the window by a small shift d = (du, dv) pixels and add up the squared change of every pixel in it. Call that total the error E(d). A good feature has a large E for every direction of d.

For a small shift, a pixel's brightness changes by its gradient times the shift: I(x + d) ≈ I(x) + Iu du + Iv dv. Square that change and add it over the window.

Say it aloud

E of d is about d-transpose G d, where G is the sum over the window of the two-by-two matrix I-u squared, I-u I-v, I-u I-v, I-v squared.

E(d)
E of d the error: the sum of squared brightness changes when the window slides by d.
d
d the shift (d-u, d-v) in pixels; d-transpose is the same two numbers written as a row.
G
G the structure tensor: a 2 × 2 matrix that summarises every gradient in the window.
ΣW
the sum over the window add one term per pixel of the window W, here 15 × 15 = 225 pixels.
Iu², IuIv, Iv²
I-u squared, I-u times I-v, I-v squared the products of one pixel's two slopes from Chapter 1.
In plain words

For each pixel in the window, multiply its slopes I-u and I-v together in the three ways and add them into G. Then the error for any shift d is d-transpose G d: no need to slide the window at all. A direction where G is small is a direction the window can slide without anyone noticing.

With numbers

With made-up numbers: a window of three pixels with gradients (40, 0), (0, 40) and (30, 30). G = (1,600 + 0 + 900, 0 + 0 + 900; 900, 0 + 1,600 + 900) = (2,500, 900; 900, 2,500). Slide 1 px right: E = 2,500. Slide one unit along (1, −1)/√2: E = 1,600, the smallest of any direction.

A symmetric 2 × 2 matrix has two eigenvalues, λ1 ≥ λ2: the largest and smallest E over all shifts of length 1. Here they are 3,400 and 1,600. The shifts with one fixed E form an ellipse, short where E grows fast. The hero draws it.

Close the corner

Left: a bright wedge with the blue window on its tip. Right: every pixel's gradient as a purple dot, and the shape of G. Turn the angle from a straight edge (180°) to a sharp point.

180°

Illustrative toy wedge, window 15 × 15, noise of 1 grey level. Exact sums in your browser.

A straight edge puts every dot on one line: λ2 is noise, about 116. Close it to 90° and the dots fill two arms: λ2 rises to 27,708, 70% of λ1. Sharpen past 90° and the two edges point nearly the same way again, so λ2 falls. A right angle is the best corner.

Symptom: a "corner" on a thin diagonal line or a gentle curve tracks badly.

Measure: λ2 / λ1. Near 0 means all gradients point one way, whatever λ1 says.

Fix: score by λ2, the weaker direction (Chapter 3), not by the gradient size.

A window's G has eigenvalues λ1 = 1,200 and λ2 = 8. What is the window on?

Chapter 3

Harris and Shi–Tomasi: A Score from G

Turn the score into a map over a whole wall and keep only its peaks

A detector turns G at every pixel into one number, a corner score, and keeps the pixels that beat a threshold and every neighbour. Two scores are standard. Both read the two eigenvalues of G from its trace, tr G = λ1 + λ2 (the sum of the diagonal), and its determinant, det G = λ1λ2.

Harris and Stephens (1988) avoid the square root of an eigenvalue formula. Their score R uses a small constant k, commonly 0.04 to 0.06.

Say it aloud

R equals det G minus k times trace-of-G squared.

R
R the Harris score: large and positive at a corner, negative on an edge, near 0 on a wall.
det G
det G the determinant: a times c minus b squared for G = (a, b; b, c). It equals λ1λ2.
k
k a constant we choose, commonly 0.04 to 0.06. Larger k punishes edges harder.
tr G
trace of G a + c, the sum of the diagonal. It equals λ1 + λ2.
In plain words

Multiply the eigenvalues (det G) and subtract k times their sum squared. If both are large, the product wins and R is positive. If one is near 0, the product is near 0 and the minus term wins, so R goes negative.

With numbers

G = (2,500, 900; 900, 2,500) from Chapter 2, k = 0.05: det G = 6,250,000 − 810,000 = 5,440,000 and tr G = 5,000. R = 5,440,000 − 0.05 × 25,000,000 = 4,190,000: a corner. An edge with G = (14,700, 0; 0, 0) gets R = 0 − 0.05 × 14,700² = −10,804,500.

Shi and Tomasi (1994) score by the weaker direction itself.

Say it aloud

Lambda-two equals trace-of-G over two, minus the square root of trace-of-G over two, squared, minus det G.

λ2
lambda-two the smaller eigenvalue of G: the error for the worst direction of shift. The Shi–Tomasi score.
tr G / 2
trace of G over two the mean of the two eigenvalues.
√
the square root of half the gap between the two eigenvalues.
det G
det G the product of the two eigenvalues.
In plain words

Two numbers with mean tr G / 2 and product det G sit the same distance either side of the mean. The square root is that distance. Subtract it from the mean to get the smaller one. Keep a window if λ2 beats a threshold.

With numbers

Same G: tr G / 2 = 2,500, det G = 5,440,000. √(6,250,000 − 5,440,000) = √810,000 = 900. So λ2 = 2,500 − 900 = 1,600 and λ1 = 3,400, as Chapter 2 found by sliding.

Map the corner score

Purple glow is the score at each pixel; edges that score below zero stay dark. Blue dots are the corners that beat the threshold and every neighbour within 5 px. Change the score, k and the threshold.

0.05
5% of peak

Illustrative toy wall, 240 × 150 pixels, window 5 × 5. Our Harris map matches cv2.cornerHarris to a correlation of 1.000; 39 of our 40 strongest Shi–Tomasi corners lie within 1.5 px of cv2.goodFeaturesToTrack's.

Last comes non-maximum suppression: keep a pixel only if no neighbour within a radius scores higher. Without it, each corner gives a blob of a dozen pixels.

Symptom: all your corners crowd into one textured part of the image.

Measure: corners per cell of a 4 × 4 grid.

Fix: a minimum distance between corners, or a quota per cell.

A pixel sits on a long straight edge. What sign is its Harris score R?

Chapter 4

FAST: A Corner Test with No Gradients

Light up the ring of sixteen pixels around a candidate and count the longest bright or dark arc

Harris needs gradients, products and sums at every pixel. A drone with a small computer wants something cheaper. FAST (Rosten and Drummond, 2006) compares raw brightness only, on a ring around the candidate pixel.

Draw a circle of radius 3 around the candidate pixel p. It passes through 16 pixels. Call the brightness of p Ip and pick a margin t, say 20 grey levels.

A ring pixel is brighter if it beats Ip + t. It is darker if it is below Ip − t. Otherwise it is similar. The pixel p is a corner if at least n ring pixels in a row are all brighter or all darker. The common choice is n = 9, called FAST-9.

Run the segment test

The blue square is the candidate p. Ring pixels that pass the test get a purple outline; a warm arc joins the longest run. Choose a place and the margin t.

20

The hero's toy image. Ring order and the n = 9 rule as in OpenCV's FAST_FEATURE_DETECTOR_TYPE_9_16. On this image rounded to whole grey levels, our test and OpenCV's flag the same 57 pixels at t = 20, without suppression.

Work the corner tip. p is the inside corner pixel of the bright rectangle, Ip = 155. With t = 20, darker means below 135. The ring reads 59, 60, 80, 128, then five bright pixels (177 to 204), then 130, 81, 60, 58, 54, 55, 55. The dark run wraps around the start: 7 at the end plus 4 at the start makes 11 in a row. 11 ≥ 9: corner.

Why 9 of 16? A straight edge splits the ring in half, so its longest run is about 8. Asking for more than half rejects every straight edge. On our edge pixel the best run is 7.

FAST is fast because most pixels fail early. For n = 12, test the four compass pixels of the ring first. At least three must agree, or FAST drops p after four reads. FAST gives no strength, so ORB (Chapter 6) ranks its corners by the Harris score.

Symptom: FAST returns thousands of corners on a noisy image, or none on a dim one.

Measure: the count per frame as the light changes. A fixed t in grey levels means a different test in a dark scene.

Fix: adapt t to keep the count near a target, then keep the best by Harris score with non-maximum suppression.

Why does FAST-9 ignore pixels on a straight edge?

Chapter 5

Scale: The Same Blob, Near and Far

Grow a blob and watch the strongest blur level follow its size

A lamp 5 m away fills 20 pixels. At 50 m it fills 2. A window of fixed size sees a different patch in each image, so Harris on a fixed window cannot match them. We need each feature's own size, its scale, and a patch cut to that size.

Blur the image with a Gaussian of width σ (sigma, in pixels). Call the blurred image L(u, v, σ). Small σ keeps fine detail; large σ keeps only big shapes. Stack many σs and you have a scale space. Lowe's SIFT (2004) subtracts neighbouring levels.

Say it aloud

D of u, v, sigma equals L of u, v, k-sigma minus L of u, v, sigma.

D
D the difference of Gaussians (DoG): how much a pixel changes between two blur levels.
σ
sigma the width of the Gaussian blur, in pixels. SIFT starts at 1.6.
L
L the image blurred with a Gaussian of the given width.
k
k the step between levels: 2 to the one-third, about 1.26, so three levels double σ.
In plain words

Blur the image a little more, by the factor k, and subtract the less blurred copy. A blob about as wide as sigma changes most, so D peaks there. Search D over u, v and sigma together. A point that beats all 26 neighbours (8 at its own level, 9 above, 9 below) is a keypoint with its own scale.

With numbers

A bright disc of radius 4 px, contrast 1. At its centre D is −0.150 for the levels 2.02 to 2.54, −0.169 for 2.54 to 3.20 and −0.154 for 3.20 to 4.03. The strongest pair sits around σ = 2.85, close to 4 / √2 = 2.83.

Find the blob's own size

Left: a bright disc with a purple circle at the size the detector picks. Right: the DoG strength at the disc's centre for each pair of SIFT levels, and the smooth curve it follows. Grow the disc.

4.0 px

Exact maths: at a disc's centre, L = 1 − e−r²/2σ², so D has a closed form. We checked it against SciPy Gaussian filtering of a drawn disc to within 1.5%. Levels σ = 1.6 × 2i/3.

Why subtract? A difference of two blurs is close to (k − 1)σ² times the Laplacian, the sum of second slopes. A blob of radius r answers it most at σ = r / √2. The σ² comes free, so small and big blobs score on one ruler.

SIFT drops weak extrema (contrast below 0.03) and points on edges. The keypoint keeps (u, v, σ), and Chapter 6 cuts its patch to that σ. Harris and FAST have no scale of their own. So ORB runs FAST on an image pyramid: by default in OpenCV, 8 levels, each 1.2 times smaller.

Symptom: features match well between frames, but not after the drone climbs or flies forward a long way.

Measure: the match count against the change of distance. Fixed-size patches fail beyond about a 1.5× size change.

Fix: detect in scale space (SIFT) or on a pyramid (ORB), and cut each patch to the keypoint's scale.

Why does SIFT search for extrema over (u, v, σ) and not only over (u, v)?

Chapter 6

Descriptors: A Fingerprint for Each Feature

Rotate a patch and watch which fingerprint survives

After a long gap or a loop back to a known place, a tracker has no recent position to start from. We need a short summary of the patch, a descriptor, that two views of the same point share and other points do not.

SIFT (Lowe, 2004) gives the keypoint an orientation: the peak of a 36-bin histogram of gradient directions. It turns a 16 × 16 sample grid to that orientation, at the keypoint's scale, and cuts it into 4 × 4 cells and builds an 8-bin histogram of gradient directions in each: 4 × 4 × 8 = 128 numbers. It scales the vector to length 1, clips entries above 0.2 and scales again, so light changes matter less. SIFT compares vectors by straight-line distance.

BRIEF (Calonder et al., 2010) is cheaper. Pick 256 pairs of pixel positions in the smoothed patch, once. Each pair is one test: 1 if the first pixel is darker than the second, else 0. That is 32 bytes, against SIFT's 512.

Say it aloud

d-H of a and b equals the sum over i of one wherever a-i differs from b-i.

dH
d-H the Hamming distance: how many bits differ, from 0 to 256.
Σi [ · ]
the sum over i of one where count the tests i = 1 to 256 where the condition holds.
ai, bi
a-i, b-i bit i of the two descriptors: the result of test i on each patch.
In plain words

Line up the two bit strings and count the places where they disagree. A processor does it with one XOR and one bit count per 64 bits.

With numbers

With made-up numbers: a = 1011 0010 and b = 1001 0110 differ in bits 3 and 6, so d-H = 2 out of 8. On our wall, the same patch in two frames differs in 0 to 10 of 256 bits; two unrelated patches differ in about 110, near half.

Rotate the patch

The patch is 31 × 31 pixels of stucco. Warm lines are 40 of the 256 tests. The strip shows all 256 bits; red ones flipped. Rotate the patch, then let the tests turn with it.

30°

Illustrative: our own BRIEF with 256 random Gaussian pairs on the toy wall, smoothed. ORB learns its pairs instead (rBRIEF); the steering by the intensity centroid is the same idea.

Fixed tests break under rotation. Turn the patch 30° and 99 of 256 bits flip, almost as many as for an unrelated patch (109). ORB (Rublee et al., 2011) steers the tests. It finds the patch's orientation from its intensity centroid, the brightness-weighted mean position, and turns the test pattern by that angle. Steered, the same 30° flips 2 bits.

ORB also learns its 256 pairs, choosing tests that vary a lot and agree little with each other. Its authors report it two orders of magnitude faster than SIFT in their tests.

Symptom: matching works in straight flight and collapses when the drone banks.

Measure: the right match's Hamming distance against the rotation. Fixed BRIEF nears 100 bits by 30°.

Fix: a rotation-aware descriptor (ORB, SIFT), or undo the gyro's roll first.

Why does ORB measure an orientation for each keypoint before it runs its tests?

Chapter 7

Matching and the Ratio Test

Tighten the ratio and watch the wrong matches go first

Two images, a list of descriptors in each. For every descriptor in image A, find the closest one in image B: its nearest neighbour. On our wall, with a true shift of (9, 4) px, that gives 54 right pairs out of 70. The other 16 are wrong, and half of them sit on the five identical windows.

A wrong pair looks like a right one: both have a closest neighbour. The difference is the second closest. A distinctive point has one close neighbour and then a gap. An ambiguous point has two neighbours almost as close. Call the closest distance d1 and the second closest d2.

Say it aloud

Keep the pair if d-one over d-two is less than r.

d1
d-one the distance from the query descriptor to its closest descriptor in the other image.
d2
d-two the distance to the second closest.
r
r the ratio threshold. Lowe used 0.8.
In plain words

For each query, find its two closest descriptors. Divide the closer distance d-one by the next one, d-two. If the best clearly beats the runner-up, the ratio is small and we keep the pair. If the two almost tie, the ratio is near 1 and we drop it.

With numbers

With made-up numbers: d-one = 31 and d-two = 78 give 0.40, kept. d-one = 42 and d-two = 51 give 0.82, dropped at r = 0.8. A brick in a repeated wall with 55 and 58 gives 0.95, dropped.

Set the ratio

Frame B is frame A moved (9, 4) px, so we can mark each kept pair right (green) or wrong (red). Dropped pairs fade. Below: each pair as a dot, d-one up, d-two across; the yellow line is d-one = r d-two.

0.80

Illustrative toy wall: 70 Shi–Tomasi corners per frame, our steered BRIEF, brute-force nearest neighbours. The same rule as OpenCV's knnMatch with k = 2.

At r = 0.8 the test keeps 55 pairs: 50 right, 5 wrong. The wrong share falls from 23% to 9%, for 4 right pairs lost. At 0.7 it keeps 47 with 1 wrong. On a test set of real images, Lowe (2004) found that 0.8 removed 90% of the false matches and less than 5% of the right ones. With OpenCV's ORB (100 keypoints, one level) on the same toy wall, 0.8 cuts the wrong share from 40% to 21%.

Symptom: the pose from two frames is wildly wrong, though "most" matches look fine.

Measure: the share of matches that break the geometry Lecture 7 fits. Even 9% wrong is too many for a least-squares fit.

Fix: the ratio test, a mutual check (A's best is B, and B's best is A), then RANSAC in Lecture 7 to throw out the rest.

A corner on a regular brick wall has d-one = 55 and d-two = 58. What does the ratio test with r = 0.8 do?

Chapter 8

Lucas–Kanade: Solve for the Shift

Step the solver toward the true shift, then add a pyramid when the shift is large

At 30 frames per second a point moves a few pixels per frame. We need no fingerprints for that: we solve for the shift d that makes the window in frame 2 look like the window in frame 1. This is Lucas–Kanade tracking (Lucas and Kanade, 1981); with Shi–Tomasi corners it is called KLT.

The assumption is brightness constancy: a scene point keeps its brightness, it only moves. So I2(x + d) = I1(x). Expand the left side for small d, as in Chapter 2. Call the change at a fixed pixel It = I2(x) − I1(x).

Say it aloud

I-u times d-u, plus I-v times d-v, plus I-t, equals zero.

Iu
I-u the pixel's slope to the right in frame 1, from Chapter 1.
Iv
I-v the pixel's slope downward in frame 1.
du, dv
d-u, d-v the unknown shift in pixels, right and down.
It
I-t frame 2 minus frame 1 at the same pixel.
In plain words

If the pattern moves by d, a pixel's brightness changes by its slope times the shift. That change must cancel the measured change I-t. One pixel gives one equation for two unknowns: it fixes only the part of d across its edge.

With numbers

With made-up numbers: I-u = 30, I-v = 10, I-t = −15. Then 30 d-u + 10 d-v = 15, and both (0.5, 0) and (0, 1.5) fit.

So use the whole window. Pick the shift that makes Σ(Iudu + Ivdv + It)² smallest: set its slopes in du and dv to zero.

Say it aloud

G times d equals b, where b is minus the sum over the window of the column I-u I-t, I-v I-t.

G
G the structure tensor of Chapter 2, from frame 1: the matrix the detector scored.
d
d the shift (d-u, d-v) we solve for, in pixels.
b
b minus the sum of each pixel's slope times its change in time.
ΣW
the sum over the window one term per pixel, 225 pixels for a 15 × 15 window.
In plain words

Build G from the slopes and b from the slopes times the change in time. Solve the 2 × 2 system for d. If λ2 is near zero, there is no single answer, so trackers keep only Shi–Tomasi corners. Move the window by d, recompute I-t, and repeat until the step is below 0.01 px.

With numbers

With made-up numbers: three pixels with slopes (30, 10), (0, 40), (20, 20) and changes −15, 20, −10. G = (1,300, 700; 700, 2,100) and b = (650, −450). Solving gives d = (0.75, −0.46) px.

The expansion holds for shifts of about a pixel or two. For more, use an image pyramid: halve the image again and again. A 12 px shift is 3 px two levels up. Solve there, double the answer, refine one level down. Bouguet's notes put the gain at 15× for 3 levels.

Step the solver

Left: a street patch with the blue window on one corner. Right: the plane of shifts; the pink dot is the true shift, the purple path is the solver. Set the shift and the pyramid, then press Play.

(12, 6) px

Illustrative toy street, window 15 × 15, each level a 2 × 2 average. OpenCV's calcOpticalFlowPyrLK gives the same answers: (−5.35, 6.01) px with maxLevel 0, (12.00, 6.01) px with maxLevel 2 or 3.

Without a pyramid, a 12 px shift lands the solver in the wrong valley: (−5.35, 6.00) px, 17 px from the truth. With 2 levels it reaches (12.00, 6.01) in 13 steps. At 16 px it needs 3.

Symptom: tracks jump to a neighbouring corner when the drone turns fast.

Measure: the forward-backward error: track 1 to 2, then 2 back to 1. A right track returns within a fraction of a pixel.

Fix: more pyramid levels, a gyro to predict the shift, and drop tracks that fail the check.

A window on a long straight edge has G with λ1 = 79,000 and λ2 = 107. What goes wrong when Lucas–Kanade solves G d = b there?

Chapter 9

Showcase: Track a Street

Drive past a street and break the tracker with speed, flicker and a passing pole

Here is the whole front end. A camera slides along a toy street. When tracks run low, the page detects Shi–Tomasi corners (Chapter 3). It follows every track with pyramidal Lucas–Kanade (Chapter 8). A track dies if its λ2 is too small, it leaves the view, or its window no longer matches: a mean leftover above 12 grey levels.

We know where each tracked point truly is, so the page can do what a drone cannot: mark a track that is alive but wrong. Try four things. Raise the speed to 12 px per frame with no pyramid. Add flicker: brightness constancy breaks and tracks die by the dozen. Turn on the pole and watch tracks behind it die. Then switch the pyramid back on.

Drive the tracker

Purple trails are live tracks; a red ring marks one more than 2 px from the truth. Blue dots are new corners. Red crosses are tracks that just died.

4 px/frame
0%

Illustrative toy street, 200 × 120 pixels per frame, noise of 1 grey level, window 15 × 15. Real detection and tracking in your browser; the truth comes from the known camera motion.

At 4 px per frame with 2 levels, the median track is within about 0.01 px of the truth. Flicker of 10% kills almost every track each frame, though the scene has not changed: Lucas–Kanade compares raw brightness. The usual fixes are to subtract each window's mean and divide by its spread, or to use binary tests that only compare pixels.

Chapter 10

Field Guide

Keep the formulas, the numbers and the code side by side

A tracker can find a patch again only if it has texture in two directions. The gradients of a window add up to one 2 × 2 matrix G; its smaller eigenvalue λ2 measures the worst direction. Harris and Shi–Tomasi score G; FAST checks a ring of pixels instead.

Scale space gives each blob its size. A descriptor (SIFT's 128 numbers, ORB's 256 bits) lets you match across long gaps, and the ratio test drops the doubtful pairs. Between neighbouring frames, Lucas–Kanade solves G d = b with the same G, on a pyramid for large shifts.

PieceFormulaNumber on this pageWatch out
GradientIu = (I(u+1, v) − I(u−1, v)) / 2(10, 80) neighbours: 35noise: smooth first
Structure tensorE(d) ≈ d⊤Gd, G = Σ ∇I∇I⊤(2,500, 900; 900, 2,500): λ 3,400, 1,600big λ1 alone is an edge
Harrisdet G − k (tr G)²k 0.05: 4,190,000k above 0.25 kills corners
Shi–Tomasiλ2 = tr/2 − √((tr/2)² − det)1,600spread corners out
FAST-99 of 16 ring pixels in a row beyond Ip ± tt 20: run of 11, cornerno score: rank by Harris
DoGL(kσ) − L(σ), k = 21/3radius 4: peak near σ 2.85drop edges and low contrast
DescriptorSIFT 4 × 4 × 8; BRIEF 256 bits, Hamming30°: 99 bits flip, steered 2steer for rotation
Ratio testd1 / d2 < 0.855 kept: 50 right, 5 wrongstill needs RANSAC
Lucas–KanadeG d = −Σ ∇I It(0.75, −0.46) px; 12 px needs 2 levelsbrightness constancy

The conventions on this page

The core, as code

python
import numpy as np, cv2

def grad(I):                                     # central differences, grey levels per px
    Iu = np.zeros_like(I); Iv = np.zeros_like(I)
    Iu[:, 1:-1] = (I[:, 2:] - I[:, :-2]) / 2
    Iv[1:-1, :] = (I[2:, :] - I[:-2, :]) / 2
    return Iu, Iv

def lk_step(I1, I2, u, v, h=7):                   # one Lucas-Kanade step at integer (u, v)
    Iu, Iv = grad(I1)
    w = np.s_[v-h:v+h+1, u-h:u+h+1]
    gu, gv, It = Iu[w].ravel(), Iv[w].ravel(), (I2[w] - I1[w]).ravel()
    G = np.array([[gu@gu, gu@gv], [gu@gv, gv@gv]])        # the structure tensor
    b = -np.array([gu@It, gv@It])
    lam2 = np.linalg.eigvalsh(G)[0]                      # Shi-Tomasi score of this window
    return np.linalg.solve(G, b), lam2

# the library versions
img1 = cv2.imread('f1.png', cv2.IMREAD_GRAYSCALE); img2 = cv2.imread('f2.png', cv2.IMREAD_GRAYSCALE)
p1 = cv2.goodFeaturesToTrack(img1, maxCorners=200, qualityLevel=0.01, minDistance=8)
p2, status, err = cv2.calcOpticalFlowPyrLK(img1, img2, p1, None, winSize=(15, 15), maxLevel=3)
back, st2, _ = cv2.calcOpticalFlowPyrLK(img2, img1, p2, None, winSize=(15, 15), maxLevel=3)
good = (status.ravel() == 1) & (np.linalg.norm(back - p1, axis=2).ravel() < 0.5)   # forward-backward check

orb = cv2.ORB_create(nfeatures=500)
ka, da = orb.detectAndCompute(img1, None); kb, db = orb.detectAndCompute(img2, None)
pairs = cv2.BFMatcher(cv2.NORM_HAMMING).knnMatch(da, db, k=2)
kept = [m for m, n in pairs if m.distance < 0.8 * n.distance]    # Lowe's ratio test

Where it sits

Lecture 5 turned 3D points into pixels. This lecture finds the same scene point in two images. Lecture 7 turns those pairs into the rotation and direction of travel between the views, with RANSAC to throw out the wrong pairs that survive here. Lecture 11 feeds the tracks to a filter with an IMU.

Keep going

The takeaway. Add up a window's gradients into G. If its smaller eigenvalue is large, the window can be found again: score it to detect, and solve G d = b to track. Describe it with bits to match it after a long gap, and keep only matches that clearly beat the runner-up.

Now press Present or Teach. Explain from memory why a tracker cannot follow an edge along itself. Derive G from a small shift, and say what Harris and Shi–Tomasi read from it. Say why FAST asks for 9 of 16, why SIFT searches over scale, and why ORB steers its tests. Then go back to the hero and say why the edge window finds 1 px and not 2.

Credit

VNAV Lecture 6: Feature Detection and Tracking
MIT 16.485 VNAV · Previous: image formation · Next: two-view geometry · Back to Gleams