Why is mathematics important when software tracks motion in a video? Two frames are only grids of brightness or colour values. They do not arrive with arrows showing where each visible point moved. Optical flow uses image gradients, vectors, linear approximations and optimisation to estimate apparent motion from changes between frames. It is a beautiful example of mathematics turning many small local clues into a field of motion.
Optical flow is not the same as the true three-dimensional velocity of an object. Camera movement, depth, lighting, reflections, blur and occlusion can all change the image. The result is an estimate under stated assumptions, not automatic understanding. That distinction is exactly why the topic is useful for students: the mathematics is powerful because it makes both the inference and its limits visible.
**Choose a route:** see the brightness equation, work a local estimate, understand pyramids, audit failure modes, or build learning habits.
From Frames to a Motion Field
A digital frame can be represented as a function I(x,y,t), where x and y locate a pixel and t identifies time. For two nearby frames, optical flow seeks a horizontal component u and vertical component v at selected pixels or across the whole image. The vector (u,v) is commonly measured in pixels per frame or pixels per second after the frame interval is included.
This is already a major mathematical move. A picture becomes a numerical field. Apparent movement becomes another field laid over it. The question changes from “what object do I see?” to “what displacement best explains how local image measurements changed?”
Sparse optical flow estimates motion at selected features such as corners. Dense optical flow estimates a vector for many or all pixels. Sparse methods can be economical and stable when distinctive features are available. Dense methods provide coverage, but smooth areas, boundaries and occlusions still require careful interpretation.
Brightness Constancy Becomes an Equation
A common starting assumption is brightness constancy: a small image patch keeps approximately the same intensity while moving. If a point at (x,y) moves by (uΔt,vΔt), then an idealised statement is I(x,y,t) = I(x+uΔt,y+vΔt,t+Δt).
For small changes, a first-order Taylor expansion gives I(x+uΔt,y+vΔt,t+Δt) ≈ I + Ix uΔt + Iy vΔt + It Δt. Subtract I, divide by Δt and obtain the optical-flow constraint:
Ix u + Iy v + It = 0.
Ix and Iy are spatial brightness gradients. It is the temporal change. The equation says that motion through a spatial gradient can explain the observed change through time. Every term has the units of intensity change per unit time when u and v use distance per unit time.
The approximation depends on small displacement, differentiability and brightness behaviour. It does not become true merely because software calculates it. A flash, shadow, glossy reflection or automatic exposure adjustment may change intensity without the surface moving.
One Equation Cannot Determine Two Components
At one pixel, the constraint contains two unknowns, u and v, but only one equation. Infinitely many velocity pairs can satisfy it. This is the aperture problem: when we see a moving edge through a small opening, only motion perpendicular to the edge is well constrained.
Imagine a long diagonal stripe. Sliding it along its own direction may produce almost the same local view. The brightness gradient points across the stripe, so the equation contains strong information about the perpendicular component and weak information about the parallel component.
Corners help because intensity varies in two independent directions. A textured window around a corner supplies several equations with different gradient directions. This is why feature detectors often prefer corners rather than flat patches or single straight edges.
Did You Know? “More pixels” does not automatically mean “more information.” A thousand pixels on a perfectly uniform wall can all provide almost the same uninformative equation. A small corner may provide better motion evidence because its gradients span two directions.
Lucas–Kanade Turns Neighbours into Least Squares
The Lucas–Kanade idea assumes motion is approximately constant within a small window. Each pixel i in that window contributes Ixi u + Iyi v = −Iti. Stacking the equations gives A w = b, where w = [u v]ᵀ.
Usually there are more equations than unknowns, and noise prevents exact agreement. Least squares chooses w to minimise the sum of squared residuals. The normal equations are:
(AᵀA)w = Aᵀb.
The two-by-two matrix AᵀA contains sums of Ix², IxIy and Iy². Its geometry describes whether the window contains useful variation. If both eigenvalues are reasonably large, gradients support motion in two directions. If one is small, the window behaves like an edge. If both are small, it is nearly flat.
Least squares does not manufacture information. An invertible-looking result can still be unstable if the matrix is poorly conditioned. A small perturbation in brightness may then cause a large change in the estimated vector. Confidence measures based on eigenvalues or residuals help expose that problem.
Worked Example: Solving a Local Motion Vector
Consider three synthetic pixels with gradient equations:
- pixel 1: u + 0v = 2;
- pixel 2: 0u + v = −1; and
- pixel 3: u + v = 1.
In matrix form, A = [[1,0],[0,1],[1,1]] and b = [2,−1,1]ᵀ. The first two equations already suggest u = 2 and v = −1. The third checks the combination because 2 + (−1) = 1.
AᵀA = [[2,1],[1,2]] and Aᵀb = [3,0]ᵀ. Solving gives u = 2 and v = −1. If pixel 3 were noisy and reported 1.3, the three equations would no longer meet exactly. Least squares would distribute the disagreement rather than obeying one pixel completely.
The vector means two pixels in the positive x direction and one pixel in the negative y direction over the chosen frame interval. If frames are 0.02 seconds apart, the apparent rate is 100 pixels/s horizontally and −50 pixels/s vertically. That is still image-plane motion. Turning it into metres per second requires camera calibration, depth and a geometric model.
Residuals Are Part of the Answer
After estimating u and v, calculate ri = Ixi u + Iyi v + Iti. Residuals near zero mean the local linear model explains the temporal changes under its assumptions. Large or patterned residuals can indicate illumination changes, mixed motion, blur, an occlusion boundary or a displacement too large for the approximation.
Do not report only an arrow. Report the window size, gradient method, residual measure and any rejected point. A visually plausible vector can be numerically unsupported, especially where algorithms smooth across object boundaries.
Robust losses can reduce the influence of extreme residuals. They do not make outliers disappear scientifically. The analyst still needs to ask whether the large residual represents bad data, a different motion, or a broken assumption.
Image Pyramids Handle Larger Motion
The Taylor approximation works best for small motion. If an object moves 24 pixels between frames, the correct match may lie far outside a small local window. An image pyramid creates coarser versions of each frame. At one-eighth scale, 24 pixels becomes about 3 pixels, which is easier to estimate.
The algorithm estimates motion at a coarse level, scales that guess to the next finer level and refines it. This coarse-to-fine process expands the capture range without searching every displacement at full resolution.
Scaling must be explicit. A vector of 3 pixels at one-eighth resolution corresponds to about 24 pixels in the original coordinates. Rounding, interpolation and smoothing affect the result. Very small objects may vanish at coarse levels, and two motions can blend together.
A pyramid is therefore a compromise. More levels help larger displacement but remove fine spatial detail. Larger windows improve robustness but blur motion boundaries. These are not merely software settings; they express mathematical assumptions about scale and local coherence.
Sparse and Dense Optical Flow Answer Different Questions
Sparse tracking follows selected features. It is useful for camera motion, stabilisation, trajectory estimation and matching when a manageable set of reliable points is enough. The output should include which points were successfully tracked and which failed.
Dense methods seek a vector field over much of the image. They often combine a data term, which rewards brightness agreement, with a smoothness term, which discourages abrupt vector changes except where evidence supports them. The relative weight changes how much the field follows local data versus a prior preference for smooth motion.
Dense flow is attractive for visualisation, but a colourful field can hide uncertainty. Textureless areas may inherit motion from neighbours. Boundaries may smear. A good report shows the image, vector scale, mask, confidence or consistency checks, and the parameter choices that created the field.
Forward–Backward Consistency
One practical diagnostic estimates flow from frame A to B and then from B back to A. A point moved forward and then backward should return near its starting position if both estimates are consistent.
The forward–backward error is not a proof of correctness. Two wrong estimates can sometimes agree. Still, a large mismatch is a useful warning for occlusion, lost features, repetitive texture or local optimisation failure.
Thresholds need units and context. A one-pixel inconsistency can be negligible in a high-resolution wide shot or substantial for a tiny feature. Plot the distribution rather than selecting a threshold only after seeing which tracks survive.
Where Optical Flow Can Fail
Illumination changes
Brightness constancy can fail under flicker, shadows, reflections, auto-exposure or changing colour balance. Gradient normalisation or more robust descriptors may help, but the change must still be acknowledged.
Occlusion and disocclusion
A point visible in one frame may be hidden in the next, while a previously hidden region becomes visible. There is no true correspondence for every pixel. An algorithm forced to return a vector may produce a convincing fiction.
Motion blur
Blur mixes light along a path. Gradients weaken or shift, and a feature can no longer be treated as a compact patch. Shorter exposure may reduce blur, but changes noise and image brightness.
Repetitive patterns
Windows, tiles or stripes can produce several similar matches. Local methods may choose the wrong repetition. Larger context helps only if it contains distinctive structure.
Large rotation or deformation
Pure translation within a small window may be insufficient. Rotation, scaling, perspective change and non-rigid deformation need richer local models or different methods.
Rolling shutter
Some cameras expose image rows at different times. Fast motion can therefore bend geometry. A single global frame time is then an approximation.
Optical Flow Is Not Object Understanding
Flow describes apparent image motion. It does not by itself name objects, infer intention or decide whether a scene is safe. A moving shadow has flow-like evidence. A camera panning across a stationary room produces motion everywhere. An approaching object may expand radially even when its centre barely shifts.
Applications combine flow with calibration, segmentation, tracking, inertial sensors, depth, physical models and domain rules. The mathematical value of optical flow lies in providing a measurable clue, not a complete story.
For comparison, Image Stitching, Homographies and Feature Matching explains how correspondences support geometric alignment, while Photography, Aperture, Shutter Speed and Exposure Values shows how exposure choices affect motion blur and image evidence.
How Students Can Learn This Mathematics
Start with displacement on graph paper. Mark a point in two frames, subtract coordinates and divide by elapsed time. Then build a two-dimensional brightness grid and calculate finite differences by hand. This makes gradients concrete before matrices arrive.
Next, solve a small overdetermined system with three or four equations. Plot the residuals. Change one gradient direction until the matrix becomes poorly conditioned. The student will see that identifiability is a geometric property, not an abstract warning.
Then use synthetic images where ground-truth motion is known. Change one factor at a time: noise, displacement, window size, pyramid level, brightness gain or occlusion. Measure endpoint error rather than judging arrows only by appearance.
A strong learning log should contain:
- the frame interval and coordinate convention;
- the gradient formula and boundary handling;
- the window and pyramid parameters;
- the known or estimated displacement;
- residual or consistency measures;
- failed tracks and reasons; and
- a sentence separating image-plane motion from physical velocity.
Parents can support this work by asking what assumption makes each equation possible. “What changed in the image besides movement?” is often more valuable than asking whether the arrow looks right.
Mathematics in Computing and Careers
Optical flow connects algebra, calculus, vectors, probability and numerical computing. Computer-vision engineers design estimators and evaluation methods. Robotics teams combine visual motion with other sensors. Researchers study robust representations, uncertainty and failure cases. Animation, film, sports analysis, microscopy and remote sensing all use related motion concepts.
For an implementation-facing reference, see the official OpenCV optical-flow tutorial, which documents pyramidal Lucas–Kanade tracking and practical status outputs. Documentation explains an implementation; validation for a real application still needs representative data and independent evaluation.
Mathematics alone does not guarantee entry to those careers. Programming, experimental design, communication, physics, domain knowledge and ethical judgment matter too. The benefit of learning the mathematics is transfer: a student learns how to turn images into variables, assumptions into equations, and uncertainty into a result that can be challenged.
A Responsible Optical-Flow Audit
Before trusting a motion field, verify frame order, time interval, colour conversion and coordinate direction. Inspect the original frames, not only the overlay. Check whether tracked regions have gradients in two directions. Compare forward and backward estimates. Plot residuals and rejected points.
Repeat the analysis at more than one scale and window size. If the conclusion changes, report sensitivity instead of choosing the most attractive output. Test on a synthetic translation with a known answer before analysing an unfamiliar video.
Preserve privacy and purpose. Video analysis can affect people. Consent, data minimisation, security, bias and appropriate human review are not solved by better flow estimation. A mathematical estimate should never be presented as an identity, intention or judgment it was not designed to support.
Evaluating a Motion Estimate
When synthetic or carefully annotated ground truth is available, endpoint error compares the estimated vector (u,v) with the reference vector (u*,v*): √[(u−u*)²+(v−v*)²]. Its units are pixels per frame unless converted. Angular error compares vector direction, but becomes unstable or unhelpful when the true motion magnitude is near zero.
Report error by region as well as one average. Motion boundaries, occluded areas and low-texture regions are often harder than well-textured interiors. A low overall mean can hide severe errors on small moving objects. Percentiles and error maps show the distribution more honestly.
Ground truth has uncertainty too. Human annotations, rendered scenes and sensor-based reference motion each represent slightly different quantities. A benchmark may exclude invalid or occluded pixels, so compare evaluation masks as carefully as algorithms.
Without ground truth, use consistency checks rather than claiming accuracy. Warp frame B back toward frame A using the estimated flow and inspect photometric residuals. Check forward–backward agreement and trajectory smoothness. These diagnostics test internal consequences of the estimate, not the true three-dimensional motion.
Evaluation should match the application. Video stabilisation may care about coherent camera motion; object boundaries may matter in segmentation; scientific imaging may need unbiased displacement at subpixel scale. One leaderboard score cannot represent every purpose.
Subpixel estimates deserve special care. They arise from interpolation and a local model, not from physically smaller sensor pixels. Test them by shifting a synthetic image through known fractional displacements and checking bias across several textures and phases. Interpolation kernel, blur and quantisation can create periodic error patterns. Report precision separately from accuracy: repeated estimates may cluster tightly around the wrong displacement.
Frame rate also changes the problem. A higher rate reduces displacement per frame but may shorten exposure and increase noise. A lower rate can improve brightness yet create larger motion, occlusion and blur. The best sampling choice balances signal quality, capture range and the time scale of the phenomenon rather than maximising one specification.
Always retain the original frame timestamps. Assuming a constant rate when frames were dropped changes pixels per frame into a misleading velocity. Use the actual elapsed time for every interval or label the result as displacement only.
Frequently Asked Questions
What is optical flow?
It is an estimate of apparent two-dimensional motion between image frames, represented by displacement or velocity vectors.
Why are image gradients needed?
Gradients show how brightness changes across space. Motion through those changes helps explain brightness change through time.
What is the aperture problem?
One local edge usually constrains only motion perpendicular to the edge, leaving the parallel component ambiguous.
Why use least squares?
A window supplies more noisy equations than unknown motion components. Least squares finds the vector that best fits them under a squared-error model.
Why use image pyramids?
They make large full-resolution movement smaller at coarse scales, allowing iterative refinement from coarse to fine.
Does optical flow give real speed in metres per second?
Not by itself. It gives image-plane motion. Physical speed requires calibration, depth, timing and a geometric model.
Can optical flow identify a person’s action?
It is only one input to a broader system. It does not by itself establish identity, intention or meaning.
Next Reading
Continue to Gauge R&R, Variance Components and Measurement Systems for another example of extracting a useful signal while preserving uncertainty, or return to the Mathematics Learning Hub. The happiest lesson here is simple: motion becomes understandable when we turn a visual hunch into equations we can test.
A Practical Investigation Studio
Use synthetic or openly released teaching data. These investigations reveal assumptions and error signals; they do not replace professional computer vision, engineering design, process diagnosis or operational approval.
Investigation 1: Moving square
Generate two small images with a bright square shifted by known pixels. Compare the known displacement with the estimate. Use synthetic or openly released teaching data. Begin by naming the response variable, input variables, units and prediction before calculating. Preserve raw values and unrounded intermediates in a table, then make one graph whose axes communicate the model clearly. Add an independent hand estimate and a dimensional or limiting-case check. Deliberately introduce one unit error and describe the numerical signature rather than merely correcting it. Label every quantity observed, assumed, fitted or derived. Record the model domain and one condition that would require a richer model. Ask a peer to reproduce the result from the written procedure without seeing the answer. If the reproduction differs, locate whether the ambiguity arose in definitions, units, rounding or software defaults. End by explaining the result to a younger student in three sentences. This remains a classroom calculation, not professional validation or a safety, production or security decision.
Investigation 2: Gradient directions
Calculate x and y finite differences around a synthetic corner. Show why one edge alone leaves motion ambiguous. Create a data dictionary before entering a spreadsheet or script. State how each row was obtained, which values are exact by definition and which are measurements or simulated observations. Calculate once with full precision and once with premature rounding, then compare the final difference. Vary the principal input across at least five sensible values and look for linearity, curvature or instability instead of reporting only two endpoints. Keep signed residuals if a model is fitted, because absolute errors hide direction. Include a graph and a small results table that another person can audit. Write a one-paragraph uncertainty note distinguishing input uncertainty from model-form limitations. A peer should be able to reconstruct one row from the formula and raw data alone. State what evidence would falsify the interpretation. Do not present the exercise as a certified engineering, manufacturing, metrology or cryptographic assessment.
Investigation 3: Brightness equation
Insert a known translation into Ix u + Iy v + It = 0. Track sign and pixel-per-frame units. Treat the investigation as a comparison of hypotheses, not a hunt for an attractive number. Write a baseline model and at least one plausible alternative, then predict where their outputs should diverge. Hold all unrelated inputs fixed while varying the chosen factor. Preserve coordinate, sign, phase, size-weighting or bit conventions beside the data. Use a ratio, residual or normalised error that has a declared denominator. Repeat the calculation with that denominator changed and explain why the percentage changes. Check one extreme case where the answer should approach zero, unity or another known limit. Make the graph before writing the conclusion and note any outlier without deleting it. Separate repeatability of one prepared sample from coverage across positions, times or populations. The final claim should match the observed range and must not be extrapolated into real operational approval.
Investigation 4: Window solve
Assemble the two-by-two normal equations for several neighbouring pixels. Inspect determinant and eigenvalues before solving. Plan the computation so that errors leave visible fingerprints. Save the raw input, transformed input, intermediate result and final result in separate columns or variables. Insert one deliberate sign reversal, one missing observation and one hidden reset, each in a separate copy, and document how the plots or checks respond. Compare an analytical shortcut with the more complete calculation over a range where the shortcut is expected to fail. Report the largest absolute difference and where it occurs. Include conservation, balance, boundedness or monotonicity checks appropriate to the topic. If a fitted curve is used, inspect residual clusters and changing spread instead of relying on one fit statistic. Have a peer review only the assumptions first, then the arithmetic. Keep the conclusion educational and conditional on the fictional data.
Investigation 5: Aperture problem
Move a long diagonal edge in two different ways. Identify the observable normal component. Build a sensitivity map rather than changing several settings at once. Choose a baseline, vary one input downward and upward, and express output change in both original units and a dimensionless ratio. Then select a second input and repeat. If interactions seem likely, test a small two-dimensional grid and identify where the one-factor interpretation breaks down. State why the chosen ranges are plausible for the teaching model. Preserve failed or surprising runs and annotate them. Compare computational resolution or sample length at three levels so numerical artefacts are not confused with physical behaviour. Provide a hand estimate for the order of magnitude. Finish with a decision table using cautious language—stable, sensitive or unresolved—rather than safe or unsafe. Classroom evidence cannot authorise a product, structure, process or security control.
Investigation 6: Pyramid motion
Downsample a large displacement through three levels. Map the estimate back with the correct scale. Make uncertainty visible at every stage. Assign each input a source and a plausible interval, then identify which inputs are correlated rather than automatically treating them as independent. Propagate uncertainty with a simple high-and-low calculation or transparent simulation, and retain the seed or full synthetic samples for reproduction. Compare the spread caused by measurement variation with the shift caused by changing the model assumption. Plot both if possible. Explain why more decimal places do not narrow an interval supported by weak inputs. If a result lies near a fictional decision boundary, rewrite the conclusion to reflect the chance of crossing it. Ask a peer to challenge the largest assumed uncertainty and rerun the analysis. Report the conclusion as evidence about the model, never as professional certification.
Investigation 7: Noise test
Add several levels of image noise. Plot endpoint error against noise level. Audit representation choices. Recalculate after changing the coordinate origin, phase wrapping convention, histogram bins, mesh labels or binary mapping while preserving the underlying situation. A correct physical or probabilistic conclusion should change only where the definition genuinely changes. Show one example where a visual choice exaggerates or hides a pattern. Use identical axes for fair comparison and include sample count or resolution in captions. Test an invariant such as total mass, probability, force, energy sign or average ratio. Where values are averaged, identify whether the mean is number-, mass-, volume-, time- or state-weighted. Ask another student to explain the plot without reading the conclusion; revise labels if their interpretation differs. The display supports reasoning but cannot replace domain review.
Investigation 8: Illumination change
Multiply one frame by a gain and add an offset. Record the failure of brightness constancy. Separate verification from validation. First verify arithmetic or code against a case with a known answer, including units and at least one manually calculated row. Next ask whether the teaching model represents the intended phenomenon and list the omitted mechanisms. Refine numerical resolution or increase synthetic sample length and record whether the chosen quantity stabilises. A stable answer can still arise from an unrealistic model, so compare with an alternative assumption or openly documented benchmark. Record software version, solver or library settings and stopping rules. Avoid tuning settings after seeing the desired result; predeclare the comparison instead. Summarise numerical error, input uncertainty and model-form uncertainty separately. No classroom agreement with a benchmark should be described as product or system validation.
Investigation 9: Occlusion mask
Hide part of the moving object in the second frame. Use forward-backward consistency to flag weak tracks. Design the investigation to reveal dependence over position, time or sequence order. Keep the original ordering, then compare with a deliberately shuffled copy and explain which statistics change. Examine at least two lags, locations or neighbourhood scales rather than only the overall average. Plot local values alongside the aggregate so compensating errors are visible. State whether successive observations are plausibly independent and why that matters to the calculation. If repeated measurements share one specimen, source or initial state, do not count them as independent coverage. Add a block or subgroup analysis and note any drift. Preserve the random seed for simulated data but use more than one seed before generalising. The conclusion should describe detected structure without claiming causation from the pattern alone.
Investigation 10: Dense and sparse
Estimate selected corners and a full motion field. Compare cost, coverage and confidence. Create an adversarial edge-case test. Identify the smallest, largest, most symmetric and most irregular inputs allowed by the classroom model, predict the expected behaviour, and then compute it. Include zero or a limiting value only when mathematically meaningful. Watch for division by a small number, logarithms of invalid values, wrapped angles, negative geometry, impossible probabilities or solver singularities. Replace silent software errors with explicit checks and explanatory messages. Compare the edge cases with the ordinary baseline on the same scale and describe why a method that works in the middle may fail near a boundary. Record the first assumption that breaks. The exercise is about model literacy; it is not permission to explore hazardous physical extremes.
Investigation 11: Reproducible report
Archive frames, parameters, masks and errors. Have a peer regenerate one vector field. Prepare a compact reproducibility package: raw synthetic data, formulas or code, version information, one chart, a results table and a short read-me file. Give every file and column a meaningful name and avoid values copied manually between tools. Re-run from a clean state and confirm that outputs are regenerated rather than cached. Ask a peer to alter one declared input and predict the direction of change before execution. Compare the prediction with the result and investigate any disagreement. Add a limitations section naming data coverage, numerical resolution, model assumptions and the next useful measurement. Archive corrections instead of erasing them so the reasoning trail remains visible. Conclude with what the calculation demonstrates, what it does not demonstrate and which qualified professional or authoritative standard would govern a real application.
