Lucas-Kanade Optical Flow
Imagine a drone tracking a single bright window corner. It drifts across a video feed shot from a shaking camera. The brightness pattern near that corner barely changes frame to frame. But its position does. Recovering that displacement, robustly and in real time, is the central problem this article solves. A single pixel's brightness gives one equation for two unknowns. These are the horizontal and vertical velocity. So no isolated point can determine its own motion. The fix is to stop treating pixels in isolation. Instead, reason about small neighborhoods as coherent, rigidly translating patches. This is the insight behind the Lucas-Kanade method. It was introduced in 1981 as a way to estimate dense-enough motion fields. This avoids solving an expensive global optimization. Rather than regularizing over the whole image the way the competing Horn-Schunck method does, Lucas-Kanade assumes flow is locally constant inside a small window. It solves an overdetermined least-squares system per pixel. This turns an ill-posed one-equation-two-unknown problem into a well-posed system. This happens whenever the window contains enough gradient diversity. That is precisely the condition that Harris Corner Detection was built to detect. Lucas-Kanade matters because it is fast, differentiable, and analytically transparent. Every quantity in the final formula is a simple sum of image derivatives. It is computable in a tight inner loop. It underlies decades of production tracking systems. These range from KLT (Kanade-Lucas-Tomasi) feature trackers in visual odometry pipelines. They extend to the sparse optical flow front end of modern SLAM and augmented reality systems. It also feeds directly into Structure from Motion pipelines. These pipelines need frame-to-frame correspondences before triangulating 3D geometry. This article derives the Lucas-Kanade equations from the brightness constancy assumption. It works through the linear algebra that makes the local window trick well-posed. It gives complete pseudocode with the iterative Newton refinement needed for large motions. It also traces the method's relationship to corner detection, its complexity, its classic failure modes, and its place in the history of computer vision.
- Lucas-Kanade estimates per-pixel motion by assuming a small window moves with one constant velocity.
- It converts the single-pixel brightness constancy equation into an overdetermined 2-equation-per-pixel least-squares system.
- The system is solvable exactly where the local structure tensor (same matrix as in Harris corner detection) is well-conditioned.
- An iterative, coarse-to-fine (pyramidal) version handles large displacements beyond the linear approximation's validity.
- Complexity is linear in image size and window area; the bottleneck is the small 2×2 matrix inversion per pixel.
- It is the computational core of the KLT tracker, feeding correspondences into Structure from Motion and visual SLAM.
Lucas-Kanade turns an underdetermined single-pixel motion equation into a solvable system by assuming the flow is constant across a small spatial window and solving that window's equations by least squares.
The idea
The starting point is the brightness constancy assumption: a point on a physical surface preserves its intensity as it moves between frames, so . A first-order Taylor expansion of the right side, dropping second-order terms, produces the optical flow constraint equation,
where are the spatial image gradients, is the temporal derivative, and is the flow velocity at that pixel. This single equation constrains motion only along the gradient direction — the aperture problem — because any satisfying it lies on a line in velocity space, not a point. Prerequisite treatments of Optical Flow Fundamentals establish this constraint and its ambiguity; Lucas-Kanade is the classical resolution. The Lucas-Kanade method resolves the ambiguity with a local constancy assumption: all pixels within a small window around a point share the same flow . Instead of one equation per pixel, this yields one equation per pixel inside the window, all sharing the same two unknowns. If the window has pixels, this gives an overdetermined linear system, solved by ordinary least squares. The system is well-posed exactly when the window contains gradients pointing in at least two independent directions — geometrically, when the window sits on a corner or richly textured patch rather than a flat region or a straight edge. This is the same structural condition tested by the Harris corner response, which is why Lucas-Kanade trackers are almost always seeded at Harris (or Shi-Tomasi) corners: the matrix that must be inverted here is identical to the second-moment matrix used there. Because the Taylor linearization is only accurate for small displacements, practical Lucas-Kanade implementations wrap the core least-squares solve in two extensions: an iterative Newton-style refinement that re-linearizes around the current estimate until convergence, and a coarse-to-fine image pyramid that estimates large motions at low resolution and refines them at higher resolution, where the linear approximation is locally valid.
How it works
Step 1 — Compute image derivatives. For each frame, compute spatial gradients (e.g., via Sobel filters) and, using the next frame, the temporal derivative .
Step 2 — Build the per-window normal equations. For a window of pixels around a tracked point, stack the constraint equation from each pixel :
Write this as , an system. Since generally, solve it in the least-squares sense by the normal equations:
which is a linear system:
The matrix is exactly the structure tensor (second-moment matrix) from Harris corner detection. Its two eigenvalues measure gradient energy along two orthogonal directions: two large eigenvalues mean a well-conditioned corner-like window, one large and one near-zero means an edge (aperture problem persists along the edge direction), and two small eigenvalues mean a flat, untrackable region.
Step 3 — Iterative refinement (Newton's method). Because the Taylor expansion is only locally valid, one linear solve rarely gives the exact displacement for anything but sub-pixel motion. Lucas-Kanade is applied iteratively: warp the second image by the current flow estimate, recompute against the warped image, resolve the linear system for an incremental update, and accumulate updates until they fall below a threshold or a maximum iteration count is reached.
Step 4 — Coarse-to-fine pyramid. For displacements larger than a few pixels, the linearization breaks down entirely before iteration can rescue it. The standard fix builds a Gaussian image pyramid, estimates flow at the coarsest (smallest) level where displacements are small in pixel units, upsamples and scales that estimate as an initial guess for the next finer level, and repeats down to full resolution. This is the algorithm implemented in most production KLT trackers. ``` function LUCAS_KANADE_PYRAMIDAL(I1, I2, point p, levels L, window_radius r, max_iters K, eps):
# Build image pyramids (coarsest last index L-1) pyramid1 = build_gaussian_pyramid(I1, L) pyramid2 = build_gaussian_pyramid(I2, L) total_flow = (0, 0) # accumulated at coarse resolution for level in (L-1) down to 0: scale = 2^level p_level = p / scale # point coordinates at this pyramid level guess = total_flow * 2 # upscale estimate from coarser level Ix, Iy = spatial_gradients(pyramid1[level]) window = extract_window(p_level, r) # fixed neighborhood in I1
# Precompute the 2x2 structure tensor ONCE per level (does not change with iteration) Sxx = sum(Ix[window]^2) Syy = sum(Iy[window]^2) Sxy = sum(Ix[window] Iy[window]) Z = [[Sxx, Sxy], [Sxy, Syy]] if not well_conditioned(Z): # smallest eigenvalue below threshold return FAILURE # flat region: cannot resolve motion Z_inv = invert_2x2(Z) flow = guess for iter in 1..K: warped_point = p_level + flow I2_warped = sample_bilinear(pyramid2[level], window shifted by flow) It = I2_warped - pyramid1[level][window] # temporal difference bx = sum(Ix[window] It) by = sum(Iy[window] * It) delta = Z_inv @ [-bx, -by] # incremental update solving normal equations flow = flow + delta if norm(delta) < eps: break total_flow = flow # becomes the guess for the next finer level return total_flow # final (u, v) displacement at full resolution ``` The inner loop is the classical Lucas-Kanade update; the outer pyramid loop is the Kanade-Lucas-Tomasi (KLT) extension that makes it practical for real motions.
Complexity & correctness
Time complexity. For a single point tracked with a window of pixels, computing the sums costs per iteration. Inverting the resulting matrix is . With Newton iterations and pyramid levels, tracking one point costs . Tracking points over a frame is , which is linear in every parameter — the reason KLT trackers run comfortably in real time for hundreds of feature points. Computing dense flow at every pixel of an -pixel image is , still linear in image size, in contrast to global methods like Horn-Schunck that require solving a large sparse linear system (typically per iteration of an iterative solver, but with much larger hidden constants and slower convergence for the same accuracy).
Space complexity. per point for the window buffers, plus for the image pyramid, which is shared across all tracked points. No global system is ever assembled, unlike variational (Horn-Schunck style) approaches, which is the structural reason Lucas-Kanade is far cheaper in memory.
Correctness argument. The method rests on two approximations whose validity conditions can be stated precisely. Well-posedness of the linear solve. The normal-equations matrix is symmetric positive semi-definite, so it is invertible iff both eigenvalues . Since is a sum of outer products , a nonzero smallest eigenvalue requires gradients pointing in at least two independent directions somewhere in the window — precisely the Harris "cornerness" condition. This is not incidental: least-squares here is solving the exact same aperture-resolution problem that motivates corner detection, so seeding Lucas-Kanade tracking at Harris/Shi-Tomasi corners is provably choosing the windows where the underlying linear system is best conditioned, minimizing the amplification of pixel noise into flow error (formally, the error covariance of the least-squares estimate scales with , so small directly inflates estimation variance along that eigendirection). Validity of linearization. The Taylor expansion has a remainder term of order times the local curvature of the intensity surface. The approximation is accurate only when is small relative to the scale over which the image gradient itself varies. Iteration corrects for this: re-warping the image by the current estimate and re-linearizing around the new residual reduces the effective displacement being linearized at each step, so if the iteration converges, it converges to a stationary point of the true (non-linearized) sum-of-squared-differences objective
which each Newton step is implicitly minimizing via its local quadratic approximation. Convergence is not guaranteed in general (the true objective can be non-convex with multiple local minima from repeated texture), but it is guaranteed to converge quickly for small residual displacements because the quadratic approximation of near a good corner is well-conditioned, by the same eigenvalue argument above. The pyramid extension exists precisely to keep the initial residual displacement small at every level, so that this local-convergence guarantee actually applies before any iteration begins.
Honest tradeoffs. Lucas-Kanade is fast and accurate at strong corners but produces no estimate (or an unreliable one) in flat or purely edge-like regions — it deliberately trades completeness for reliability, unlike Horn-Schunck-style global methods that produce a dense flow field everywhere by propagating information from confident regions into ambiguous ones, at higher computational cost and with a smoothing bias.
Worked example
Consider tracking a small corner feature between two consecutive grayscale windows extracted around a candidate point, with pixel intensities (0–255) given below. Frame 1 shows a bright L-shaped corner; frame 2 shows the same pattern shifted by roughly pixels (sub-pixel, simulating a slow real drift).
| Frame 1 window | Frame 2 window (same crop) |
|---|---|
| 10 10 10 200 200 | 10 10 10 90 200 |
| 10 10 10 200 200 | 10 10 60 190 200 |
| 10 10 10 200 200 | 10 10 90 195 200 |
| 10 10 10 200 200 | 10 40 150 200 200 |
| 10 10 10 200 200 | 10 90 190 200 200 |
Step through the algorithm: 1. Gradients. Using central differences on frame 1, is large and positive (≈190 per 2 pixels of horizontal step) at the column-3/4 boundary where intensity jumps from 10 to 200, and near zero elsewhere; is near zero everywhere in frame 1 because intensity is constant along each row (a pure vertical edge has no vertical gradient). This is deliberately an edge-dominated window at first glance — but the diagonal blur of the transition in frame 2 (see how the boundary bends across rows) means a few pixels near the corner of the L carry non-negligible too, giving the matrix just enough rank. 2. Structure tensor. Summing over the 25 pixels (numeric derivatives computed via Sobel):
Eigenvalues are approximately , . Both are well above a typical noise threshold (commonly a few hundred, depending on sensor noise), so the point is trackable, though the small signals it's edge-leaning rather than a crisp corner. 3. Temporal difference and right-hand side. Subtracting frame 1 from frame 2 pixelwise gives large positive concentrated where the boundary moved (the region that changed from dark 10 to bright ~150–200 as the corner slid rightward/downward). Computing . 4. Solve.
5. Iterate. Warping frame 2 backward by and recomputing the residual yields a much smaller correction, typically under pixels, so the loop terminates after 2–3 iterations. The recovered flow matches the simulated ground-truth shift of to within numerical rounding — exactly the behavior the correctness argument predicts: a well-conditioned (both eigenvalues comfortably above noise floor) combined with a small true displacement (well inside the linearization's valid range) yields fast, accurate convergence.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Tracking points in flat/textureless regions | has both eigenvalues near zero; the solve is numerically unstable or the matrix is singular | Only seed points at strong Harris/Shi-Tomasi corners; check against a threshold before accepting a track |
| Aperture problem on long straight edges | One eigenvalue is large, the other near zero; flow along the edge direction is unconstrained | Reject or flag low- points; rely on corner-like windows only |
| Large displacement without pyramid | Taylor linearization is invalid beyond a few pixels; iteration diverges or converges to the wrong local minimum | Always use a coarse-to-fine pyramid so per-level residual displacement stays small |
| Window too small | Too few equations relative to noise; estimate is noisy even at a true corner | Use a window large enough to average out sensor noise, but not so large that it violates the constant-flow-within-window assumption |
| Window too large | Assumes the entire window moves rigidly with one ; breaks near motion boundaries and occlusions | Use adaptive or smaller windows near depth discontinuities; consider affine (not just translational) local models |
| Ignoring brightness constancy violations | Lighting changes, specular highlights, or shadows break the core assumption, injecting bias into | Apply photometric normalization or a gain/bias term in the matching model |
| Stopping iteration too early or with too loose | Residual displacement remains large enough to violate linearization at the next pyramid level | Tune convergence threshold and max iterations per level, and verify residual sum-of-squared-differences decreases |
Pioneers & history
Origins · 1 minTakeo Kanade and how this was discovered
Takeo Kanade co-developed the Lucas-Kanade optical flow method and later extended it with Carlo Tomasi into the KLT feature tracker, one of the most widely deployed correspondence algorithms in computer vision. His broader career spans robotics, multi-camera 3D reconstruction (the Virtualized Reality system), and facial recognition, and he is regarded as one of the foundational figures connecting classical geometric vision to modern robotic perception.
Where this matters
Pyramidal Lucas-Kanade, under the name KLT tracking, is the sparse feature-tracking backbone of countless real-time systems. Visual-inertial odometry pipelines used in drones, mobile robots, and AR headsets track a sparse set of Harris/Shi-Tomasi corners frame to frame with KLT before feeding the resulting 2D correspondences into a bundle adjustment or filtering backend for pose estimation — the natural entry point into Structure from Motion and monocular SLAM. Video stabilization software estimates dominant camera motion by robustly aggregating many local Lucas-Kanade flow vectors. Motion-compensated video codecs and frame-interpolation systems use local flow estimates conceptually descended from this formulation. Optical mice and some industrial machine-vision motion sensors use closely related local gradient-based tracking at the hardware level. Even modern deep optical flow networks (such as those in the FlowNet and RAFT families) are frequently evaluated against, and sometimes initialized or regularized by, the same local-window least-squares intuition that Lucas-Kanade formalized four decades earlier, and many learned trackers still use its coarse-to-fine, iterative-refinement structure as an architectural template.
Ask the tutor: How does the affine (six-parameter) extension of Lucas-Kanade change the structure tensor and the conditions needed for a stable solve?
How is Lucas-Kanade different from Horn-Schunck optical flow?
Lucas-Kanade assumes flow is constant within a small local window and solves an independent least-squares problem per point, producing fast, sparse, locally reliable estimates but leaving flat or aperture-ambiguous regions unresolved. Horn-Schunck instead assumes flow is globally smooth and solves one large coupled system over the whole image using a smoothness regularizer, producing a dense flow field everywhere, including in textureless regions, by propagating information from confident areas. The tradeoff is speed and simplicity (Lucas-Kanade) versus completeness and smoothness at higher computational cost (Horn-Schunck). Modern dense flow, including deep-learning methods, borrows ideas from both: local matching costs plus global or learned regularization.
Why is Lucas-Kanade so closely tied to Harris corner detection?
Both methods analyze the same object: the second-moment/structure tensor built from local image gradients. Harris corner detection uses this matrix's eigenvalues to decide whether a point is trackable at all. Lucas-Kanade uses the very same matrix as the coefficient matrix it must invert to solve for the flow. A point with two large eigenvalues is simultaneously a good corner and a well-conditioned Lucas-Kanade solve; a point on an edge has one small eigenvalue, causing both corner detection to reject it and the flow solve to become unstable along that direction. This shared mathematics is why practical trackers always seed Lucas-Kanade at Harris or Shi-Tomasi corners.
Can Lucas-Kanade handle rotation, scale change, or non-translational motion?
The basic formulation only models pure translation within the window, which is a good local approximation for small windows over short time intervals but breaks down under strong rotation, scaling, or perspective distortion. Extensions replace the translational model with an affine warp (six parameters) solved by the same least-squares machinery, at the cost of needing more equations (a larger window) to constrain the extra parameters reliably. This affine extension is common in longer-baseline tracking, such as tracking a feature across many frames where cumulative rotation or scale change becomes significant.
Why does the method fail near motion boundaries and occlusions?
The core assumption is that every pixel within the window shares one rigid flow vector. Near an object boundary, one part of the window belongs to a foreground object moving one way, and another part belongs to background moving differently, or that background may become occluded outright in the next frame. Least squares does not detect this violation; it silently blends the conflicting constraints into a single vector that may not represent either true motion accurately, and the resulting error is not signaled by the eigenvalues of the structure tensor. This is why production trackers add explicit consistency checks, such as forward-backward tracking verification.
What role does the iterative Newton refinement play, and does it always converge?
A single linear solve of the normal equations only gives the exact answer under the ideal case of a perfectly linear intensity surface and infinitesimal displacement; in practice, higher-order terms in the Taylor expansion introduce error. Iterative refinement re-warps the image by the current estimate, re-derives against this warped image, and solves for an incremental correction, effectively performing Newton's method on the true sum-of-squared-differences objective. Convergence is fast and reliable when the true residual displacement entering each iteration is small and the structure tensor is well-conditioned, but is not globally guaranteed, since the underlying objective can have multiple local minima for repetitive textures.
How does the pyramid level count and window size get chosen in practice?
Window size trades off noise averaging against violation of the local-constancy assumption: larger windows better average out sensor noise and stabilize the structure tensor estimate, but risk covering pixels with genuinely different true motions, especially near depth or motion boundaries. Common choices are windows of roughly 7×7 to 21×21 pixels. Pyramid level count is chosen so that the maximum expected displacement, after halving at each coarser level, is small (a few pixels) at the coarsest level; three to five levels typically suffice for displacements up to several dozen pixels at full resolution.
Why is Lucas-Kanade usually described as producing sparse rather than dense flow?
Nothing in the mathematics prevents running Lucas-Kanade at every pixel, and dense variants exist, but the method only produces a reliable estimate where the local structure tensor is well-conditioned, which in natural images is a small fraction of pixels (corners and richly textured regions). Running it everywhere wastes computation on ill-posed flat regions that yield noisy, near-arbitrary vectors. The standard and far more efficient practice is therefore to first select a sparse set of strong Harris/Shi-Tomasi corners and track only those, since this concentrates computation exactly where the underlying least-squares problem is guaranteed to be well-posed.