Algorithmcore
Kanade-Lucas-Tomasi tracker
Also called KLT tracker, KLT feature tracker.
Select corners whose window matrix has a large smaller eigenvalue, follow each one from frame to frame by pyramidal Lucas-Kanade steps, and drop a point that fails a check.
- Solves
- Optical flow
- Time
- Θ(W H m + N (W H + n (L + 1) k m)) worst · averageΘ(W H m + N (W H + n (L + 1) m)) best
- Space
- Θ(W H + n N) extra
- Where
- H = image height; L = the number of pyramid levels above level 0; N = the number of frames; W = image width; k = the iteration limit per level; m = the number of pixels in a window; n = the number of points
- Model
- Real RAM
- Properties
- deterministicnot exactiterativelocalonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Bruce D. Lucas, Takeo Kanade, Carlo Tomasi, Jianbo Shi, 1991
The Kanade-Lucas-Tomasi tracker (KLT) follows a set of small image windows through a video. It chooses the windows in the first frame with the rule of the Shi-Tomasi corner detector: keep the pixels where the smaller eigenvalue of the 2 by 2 gradient matrix of the window is large. It then finds the shift of each window from one frame to the next with the Lucas-Kanade method, run from coarse to fine on a Gaussian pyramid so that shifts of many pixels stay inside the range of the linearization. A point is dropped when its window loses texture, leaves the image or fails a forward-backward check. The output is a sparse optical flow in the form of point tracks, one feature track for each window.
In plain words
A video is a sequence of pictures. We want to follow some small patches from picture to picture. Not every patch can be followed: a patch on a blank wall looks the same everywhere, and a patch on a straight edge can slide along the edge without any visible change. So the tracker first picks patches that look like corners, where the picture changes in every direction, and keeps them a minimum distance apart. For each patch, it then asks where the same pattern is in the next picture. It answers with a few small correction steps, first on blurred and shrunk copies of the pictures, where a large motion looks small, and then on sharper copies. A patch that becomes flat, moves out of the picture, or cannot find its way back to its start when tracked backward is dropped.
The problem
The input is a sequence of gray frames of columns and rows, given as digital images. We use the convention of the computer vision pages: the pixel is the value , points right, points down, and the center of the pixel is the point . (The Lucas-Kanade method page puts the center at ; the two conventions differ by a constant shift and give the same displacements.) Off-grid values come from bilinear interpolation with clamped indices. A window of radius around a point is the set of points with integers .
The output is a set of tracks. A track is a list of points with in frame , such that the window around in shows the same pattern as the window around in up to a translation. For two frames and and a point , the shift is the that minimizes
The gradient matrix of the window, the structure tensor, is
If is near zero, the window has texture in at most one direction and is not determined (the aperture problem of optical flow).
The algorithm
The tracker has three parts: SELECT picks the points, PYR-LK finds one shift, and KLT runs them over the video. A pyramid with levels is built once per frame; level is level blurred with the binomial filter in both directions and then sampled at even and even . So the pixel of level is the point of level 0.
KLT(F₀, ..., F_N, r, L, k, τ, λ_min, ε_fb)- 1
P ← SELECT(F₀) - 2
for t ← 1 to N do - 3
for each point p in P do - 4
d ← PYR-LK(F_{t-1}, F_t, p) ▷ LOST if the window is flat - 5
b ← PYR-LK(F_t, F_{t-1}, p + d) ▷ track back - 6
if d or b is LOST or |d + b| > ε_fb then remove p from P - 7
else append p + d to the track of p; p ← p + d - 8
return the tracks SELECT(I) ▷ quality q, minimum distance δ- 9
for each pixel x whose window lies inside I do λ(x) ← λ_min(x) - 10
C ← the pixels with λ(x) ≥ q · max λ, sorted by decreasing λ - 11
P ← empty; for each c in C do if |c - p| ≥ δ for every p in P then add c to P - 12
return P PYR-LK(I, J, p) ▷ pyramids I⁰..I^L and J⁰..J^L- 13
g ← (0, 0) - 14
for ℓ ← L down to 0 do - 15
q ← p / 2^ℓ; G ← Σ_{x ∈ window(q)} ∇I^ℓ(x) ∇I^ℓ(x)ᵀ - 16
if the smaller eigenvalue of G < λ_min then return LOST - 17
ν ← (0, 0) - 18
repeat up to k times - 19
b ← Σ_{x ∈ window(q)} ∇I^ℓ(x) (I^ℓ(x) - J^ℓ(x + g + ν)) - 20
η ← G⁻¹ b; ν ← ν + η - 21
if |η| < τ then leave the loop - 22
if ℓ > 0 then g ← 2 (g + ν) else g ← g + ν - 23
return g
Lines L15 to L21 are one Lucas-Kanade solve at level , started from the guess that the coarser levels give. Two details follow Bouguet's description. First, the gradient and the matrix come from the first image , at the fixed window, so and its inverse are computed once per level and not once per iteration. For a translation this is the inverse compositional step of Baker and Matthews. Second, line L22 doubles the guess when it goes one level down, because one pixel at level is two pixels at level . The gradient at an off-grid point is the central difference of interpolated values, and likewise in .
Example
Selection on numbers. A window with has eigenvalues 4 and 16, so : there is texture in both directions. A window on a vertical step edge has all gradients of the form , so and . Line L16 rejects it at any positive threshold; a shift along the edge cannot be measured there.
A shift of 6 pixels. Frame is a texture made of 14 Gaussian blobs (seeded positions, widths from 2 to 3.5 pixels, heights from 60 to 200), and is the same texture moved by . The windows have (), the pyramid has (sizes 48, 24 and 12), . SELECT with and keeps 10 points, the first at , which has the largest of the image, about 32135. PYR-LK at this point gives:
| Level | Window center | Guess on entry | Result | Iterations |
|---|---|---|---|---|
| 2 | 5 | |||
| 1 | 2 | |||
| 0 | 1 |
The result is . The shift is at level 2, inside the range of one linearization, and each level down only corrects the doubled guess. Without the pyramid (), the solve starts 7.2 pixels from the answer: of the 6 selected points that lie at least 8 pixels inside the image, 4 still converge, but two stop 7.7 and 102.5 pixels from the true position. With all 6 are within 0.01 pixel.
A subpixel shift. With moved by instead, the same 6 points are found with errors from 0.011 to 0.049 pixel. The error does not go to zero because bilinear interpolation of the blobs is not exact between pixels; for the whole-pixel shift it is at most 0.0012 pixel, and the iteration stops at before the last digits settle.
The backward check. In the texture moves by , and a block with , is replaced by another texture, an occluder. The point at , under the occluder, moves to a wrong place, away; tracked back, it misses its start by 2.54 pixels, so line L6 drops it at . The point at is outside the occluder at level 0, but its window at level 2 covers it, and the result is 18 pixels off; the backward error is 18.5, and it is dropped too. The point at , at the edge of the occluder, ends 0.395 pixel from the truth with a backward error of only 0.11, so it is kept. The check is a heuristic, not a guarantee. The four points far from the occluder are kept with errors below 0.02 pixel.
Correctness
The full proof is in proofs/correctness.md. It shows four facts.
- Selection. The output of SELECT has three properties: every point passes the threshold, any two points are at least apart, and every rejected pixel above the threshold is within of a kept point with at least as large. The proof is by the order of the greedy loop.
- The step. For a translation, line L20 is the Gauss-Newton step of the inverse compositional formulation: it minimizes the linearization of with respect to , whose normal matrix is the fixed . When is nonsingular the step is unique.
- Fixed point and local convergence. If on the window for a shift , then is a fixed point of lines L19 and L20. For a smooth image model the Jacobian of the iteration map is zero at , so the iteration converges to from every start close enough to it, faster than any fixed linear rate.
- The pyramid. If level returns , the final shift is , and a translation by at level 0 is a translation by at level in the continuous model. So each level solves the same problem at a scale where the shift is smaller.
No result gives convergence from a far start: the range depends on the image content, as the example of the 7.2 pixel start shows. The forward-backward check of line L6 is a heuristic test with no guarantee.
Proof: The KLT selection is a greedy maximal spaced set, each tracking step is the inverse compositional Gauss-Newton step for a translation, an exact translation is a superlinearly attracting fixed point, and the pyramid sums the level resultsfull
We use the notation of the page: the window of a point is the set of points with integers , the gradient matrix is over the window, and is its smaller eigenvalue.
1. The selection
Claim 1. Let be the list of line L10, sorted by decreasing , and let be the output of line L11. Then (a) every has ; (b) any two points of are at least apart; (c) every has a point with and .
Proof. (a) , and line L10 puts in only pixels that pass the threshold. (b) A point is added only when its distance to every point already in is at least , and points are never removed; so for two points of , the later one was tested against the earlier one. (c) Let be rejected. When the loop reached , the test failed, so some already in had . That came earlier in , so by the order of , and stays in until the end.
Property (c) says that is a maximal set of spaced points: no rejected candidate can be added without breaking (b). It does not say that is the largest such set; that problem is a maximum independent set problem in a disk graph, and the greedy order by strength is a design choice.
2. The step at one level
Fix a level, drop the index , and fix the guess and the current correction . Write and . Consider the inverse compositional problem for a translation: find that minimizes
which asks which shift of the first window matches the current sample of . If solves it, then , that is with , so the new correction is , as in line L20.
Claim 2. The Gauss-Newton step for from is with , which is line L19 and line L20. It is unique when is nonsingular, and does not depend on .
Proof. The first-order expansion turns into the linear least-squares function
For any and , . is a sum of matrices , so . If , the difference is for every , so is a minimizer. If is nonsingular it is positive definite (its smaller eigenvalue is positive by line L16), so for and the minimizer is unique. Conversely, at a minimizer the gradient is zero. The gradient is taken on the fixed window of , so depends only on , and : line L15 computes it once per level.
3. Fixed point and local convergence
Here we use a smooth image model: and are continuously differentiable functions on the plane (for example the continuous image before sampling, or an interpolation with continuous derivatives). Define the map of one iteration
Claim 3. Suppose that for all in an open set that contains the window, and that is nonsingular. Then is a fixed point of , the Jacobian of at is zero, and there is a such that for every start with the iterates converge to with .
Proof. At every term is zero, so . The Jacobian is
The identity holds on an open set, so its derivatives agree there: for each window point . Then the sum is and . is continuous because is, so for each there is a with on the closed ball of radius around . Take . For , the mean value inequality on the segment from to (which lies in the convex set ) gives . So maps into , and by induction . For the rate, fix . Once is in the ball of radius , which happens for all large , the same inequality gives . As is arbitrary, the ratio tends to 0.
The claim needs the identity on an open set, not only on the window points: the step uses the gradients. Bilinear interpolation has kinks on the grid lines, so on sampled images the claim holds only approximately; this is why the subpixel example on the page ends at about 0.01 to 0.05 pixel and not at zero. The claim says nothing about starts far from . The size of depends on the image, which is the reason for the pyramid.
4. The pyramid
Claim 4. Let be the correction that level returns in lines L17 to L21. Then PYR-LK returns .
Proof. Let be the guess on entry to level , so and, by line L22, for . We show by induction on that . For the sum is empty and . If it holds for , then . At level 0, line L22 returns .
Claim 5. In the continuous model, let level of an image be for a blur kernel . If for all , then for all .
Proof. Convolution commutes with translation: . Put : .
So, with Claim 3 at each level, if the guess from level is within the attraction radius of level , the level converges to the right correction, and by Claim 4 the corrections add up to . The sampled pyramid of the page (binomial blur, then every second pixel) satisfies Claim 5 exactly only for shifts by multiples of ; for other shifts it holds up to the sampling error of the blur.
5. What is not proved
The backward check of lines L5 and L6 is a heuristic. A wrong track can return to its start (the page shows a point that is 0.395 pixel wrong with a backward error of 0.11), and a right track can fail the check when the backward solve starts outside its attraction radius. The tracker has no global convergence result: for a start outside the radius of Claim 3, the iteration can converge to another fixed point.
Complexity
- Selection. Line L9 computes at pixels. With a direct sum over each window, this is ; with box sums (an integral image of each of the three products) it is . Sorting the candidates costs , and the distance test in line L11 is in the direct form.
- One PYR-LK call. Line L15 reads points per level, and each of at most iterations reads points of . So the cost is in the worst case and when each level stops after one step.
- Pyramids. Level has about pixels, so a pyramid costs at most times a constant: per frame.
- Total. For points and frames, with the backward check (which doubles the PYR-LK calls), the time is in the real RAM. The extra space is for two pyramids and for the tracks.
Properties
- Sparse. It gives motion only at the selected points. The selection rule is the same quantity that decides whether the solve is well posed, so the tracker tracks only where it can.
- Subpixel. Positions are real numbers, and the error on a pure translation of a smooth image is limited by the interpolation.
- Translation only. Each step assumes that the window only moves. Rotation, scaling and perspective change the window, and over many frames the pattern drifts. Shi and Tomasi check the window against the first frame with an affine model to find such failures.
- Local and independent. Each point is tracked alone, so the cost is linear in the number of points and the points can be tracked in parallel.
- Not robust to occlusion by itself. An occluder that covers part of a window pulls the solution. The backward check and the window residual detect many of these cases but not all.
Variants and improvements
- Affine KLT. Track with an affine warp of the window (6 parameters), or use the affine model only to check the translation result, as Shi and Tomasi do.
- Gain and bias. Add a scale and an offset of brightness to the unknowns, so that a change of exposure does not bias the shift.
- Weighted windows. Weight the pixels of the window with a Gaussian, so that pixels near the border of the window count less.
- Robust losses. Replace the squared difference by a robust function and solve by reweighted least squares, which reduces the pull of occluded pixels.
- Median flow. Track a grid of points inside a box, drop the half with the largest backward error, and move the box by the median of the remaining shifts; this is the tracker of tracking-learning-detection.
- Replenishing. Run SELECT again every few frames in the regions without points, so that the number of tracks stays about constant; this is common in visual odometry.
- Direct methods. Align whole images or many pixels at once with a camera motion model instead of independent windows; see direct image alignment.
When to use it
Use KLT when you need many point tracks over a short video with small motion between frames, for example for visual odometry, structure from motion, video stabilization or as the motion part of an object tracker. It is fast, needs no training and gives subpixel positions. Use descriptor matching instead when the frames are far apart in time or viewpoint, when the motion is larger than the pyramid can absorb, or when the scene changes in brightness or scale.
Pitfalls
- Too few levels. A shift larger than about the radius of the window at the top level makes the solve converge to a wrong place, as in the example. Choose so that the largest expected shift divided by is a few pixels.
- Too many levels. At a coarse level the window covers a large part of the image, and other objects enter it. The occluder example shows a window that is clean at level 0 but wrong at level 2.
- A threshold without a scale. grows with the square of the contrast and with the window size. Make the threshold relative to the largest value, as SELECT does, or normalize the images.
- Points at the border. A window that leaves the image reads clamped values, which do not move with the scene. Drop points whose window leaves the image.
- Drift. Frame-to-frame tracking adds a small error at each frame. Over hundreds of frames the error grows; compare the window with its first appearance to detect it.
- Coordinate conventions. The pixel center is at here and at in some code. The pyramid map is right only for the first convention; with the second, it is . Mixing them biases every track by a fraction of a pixel per level.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kanade-lucas-tomasi-tracker/. The authors are listed in prov/GW9GYD.jsonl.
"""Kanade-Lucas-Tomasi feature tracker: Shi-Tomasi selection, pyramidal
Lucas-Kanade tracking in the form of Bouguet, and a forward-backward check.
Images are lists of rows of gray values, indexed img[v][u]: u is the column
(to the right) and v is the row (down). The center of pixel (u, v) is the
point (u, v). Off-grid values come from bilinear interpolation with the
indices clamped to the image. Level l of a pyramid has the pixel (u, v) at
the point (2^l u, 2^l v) of level 0.
"""
import math
LOST = None
def sample(img, u, v):
"""Bilinear sample at the real point (u, v), indices clamped."""
h, w = len(img), len(img[0])
u0, v0 = math.floor(u), math.floor(v)
fu, fv = u - u0, v - v0
def at(vv, uu):
return img[min(max(vv, 0), h - 1)][min(max(uu, 0), w - 1)]
top = (1 - fu) * at(v0, u0) + fu * at(v0, u0 + 1)
bottom = (1 - fu) * at(v0 + 1, u0) + fu * at(v0 + 1, u0 + 1)
return (1 - fv) * top + fv * bottom
def reduce_level(img):
"""Blur with the binomial filter (1, 4, 6, 4, 1) / 16 in both directions,
then keep the pixels with even u and even v."""
h, w = len(img), len(img[0])
k = (1, 4, 6, 4, 1)
tmp = [[sum(k[i + 2] * row[min(max(u + i, 0), w - 1)] for i in range(-2, 3)) / 16
for u in range(w)] for row in img]
return [[sum(k[i + 2] * tmp[min(max(v + i, 0), h - 1)][u] for i in range(-2, 3)) / 16
for u in range(0, w, 2)] for v in range(0, h, 2)]
def pyramid(img, levels):
"""The list [level 0, ..., level levels] of a Gaussian pyramid."""
pyr = [img]
for _ in range(levels):
pyr.append(reduce_level(pyr[-1]))
return pyr
def min_eigenvalue(a, b, c):
"""The smaller eigenvalue of the symmetric matrix [[a, b], [b, c]]."""
return (a + c - math.sqrt((a - c) ** 2 + 4 * b * b)) / 2
def corner_strength(img, r):
"""Map (u, v) -> smaller eigenvalue of the structure tensor of the
(2r+1) x (2r+1) window, for every pixel whose window and gradients lie
inside the image. Gradients are central differences."""
h, w = len(img), len(img[0])
gx = [[0.0] * w for _ in range(h)]
gy = [[0.0] * w for _ in range(h)]
for v in range(1, h - 1):
for u in range(1, w - 1):
gx[v][u] = (img[v][u + 1] - img[v][u - 1]) / 2
gy[v][u] = (img[v + 1][u] - img[v - 1][u]) / 2
lam = {}
for v in range(r + 1, h - r - 1):
for u in range(r + 1, w - r - 1):
a = b = c = 0.0
for y in range(v - r, v + r + 1):
for x in range(u - r, u + r + 1):
a += gx[y][x] * gx[y][x]
b += gx[y][x] * gy[y][x]
c += gy[y][x] * gy[y][x]
lam[(u, v)] = min_eigenvalue(a, b, c) # @line L9
return lam
def select_features(img, r=3, quality=0.05, min_dist=5.0, max_count=None):
"""Shi-Tomasi selection: pixels whose smaller eigenvalue is at least
quality times the largest one, taken greedily in decreasing order and
kept only when they are at least min_dist from every point kept before."""
lam = corner_strength(img, r)
if not lam:
return []
top = max(lam.values())
cand = sorted((p for p in lam if lam[p] >= quality * top and lam[p] > 0),
key=lambda p: (-lam[p], p[1], p[0])) # @line L10
kept = []
for p in cand: # @line L11
if all((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2 >= min_dist * min_dist for q in kept):
kept.append(p)
if max_count is not None and len(kept) == max_count:
break
return [(float(u), float(v)) for u, v in kept] # @line L12
def pyr_lk(ipyr, jpyr, p, r=3, iters=20, tol=0.01, lam_min=1e-6):
"""Track the point p of image I into image J, given their pyramids.
Returns the displacement (du, dv) at level 0, or LOST when the window
has too little texture at some level."""
levels = len(ipyr) - 1
g = (0.0, 0.0) # @line L13
for lev in range(levels, -1, -1): # @line L14
img, jmg = ipyr[lev], jpyr[lev]
qu, qv = p[0] / 2 ** lev, p[1] / 2 ** lev # @line L15
win = []
a = b = c = 0.0
for j in range(-r, r + 1):
for i in range(-r, r + 1):
u, v = qu + i, qv + j
ix = (sample(img, u + 1, v) - sample(img, u - 1, v)) / 2
iy = (sample(img, u, v + 1) - sample(img, u, v - 1)) / 2
win.append((u, v, ix, iy, sample(img, u, v)))
a += ix * ix
b += ix * iy
c += iy * iy
if min_eigenvalue(a, b, c) < lam_min: # @line L16
return LOST
det = a * c - b * b
nu = (0.0, 0.0) # @line L17
for _ in range(iters): # @line L18
bx = by = 0.0
for u, v, ix, iy, ival in win: # @line L19
diff = ival - sample(jmg, u + g[0] + nu[0], v + g[1] + nu[1])
bx += ix * diff
by += iy * diff
eta = ((c * bx - b * by) / det, (a * by - b * bx) / det) # @line L20
nu = (nu[0] + eta[0], nu[1] + eta[1])
if math.hypot(eta[0], eta[1]) < tol: # @line L21
break
if lev > 0: # @line L22
g = (2 * (g[0] + nu[0]), 2 * (g[1] + nu[1]))
else:
g = (g[0] + nu[0], g[1] + nu[1])
return g # @line L23
def klt_track(frames, levels=2, r=3, fb_max=0.5, quality=0.05, min_dist=5.0,
max_count=None, iters=20, tol=0.01, lam_min=1e-6):
"""Select points in frames[0] and track them through the other frames.
Returns one track per selected point: the list of its positions, which
stops at the frame where the point is dropped."""
pts = select_features(frames[0], r, quality, min_dist, max_count) # @line L1
tracks = [[p] for p in pts]
alive = list(range(len(pts)))
prev = pyramid(frames[0], levels)
for t in range(1, len(frames)): # @line L2
cur = pyramid(frames[t], levels)
still = []
for k in alive: # @line L3
p = tracks[k][-1]
d = pyr_lk(prev, cur, p, r, iters, tol, lam_min) # @line L4
if d is LOST:
continue
q = (p[0] + d[0], p[1] + d[1])
back = pyr_lk(cur, prev, q, r, iters, tol, lam_min) # @line L5
if back is LOST or math.hypot(d[0] + back[0], d[1] + back[1]) > fb_max: # @line L6
continue
tracks[k].append(q) # @line L7
still.append(k)
alive = still
prev = cur
return tracks # @line L8
test_kanade_lucas_tomasi_tracker.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kanade-lucas-tomasi-tracker/. The authors are listed in prov/GW9GYD.jsonl.
import math
import random
from kanade_lucas_tomasi_tracker import (
LOST,
corner_strength,
klt_track,
min_eigenvalue,
pyr_lk,
pyramid,
select_features,
)
N = 48
def texture(seed):
"""A smooth texture: 14 Gaussian blobs at seeded places."""
rng = random.Random(seed)
blobs = [(rng.uniform(4, 44), rng.uniform(4, 44), rng.uniform(2.0, 3.5), rng.uniform(60, 200))
for _ in range(14)]
def f(u, v):
return sum(a * math.exp(-((u - x) ** 2 + (v - y) ** 2) / (2 * s * s)) for x, y, s, a in blobs)
return f
def frame(f, du=0.0, dv=0.0):
"""The texture moved by (du, dv): frame(u + du, v + dv) = f(u, v)."""
return [[f(u - du, v - dv) for u in range(N)] for v in range(N)]
def interior(pts, margin=8):
return [p for p in pts if margin <= p[0] <= N - margin and margin <= p[1] <= N - margin]
def test_pyramid_sizes_and_constant_image():
img = [[7.0] * N for _ in range(N)]
pyr = pyramid(img, 2)
assert [(len(x), len(x[0])) for x in pyr] == [(48, 48), (24, 24), (12, 12)]
assert all(abs(val - 7.0) < 1e-12 for lev in pyr for row in lev for val in row)
def test_min_eigenvalue_is_the_minimum_of_the_quadratic_form():
rng = random.Random(3)
for _ in range(20):
a, c = rng.uniform(0, 10), rng.uniform(0, 10)
b = rng.uniform(-1, 1) * math.sqrt(a * c)
scan = min(a * math.cos(t) ** 2 + 2 * b * math.cos(t) * math.sin(t) + c * math.sin(t) ** 2
for t in (k * math.pi / 3600 for k in range(3600)))
assert abs(min_eigenvalue(a, b, c) - scan) < 1e-4 * (a + c + 1)
def test_selection_threshold_spacing_and_maximality():
img = frame(texture(1))
lam = corner_strength(img, 3)
quality, dist = 0.05, 6.0
pts = select_features(img, 3, quality, dist)
top = max(lam.values())
kept = [(int(u), int(v)) for u, v in pts]
assert kept and kept[0] == max(lam, key=lambda p: lam[p])
for p in kept:
assert lam[p] >= quality * top
for i, p in enumerate(kept):
for q in kept[:i]:
assert math.dist(p, q) >= dist
# every strong pixel that was not kept is close to a kept pixel at least as strong
for p, val in lam.items():
if val >= quality * top and p not in kept:
assert any(math.dist(p, q) < dist and lam[q] >= val for q in kept)
def test_subpixel_translation():
f = texture(1)
img0, img1 = frame(f), frame(f, 1.3, -0.7)
p0, p1 = pyramid(img0, 2), pyramid(img1, 2)
pts = interior(select_features(img0, 3, 0.05, 6.0, 10))
assert len(pts) >= 5
for p in pts:
d = pyr_lk(p0, p1, p)
assert d is not LOST
assert math.hypot(d[0] - 1.3, d[1] + 0.7) < 0.1
def test_pyramid_handles_large_motion():
f = texture(1)
img0, img1 = frame(f), frame(f, 6.0, 4.0)
pts = interior(select_features(img0, 3, 0.05, 6.0, 10))
errors = {}
for levels in (0, 2):
p0, p1 = pyramid(img0, levels), pyramid(img1, levels)
errs = []
for p in pts:
d = pyr_lk(p0, p1, p)
errs.append(math.inf if d is LOST else math.hypot(d[0] - 6.0, d[1] - 4.0))
errors[levels] = errs
assert max(errors[2]) < 0.01
assert max(errors[0]) > 1.0
def test_straight_edge_is_lost():
edge = [[100.0 / (1 + math.exp(-(u - 23.6))) for u in range(N)] for v in range(N)]
moved = [[100.0 / (1 + math.exp(-(u - 24.6))) for u in range(N)] for v in range(N)]
assert pyr_lk(pyramid(edge, 1), pyramid(moved, 1), (24.0, 24.0)) is LOST
def test_constant_velocity_over_frames():
f = texture(1)
vel = (0.8, 0.5)
frames = [frame(f, vel[0] * t, vel[1] * t) for t in range(8)]
tracks = klt_track(frames, levels=2, r=3, max_count=10, min_dist=6.0)
# points that stay at least 8 pixels inside the image for all 8 frames
full = [tr for tr in tracks if len(tr) == 8 and tr[0] in interior([tr[0]]) and tr[-1] in interior([tr[-1]])]
assert len(full) >= 4
for tr in full:
start = tr[0]
for t, p in enumerate(tr):
assert math.hypot(p[0] - start[0] - vel[0] * t, p[1] - start[1] - vel[1] * t) < 0.2
def test_forward_backward_check_drops_an_occluded_point():
f, other = texture(1), texture(3)
img0 = frame(f)
img1 = frame(f, 1.0, 0.5)
for v in range(19, 36):
for u in range(29, 46):
img1[v][u] = other(u, v)
tracks = klt_track([img0, img1], levels=2, r=3, max_count=10, min_dist=6.0, fb_max=0.5)
by_start = {tr[0]: tr for tr in tracks}
assert len(by_start[(37.0, 27.0)]) == 1
for p in [(34.0, 4.0), (13.0, 21.0), (24.0, 18.0), (8.0, 5.0)]:
tr = by_start[p]
assert len(tr) == 2
assert math.hypot(tr[1][0] - p[0] - 1.0, tr[1][1] - p[1] - 0.5) < 0.1
History
Lucas and Kanade (1981) gave the registration step: a Newton-type iteration on the squared difference between a window and its shifted copy. Tomasi and Kanade (1991), in a Carnegie Mellon technical report, used this step to track point features and chose the features where both eigenvalues of the 2 by 2 gradient matrix are large, because those are the windows where the step is well conditioned. Shi and Tomasi (1994) justified this rule and added a test of each feature against its first appearance with an affine model, to drop features that change. Bouguet described the pyramidal form with the propagation of the guess between levels in an Intel technical report that came with the OpenCV library, and that form is the one most programs use. Baker and Matthews (2004) put the step with the template gradient into their framework as the inverse compositional algorithm.
References
- Carlo Tomasi and Takeo Kanade, Detection and tracking of point features, Technical Report CMU-CS-91-132, Carnegie Mellon University, 1991, the whole report (tracking a window by its translation, and choosing windows where both eigenvalues of the 2 by 2 gradient matrix are large)
- Jianbo Shi and Carlo Tomasi, Good features to track, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 1994, 593 to 600, the whole paper (the selection rule by the smaller eigenvalue, and the check of each feature by an affine model of the window)
- Jean-Yves Bouguet, Pyramidal implementation of the Lucas Kanade feature tracker, description of the algorithm, Intel Corporation, Microprocessor Research Labs, technical report distributed with OpenCV, 2000, the whole report (the pyramid, the propagation of the guess from level to level, and the iteration with the gradient of the first image)
- Bruce D. Lucas and Takeo Kanade, An iterative image registration technique with an application to stereo vision, Proceedings of the 7th International Joint Conference on Artificial Intelligence (IJCAI), Vancouver, 1981, volume 2, pages 674 to 679, the whole paper (the registration step that the tracker repeats)
- Simon Baker and Iain Matthews, Lucas-Kanade 20 years on, a unifying framework, International Journal of Computer Vision 56(3), 2004, 221 to 255, Section 3 (the compositional and inverse compositional updates, which for a translation give the step used here)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag GW9GYD Edit this page History Report an error Markdown