AI Wiki中文/EN

Optical flow

光流

Derive a local motion estimate and distinguish a supported zero velocity from an unobservable direction.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A question to test

Watch a straight edge through a small aperture. Motion perpendicular to the edge changes the visible brightness pattern; motion along the edge can be invisible. A motion estimator that reports a precise two-dimensional velocity from this patch is supplying information the image did not contain.

Optical flow describes apparent image motion between times. It is not automatically the three-dimensional velocity of an object. Camera motion, perspective, lighting changes and occlusion can all complicate that interpretation. Here we derive a local brightness-based estimate and make the program refuse a patch that cannot constrain both components.

The model and its derivation

Assume a visible point keeps its brightness over a small time interval. If it moves by (uΔt,vΔt)(u\Delta t,v\Delta t), then:

I(x+uΔt,y+vΔt,t+Δt)≈I(x,y,t).I(x+u\Delta t,y+v\Delta t,t+\Delta t)\approx I(x,y,t).

A first-order Taylor expansion, subtraction and division by Δt\Delta t yield:

Ixu+Iyv+It=0.I_xu+I_yv+I_t=0.

The spatial derivatives measure intensity change per pixel; with time measured in frames, u and v have units of pixels per frame. Horn and Schunck explain why this single equation cannot determine two unknowns. Their global smoothness model supplies an additional assumption; it is not the same as the local constant-motion assumption below. Determining Optical Flow

Assume n nearby pixels share the same flow vector f=(u,v)Tf=(u,v)^T. Stack their derivative constraints into A with n rows and two columns, and b with entries −It-I_t. The local least-squares problem is:

f^=arg⁡min⁡f∥Af−b∥22,ATAf^=ATb.\widehat f=\arg\min_f\lVert Af-b\rVert_2^2,\qquad A^TA\widehat f=A^Tb.

The normal equations follow by differentiating the squared residual and setting its gradient to zero. A unique solution requires A to have rank two. A numerically stable least-squares routine should solve the problem without explicitly forming an inverse. We form the two-by-two information matrix only to inspect conditioning:

M=ATA=∑p[Ix(p)2Ix(p)Iy(p)Ix(p)Iy(p)Iy(p)2].M=A^TA=\sum_p\begin{bmatrix}I_x(p)^2&I_x(p)I_y(p)\\I_x(p)I_y(p)&I_y(p)^2\end{bmatrix}.

This is the same unweighted gradient matrix used to reason about corners. If all gradients are horizontal, A’s second column is zero and v remains undetermined. Two positive eigenvalues help, but a very small minimum eigenvalue still means weak information. A large eigenvalue ratio indicates directional imbalance.

Lucas and Kanade derive iterative registration using local linearization and least squares. A practical image-pair method repeatedly warps one image toward the other, recomputes residuals and updates motion; a coarse-to-fine scheme can help with larger displacements. Our implementation tests one linearized derivative system only. It neither warps images nor constructs a pyramid. An Iterative Image Registration Technique with an Application to Stereo Vision

Run a small experiment

Use Python 3.12 and NumPy 1.26.4. The synthetic derivative fields come from the spatial surface x²+y² on a five-by-five grid. We prescribe flow (0.2,−0.1) and construct the temporal derivative to satisfy the linearized equation exactly. This is a derivative-level test, not a pair of rendered moving frames.

import numpy as np

def local_flow_step(ix,iy,it,min_eigenvalue=1e-6,max_condition=1e6):
    fields=[np.asarray(x,dtype=float) for x in (ix,iy,it)]
    if fields[0].ndim!=2 or fields[0].size<2 or any(x.shape!=fields[0].shape or not np.isfinite(x).all() for x in fields):
        raise ValueError('need matching finite 2D derivative fields')
    if not np.isfinite(min_eigenvalue) or min_eigenvalue<=0 or not np.isfinite(max_condition) or max_condition<1:
        raise ValueError('invalid conditioning thresholds')
    a=np.column_stack((fields[0].ravel(),fields[1].ravel()))
    b=-fields[2].ravel()
    information=a.T@a
    if not np.isfinite(information).all():
        raise ValueError('rescale derivatives: information matrix overflowed')
    eigenvalues=np.linalg.eigvalsh(information)
    if eigenvalues[0]<min_eigenvalue or eigenvalues[-1]/eigenvalues[0]>max_condition:
        return None,eigenvalues
    flow=np.linalg.lstsq(a,b,rcond=None)[0]
    return flow,eigenvalues

