Algorithm Search⌘K

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.

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
Properties
deterministicnot exactiterativelocalonline
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 F0,…,FNF_0, \ldots, F_N of WW columns and HH rows, given as digital images. We use the convention of the computer vision pages: the pixel (u,v)(u, v) is the value F[v][u]F[v][u], uu points right, vv points down, and the center of the pixel is the point (u,v)(u, v). (The Lucas-Kanade method page puts the center at x+1/2x + 1/2; 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 rr around a point pp is the set of m=(2r+1)2m = (2r + 1)^2 points p+(i,j)p + (i, j) with integers ∣i∣,∣j∣≤r|i|, |j| \le r.

The output is a set of tracks. A track is a list of points p0,p1,…p_0, p_1, \ldots with ptp_t in frame tt, such that the window around ptp_t in FtF_t shows the same pattern as the window around pt−1p_{t-1} in Ft−1F_{t-1} up to a translation. For two frames II and JJ and a point pp, the shift is the dd that minimizes

ε(d)=∑x∈window(p)(J(x+d)−I(x))2.\varepsilon(d) = \sum_{x \in \text{window}(p)} \big( J(x + d) - I(x) \big)^2 .

The gradient matrix of the window, the structure tensor, is

G(p)=∑x∈window(p)∇I(x) ∇I(x)T,λmin⁡(p)=the smaller eigenvalue of G(p).G(p) = \sum_{x \in \text{window}(p)} \nabla I(x)\, \nabla I(x)^{\mathsf T}, \qquad \lambda_{\min}(p) = \text{the smaller eigenvalue of } G(p).

If λmin⁡(p)\lambda_{\min}(p) is near zero, the window has texture in at most one direction and dd 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 0,…,L0, \ldots, L is built once per frame; level ℓ\ell is level ℓ−1\ell - 1 blurred with the binomial filter (1,4,6,4,1)/16(1, 4, 6, 4, 1)/16 in both directions and then sampled at even uu and even vv. So the pixel (u,v)(u, v) of level ℓ\ell is the point (2ℓu,2ℓv)(2^\ell u, 2^\ell v) of level 0.

  1. KLT(F₀, ..., F_N, r, L, k, τ, λ_min, ε_fb)
  2. 1P ← SELECT(F₀)
  3. 2for t ← 1 to N do
  4. 3for each point p in P do
  5. 4d ← PYR-LK(F_{t-1}, F_t, p) ▷ LOST if the window is flat
  6. 5b ← PYR-LK(F_t, F_{t-1}, p + d) ▷ track back
  7. 6if d or b is LOST or |d + b| > ε_fb then remove p from P
  8. 7else append p + d to the track of p; p ← p + d
  9. 8return the tracks
  10. SELECT(I) ▷ quality q, minimum distance δ
  11. 9for each pixel x whose window lies inside I do λ(x) ← λ_min(x)
  12. 10C ← the pixels with λ(x) ≥ q · max λ, sorted by decreasing λ
  13. 11P ← empty; for each c in C do if |c - p| ≥ δ for every p in P then add c to P
  14. 12return P
  15. PYR-LK(I, J, p) ▷ pyramids I⁰..I^L and J⁰..J^L
  16. 13g ← (0, 0)
  17. 14for ℓ ← L down to 0 do
  18. 15q ← p / 2^ℓ; G ← Σ_{x ∈ window(q)} ∇I^ℓ(x) ∇I^ℓ(x)ᵀ
  19. 16if the smaller eigenvalue of G < λ_min then return LOST
  20. 17ν ← (0, 0)
  21. 18repeat up to k times
  22. 19b ← Σ_{x ∈ window(q)} ∇I^ℓ(x) (I^ℓ(x) - J^ℓ(x + g + ν))
  23. 20η ← G⁻¹ b; ν ← ν + η
  24. 21if |η| < τ then leave the loop
  25. 22if ℓ > 0 then g ← 2 (g + ν) else g ← g + ν
  26. 23return g

Lines L15 to L21 are one Lucas-Kanade solve at level ℓ\ell, started from the guess gg that the coarser levels give. Two details follow Bouguet's description. First, the gradient and the matrix GG come from the first image II, at the fixed window, so GG 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 ℓ\ell is two pixels at level ℓ−1\ell - 1. The gradient at an off-grid point is the central difference (I(x+e1)−I(x−e1))/2(I(x + e_1) - I(x - e_1))/2 of interpolated values, and likewise in vv.

Example

Selection on numbers. A window with G=(106610)G = \begin{pmatrix} 10 & 6 \\ 6 & 10 \end{pmatrix} has eigenvalues 4 and 16, so λmin⁡=4\lambda_{\min} = 4: there is texture in both directions. A window on a vertical step edge has all gradients of the form (gu,0)(g_u, 0), so G=(a000)G = \begin{pmatrix} a & 0 \\ 0 & 0 \end{pmatrix} and λmin⁡=0\lambda_{\min} = 0. Line L16 rejects it at any positive threshold; a shift along the edge cannot be measured there.

A shift of 6 pixels. Frame F0F_0 is a 48×4848 \times 48 texture made of 14 Gaussian blobs (seeded positions, widths from 2 to 3.5 pixels, heights from 60 to 200), and F1F_1 is the same texture moved by (6,4)(6, 4). The windows have r=3r = 3 (m=49m = 49), the pyramid has L=2L = 2 (sizes 48, 24 and 12), τ=0.01\tau = 0.01. SELECT with q=0.05q = 0.05 and δ=6\delta = 6 keeps 10 points, the first at (22,24)(22, 24), which has the largest λmin⁡\lambda_{\min} of the image, about 32135. PYR-LK at this point gives:

Level ℓ\ell Window center qq Guess gg on entry Result ν\nu Iterations
2 (5.5,6)(5.5, 6) (0,0)(0, 0) (1.5053,0.9881)(1.5053, 0.9881) 5
1 (11,12)(11, 12) (3.0106,1.9762)(3.0106, 1.9762) (−0.0106,0.0238)(-0.0106, 0.0238) 2
0 (22,24)(22, 24) (6.0000,4.0000)(6.0000, 4.0000) (0.0000,0.0000)(0.0000, 0.0000) 1

The result is (6.000002,3.999998)(6.000002, 3.999998). The shift is (1.5,1)(1.5, 1) at level 2, inside the range of one linearization, and each level down only corrects the doubled guess. Without the pyramid (L=0L = 0), 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 L=2L = 2 all 6 are within 0.01 pixel.

A subpixel shift. With F1F_1 moved by (1.3,−0.7)(1.3, -0.7) 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 (6,4)(6, 4) it is at most 0.0012 pixel, and the iteration stops at τ=0.01\tau = 0.01 before the last digits settle.

The backward check. In F1F_1 the texture moves by (1,0.5)(1, 0.5), and a 17×1717 \times 17 block with 29≤u≤4529 \le u \le 45, 19≤v≤3519 \le v \le 35 is replaced by another texture, an occluder. The point at (37,27)(37, 27), under the occluder, moves to a wrong place, (4.68,11.17)(4.68, 11.17) away; tracked back, it misses its start by 2.54 pixels, so line L6 drops it at εfb=0.5\varepsilon_{fb} = 0.5. The point at (22,24)(22, 24) 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 (28,23)(28, 23), 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 δ\delta apart, and every rejected pixel above the threshold is within δ\delta of a kept point with λ\lambda 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 ∑x(I(x−η)−J(x+g+ν))2\sum_x (I(x - \eta) - J(x + g + \nu))^2 with respect to η\eta, whose normal matrix is the fixed GG. When GG is nonsingular the step is unique.
  • Fixed point and local convergence. If J(x+d∗)=I(x)J(x + d^*) = I(x) on the window for a shift d∗d^*, then d∗d^* is a fixed point of lines L19 and L20. For a smooth image model the Jacobian of the iteration map is zero at d∗d^*, so the iteration converges to d∗d^* from every start close enough to it, faster than any fixed linear rate.
  • The pyramid. If level ℓ\ell returns νℓ\nu_\ell, the final shift is ∑ℓ2ℓνℓ\sum_\ell 2^\ell \nu_\ell, and a translation by dd at level 0 is a translation by d/2ℓd / 2^\ell at level ℓ\ell 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 qq is the set of points q+(i,j)q + (i, j) with integers ∣i∣,∣j∣≤r|i|, |j| \le r, the gradient matrix is G(q)=∑x∇I(x)∇I(x)TG(q) = \sum_x \nabla I(x) \nabla I(x)^{\mathsf T} over the window, and λ(q)\lambda(q) is its smaller eigenvalue.

1. The selection

Claim 1. Let CC be the list of line L10, sorted by decreasing λ\lambda, and let PP be the output of line L11. Then (a) every p∈Pp \in P has λ(p)≥qmax⁡λ\lambda(p) \ge q \max \lambda; (b) any two points of PP are at least δ\delta apart; (c) every c∈C∖Pc \in C \setminus P has a point p∈Pp \in P with ∣c−p∣<δ|c - p| < \delta and λ(p)≥λ(c)\lambda(p) \ge \lambda(c).

Proof. (a) P⊆CP \subseteq C, and line L10 puts in CC only pixels that pass the threshold. (b) A point is added only when its distance to every point already in PP is at least δ\delta, and points are never removed; so for two points of PP, the later one was tested against the earlier one. (c) Let c∈Cc \in C be rejected. When the loop reached cc, the test failed, so some pp already in PP had ∣c−p∣<δ|c - p| < \delta. That pp came earlier in CC, so λ(p)≥λ(c)\lambda(p) \ge \lambda(c) by the order of CC, and pp stays in PP until the end. □\square

Property (c) says that PP is a maximal set of spaced points: no rejected candidate can be added without breaking (b). It does not say that PP 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 ℓ\ell, and fix the guess gg and the current correction ν\nu. Write Jν(x)=J(x+g+ν)J_\nu(x) = J(x + g + \nu) and e(x)=I(x)−Jν(x)e(x) = I(x) - J_\nu(x). Consider the inverse compositional problem for a translation: find η\eta that minimizes

ψ(η)=∑x(I(x−η)−Jν(x))2,\psi(\eta) = \sum_{x} \big( I(x - \eta) - J_\nu(x) \big)^2 ,

which asks which shift of the first window matches the current sample of JJ. If η\eta solves it, then I(x−η)≈J(x+g+ν)I(x - \eta) \approx J(x + g + \nu), that is I(y)≈J(y+g+ν+η)I(y) \approx J(y + g + \nu + \eta) with y=x−ηy = x - \eta, so the new correction is ν+η\nu + \eta, as in line L20.

Claim 2. The Gauss-Newton step for ψ\psi from η=0\eta = 0 is η=G−1b\eta = G^{-1} b with b=∑x∇I(x) e(x)b = \sum_x \nabla I(x)\, e(x), which is line L19 and line L20. It is unique when GG is nonsingular, and GG does not depend on ν\nu.

Proof. The first-order expansion I(x−η)=I(x)−∇I(x)Tη+o(∣η∣)I(x - \eta) = I(x) - \nabla I(x)^{\mathsf T} \eta + o(|\eta|) turns ψ\psi into the linear least-squares function

ϕ(η)=∑x(e(x)−∇I(x)Tη)2=ηTGη−2bTη+∑xe(x)2.\phi(\eta) = \sum_x \big( e(x) - \nabla I(x)^{\mathsf T} \eta \big)^2 = \eta^{\mathsf T} G \eta - 2 b^{\mathsf T} \eta + \sum_x e(x)^2 .

For any η\eta and hh, ϕ(η+h)−ϕ(η)=2hT(Gη−b)+hTGh\phi(\eta + h) - \phi(\eta) = 2 h^{\mathsf T}(G \eta - b) + h^{\mathsf T} G h. GG is a sum of matrices aaTa a^{\mathsf T}, so hTGh=∑x(∇I(x)Th)2≥0h^{\mathsf T} G h = \sum_x (\nabla I(x)^{\mathsf T} h)^2 \ge 0. If Gη=bG \eta = b, the difference is ≥0\ge 0 for every hh, so η\eta is a minimizer. If GG is nonsingular it is positive definite (its smaller eigenvalue is positive by line L16), so hTGh>0h^{\mathsf T} G h > 0 for h≠0h \ne 0 and the minimizer is unique. Conversely, at a minimizer the gradient 2(Gη−b)2(G\eta - b) is zero. The gradient ∇I\nabla I is taken on the fixed window of II, so GG depends only on II, qq and rr: line L15 computes it once per level. □\square

3. Fixed point and local convergence

Here we use a smooth image model: II and JJ 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

Φ(ν)=ν+G−1∑x∇I(x)(I(x)−J(x+g+ν)).\Phi(\nu) = \nu + G^{-1} \sum_x \nabla I(x) \big( I(x) - J(x + g + \nu) \big).

Claim 3. Suppose that J(y+g+ν∗)=I(y)J(y + g + \nu^*) = I(y) for all yy in an open set that contains the window, and that GG is nonsingular. Then ν∗\nu^* is a fixed point of Φ\Phi, the Jacobian of Φ\Phi at ν∗\nu^* is zero, and there is a ρ>0\rho > 0 such that for every start with ∣ν0−ν∗∣≤ρ|\nu_0 - \nu^*| \le \rho the iterates νj+1=Φ(νj)\nu_{j+1} = \Phi(\nu_j) converge to ν∗\nu^* with ∣νj+1−ν∗∣/∣νj−ν∗∣→0|\nu_{j+1} - \nu^*| / |\nu_j - \nu^*| \to 0.

Proof. At ν∗\nu^* every term I(x)−J(x+g+ν∗)I(x) - J(x + g + \nu^*) is zero, so Φ(ν∗)=ν∗\Phi(\nu^*) = \nu^*. The Jacobian is

DΦ(ν)=Id−G−1∑x∇I(x) ∇J(x+g+ν)T.D\Phi(\nu) = \mathrm{Id} - G^{-1} \sum_x \nabla I(x)\, \nabla J(x + g + \nu)^{\mathsf T} .

The identity J(y+g+ν∗)=I(y)J(y + g + \nu^*) = I(y) holds on an open set, so its derivatives agree there: ∇J(x+g+ν∗)=∇I(x)\nabla J(x + g + \nu^*) = \nabla I(x) for each window point xx. Then the sum is GG and DΦ(ν∗)=Id−G−1G=0D\Phi(\nu^*) = \mathrm{Id} - G^{-1} G = 0. DΦD\Phi is continuous because ∇J\nabla J is, so for each c∈(0,1)c \in (0, 1) there is a ρc>0\rho_c > 0 with ∥DΦ(ν)∥≤c\|D\Phi(\nu)\| \le c on the closed ball BB of radius ρc\rho_c around ν∗\nu^*. Take ρ=ρ1/2\rho = \rho_{1/2}. For ν∈B\nu \in B, the mean value inequality on the segment from ν∗\nu^* to ν\nu (which lies in the convex set BB) gives ∣Φ(ν)−ν∗∣=∣Φ(ν)−Φ(ν∗)∣≤12∣ν−ν∗∣|\Phi(\nu) - \nu^*| = |\Phi(\nu) - \Phi(\nu^*)| \le \frac{1}{2} |\nu - \nu^*|. So Φ\Phi maps BB into BB, and by induction ∣νj−ν∗∣≤2−j∣ν0−ν∗∣→0|\nu_j - \nu^*| \le 2^{-j} |\nu_0 - \nu^*| \to 0. For the rate, fix c∈(0,1/2]c \in (0, 1/2]. Once νj\nu_j is in the ball of radius ρc\rho_c, which happens for all large jj, the same inequality gives ∣νj+1−ν∗∣≤c∣νj−ν∗∣|\nu_{j+1} - \nu^*| \le c |\nu_j - \nu^*|. As cc is arbitrary, the ratio tends to 0. □\square

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 ν∗\nu^*. The size of ρ\rho depends on the image, which is the reason for the pyramid.

4. The pyramid

Claim 4. Let νℓ\nu_\ell be the correction that level ℓ\ell returns in lines L17 to L21. Then PYR-LK returns d=∑ℓ=0L2ℓνℓd = \sum_{\ell = 0}^{L} 2^\ell \nu_\ell.

Proof. Let gℓg_\ell be the guess on entry to level ℓ\ell, so gL=0g_L = 0 and, by line L22, gℓ−1=2(gℓ+νℓ)g_{\ell - 1} = 2(g_\ell + \nu_\ell) for ℓ≥1\ell \ge 1. We show by induction on j=L−ℓj = L - \ell that gℓ=∑i=ℓ+1L2i−ℓνig_\ell = \sum_{i = \ell + 1}^{L} 2^{i - \ell} \nu_i. For ℓ=L\ell = L the sum is empty and gL=0g_L = 0. If it holds for ℓ\ell, then gℓ−1=2νℓ+∑i=ℓ+1L2i−ℓ+1νi=∑i=ℓL2i−(ℓ−1)νig_{\ell - 1} = 2 \nu_\ell + \sum_{i = \ell + 1}^{L} 2^{i - \ell + 1} \nu_i = \sum_{i = \ell}^{L} 2^{i - (\ell - 1)} \nu_i. At level 0, line L22 returns g0+ν0=∑i=1L2iνi+ν0g_0 + \nu_0 = \sum_{i = 1}^{L} 2^i \nu_i + \nu_0. □\square

Claim 5. In the continuous model, let level ℓ\ell of an image EE be Eℓ(x)=(kℓ∗E)(2ℓx)E_\ell(x) = (k_\ell * E)(2^\ell x) for a blur kernel kℓk_\ell. If J(y+d)=I(y)J(y + d) = I(y) for all yy, then Jℓ(x+d/2ℓ)=Iℓ(x)J_\ell(x + d / 2^\ell) = I_\ell(x) for all xx.

Proof. Convolution commutes with translation: (kℓ∗J)(z+d)=∫kℓ(w)J(z+d−w) dw=∫kℓ(w)I(z−w) dw=(kℓ∗I)(z)(k_\ell * J)(z + d) = \int k_\ell(w) J(z + d - w)\, dw = \int k_\ell(w) I(z - w)\, dw = (k_\ell * I)(z). Put z=2ℓxz = 2^\ell x: Jℓ(x+d/2ℓ)=(kℓ∗J)(2ℓx+d)=(kℓ∗I)(2ℓx)=Iℓ(x)J_\ell(x + d / 2^\ell) = (k_\ell * J)(2^\ell x + d) = (k_\ell * I)(2^\ell x) = I_\ell(x). □\square

So, with Claim 3 at each level, if the guess from level ℓ+1\ell + 1 is within the attraction radius of level ℓ\ell, the level converges to the right correction, and by Claim 4 the corrections add up to dd. The sampled pyramid of the page (binomial blur, then every second pixel) satisfies Claim 5 exactly only for shifts by multiples of 2ℓ2^\ell; 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 ρ\rho of Claim 3, the iteration can converge to another fixed point.

Complexity

  • Selection. Line L9 computes GG at WHW H pixels. With a direct sum over each window, this is Θ(WHm)\Theta(W H m); with box sums (an integral image of each of the three products) it is Θ(WH)\Theta(W H). Sorting the candidates costs O(WHlog⁡(WH))O(W H \log(W H)), and the distance test in line L11 is O(∣C∣⋅∣P∣)O(|C| \cdot |P|) in the direct form.
  • One PYR-LK call. Line L15 reads mm points per level, and each of at most kk iterations reads mm points of JJ. So the cost is Θ((L+1)km)\Theta((L + 1) k m) in the worst case and Θ((L+1)m)\Theta((L + 1) m) when each level stops after one step.
  • Pyramids. Level ℓ\ell has about WH/4ℓW H / 4^\ell pixels, so a pyramid costs at most 43WH\frac{4}{3} W H times a constant: Θ(WH)\Theta(W H) per frame.
  • Total. For nn points and NN frames, with the backward check (which doubles the PYR-LK calls), the time is Θ(WHm+N(WH+n(L+1)km))\Theta(W H m + N(W H + n (L + 1) k m)) in the real RAM. The extra space is Θ(WH)\Theta(W H) for two pyramids and Θ(nN)\Theta(n N) 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 LL so that the largest expected shift divided by 2L2^L 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. λmin⁡\lambda_{\min} 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 (u,v)(u, v) here and at (u+1/2,v+1/2)(u + 1/2, v + 1/2) in some code. The pyramid map u↦2uu \mapsto 2u is right only for the first convention; with the second, it is u+1/2↦2(u+1/2)u + 1/2 \mapsto 2(u + 1/2). 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.

kanade_lucas_tomasi_tracker.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example