Horn-Schunck Global Optical Flow
Implement Horn-Schunck optical flow with smoothness constraint to estimate the motion of pixels between two consecutive frames. This method is used to calculate the optical flow, which is the apparent motion of pixels in an image.
The Horn-Schunck method assumes that the brightness constancy of the scene is maintained between frames, which can be expressed as , where and are the spatial gradients of the image intensity, is the temporal gradient, and and are the horizontal and vertical components of the optical flow. To handle the aperture problem, a smoothness constraint weighted by (where is the alpha argument) is added to the energy function.
Here are the steps to calculate the optical flow:
- Compute the spatial and temporal gradients of the image intensity.
- Initialize the optical flow components and .
- Iterate to minimize the energy function.
This technique is widely used in video analysis and object tracking applications.
Example
Two frames
Dense optical flow
- Inputs:
img1,img2are consecutive grayscale frames;alphaweights smoothness,n_itercounts sweeps. The test uses two all-zero frames, , 100 sweeps. - Gradients: is the horizontal (left-to-right) brightness change and the vertical (top-to-bottom) change in the first frame; is the change between frames. Here all three are .
- Math: each pixel's trades the brightness-constancy error against times its deviation from the neighbours' average. At zero flow both terms vanish, so after every sweep.
- Output: dense optical flow, an array (channel 0 is , channel 1 is ); the test prints
(16, 16, 2). - Notice: flow is measurable only where there is texture. On a horizontal ramp (, constant ) the flow settles at , , and flat regions borrow flow from textured neighbours.
Constraints
- Input frames: 2D numpy arrays (grayscale) with shape (H, W) and dtype float32
- Pixel values: in range [0, 255] and assumed to be normalized to [0, 1] for computation
- Output optical flow: 2D numpy array with shape (H, W, 2) and dtype float32, representing horizontal and vertical flow components
- Smoothness parameter: α is a positive scalar, assumed to be provided as an input or set to a default value of 0.001
- Iteration limit: maximum number of iterations to minimize the energy function, assumed to be set to a default value of 1000 or provided as an input