if __name__=='__main__':
    y,x=np.mgrid[-2:3,-2:3].astype(float)
    ix,iy=2*x,2*y
    reference=np.array([.2,-.1])
    it=-(ix*reference[0]+iy*reference[1])
    flow,eigenvalues=local_flow_step(ix,iy,it)
    print('linearized flow:',flow.round(6).tolist())
    print('information eigenvalues:',eigenvalues.round(6).tolist())
    print('single edge rejected:',local_flow_step(np.ones((5,5)),np.zeros((5,5)),np.ones((5,5)))[0] is None)
linearized flow: [0.2, -0.1]
information eigenvalues: [200.0, 200.0]
single edge rejected: True

On coordinates −2 through 2, the sum of x² across the 25 points is 50, so the sum of (2 x)² is 200. Symmetry cancels the cross term. Thus M=200 I and the known flow is uniquely recovered. The edge example has a zero second column and is rejected.

A returned None means insufficient local information under the configured thresholds. It is different from a valid zero vector: a textured stationary patch with zero temporal derivative can support zero motion. Thresholds depend on derivative units, contrast and patch size. Rescaling intensities changes eigenvalues even when the least-squares motion is unchanged.

For n pixels and two unknowns, constructing the system and solving the fixed-width least-squares problem take O(n) arithmetic and O(n) storage in this implementation. Tests include twenty random full-rank systems with known flow, the exact 200 I case, flat/edge/weak regions, supported zero motion, malformed inputs and threshold errors.

Where the method breaks

Brightness constancy fails when a light switches on, a reflection moves independently or a region becomes occluded. Small-motion linearization can fail even with perfect brightness conservation. A well-conditioned matrix only says that the linearized equations constrain two directions; it does not prove that the physical assumptions are correct.

Adding smoothness can fill an aperture ambiguity by borrowing information from neighbours, but motion boundaries make that assumption risky. A robust loss can reduce the influence of some inconsistent pixels without creating missing evidence. Pyramids enlarge the capture range while potentially removing small objects. Each remedy trades one assumption for another and should be tested on its intended failure case.

Evaluate motion with known correspondences or appropriate ground truth, separating occluded regions and displacement ranges. A low derivative residual or this exact synthetic result is not a claim of accurate dense flow on real video. Learned methods can use broader context but still require a specified training and evaluation setting.

Exercises with answers

1. An edge gives Ix=1,Iy=0,It=−0.2 at every pixel. What is identifiable?

Answer. u=0.2 is constrained; v is arbitrary. A least-norm numerical answer v=0 would not prove that vertical motion is absent.

2. Why are both information eigenvalues 200 in the example?

Answer. Each diagonal sums squared derivatives 4 x² or 4 y² to 200, and symmetry makes the mixed sum zero.

3. A textured patch has It=0. Is rejecting it always correct?

Answer. No. If A has adequate rank and strength, zero flow is the unique least-squares solution. Unknown motion and supported zero motion are different states.

4. Can multiplying all derivatives by 0.001 change acceptance?

Answer. Yes. The unconstrained least-squares flow is unchanged, but M and its eigenvalues are multiplied by 10⁻⁶. An absolute minimum-eigenvalue threshold may now reject it.

Sources and next steps

Lucas and Kanade’s six-page IJCAI version supports the local linearization and iterative registration discussion; the longer DARPA version mentioned there is a separate artifact. Horn and Schunck supply the brightness constraint and contrasting global smoothness framework. OCR fractions were not copied as trusted equations: the least-squares derivation and synthetic check here are explicit. An Iterative Image Registration Technique with an Application to Stereo Vision Determining Optical Flow

Review edges and corners to recognize the information matrix. Image formation explains why image displacement and world motion should not be conflated.

Make a prediction, then check

Why does a straight edge fail to determine both flow components?

Choose one answer

Learning objectives

  • Derive brightness constraints and the local least-squares system.
  • Identify rank, conditioning and model failures separately.

Prerequisites & connections

Explore related knowledge →

References

  1. An Iterative Image Registration Technique with an Application to Stereo Vision
    Bruce D. Lucas; Takeo Kanade · 1981
  2. Determining Optical Flow
    Berthold K. P. Horn; Brian G. Schunck · 1981

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary-source passages, explicit camera, filter, descriptor and local-motion models, executed programs, independent mathematical references, input boundaries and bilingual alignment. Not independent human or second-agent review; no full-system research reproduction claimed.

  • Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
  • 6 tests:20 known random full-rank systems, exact200I information, flat/edge/weak rejection, supported zero motion, invalid arrays and thresholds. Derivative-level linearized test only; no rendered frame pair, warp, dense flow or pyramid.
  • Single AI author compared all six sections, formulas, examples, source scopes and four exercise/answer pairs across both languages.35 tests across six chapters passed before freezing; no independent human review claimed.
  • Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.