estimateFlow
Description
estimates the optical flow between the current frame flow = estimateFlow(flowModel,I)I and the previous
frame using the recurrent all-pairs field transforms (RAFT) deep learning algorithm.
RAFT optical flow estimation outperforms methods like Farneback by delivering higher accuracy, particularly in areas with minimal texture and under difficult camera movements.
specifies options using one or more name-value arguments in addition to the previous syntax.
For example, flow = estimateFlow(flowModel,I,Name=Value)MaxIterations=10 sets the number of refinement iterations to
10.
Examples
Create a RAFT optical flow object.
flowModel = opticalFlowRAFT;
Create an object to read the input video file.
vidReader = VideoReader("visiontraffic.avi",CurrentTime=11);Create a custom figure window to visualize the optical flow vectors.
h = figure;
movegui(h);
hViewPanel = uipanel(h, Position=[0 0 1 1], Title="Plot of Optical Flow Vectors");
hPlot = axes(hViewPanel);Read consecutive image frames to estimate optical flow. Display the current frame and overlay optical flow vectors using a quiver plot. The estimateFlow function calculates the optical flow between two consecutive frames.
Note that the function internally stores the previous frame and utilizes it implicitly for optical flow estimation. Consequently, when the function is called for the first time on a sequence of frames, it will return a zero flow. This is because, in the absence of a genuine previous frame, the initial frame is treated as both the current and previous frame, leading to no detectable motion between the two. This is consistent with the argument structure and behavior of established optical flow estimation methods, such as opticalFlowFarneback.
while hasFrame(vidReader) frame = readFrame(vidReader); flow = estimateFlow(flowModel,frame); imshow(frame) hold on plot(flow,DecimationFactor=[10 10],ScaleFactor=0.45,Parent=hPlot,color="g"); hold off pause(10^-3) end

Reset the opticalFlowRAFT object after the video processing has completed. This clears the internal state of the object, including the saved previous frame.
reset(flowModel);
RAFT provides accurate optical flow estimation, but it can be memory-intensive when applied to large images or run on GPUs with limited memory. In such cases, processing high-resolution frames directly may lead to out-of-memory (OOM) errors. A practical solution is to downscale the input images before passing them to the RAFT model, compute optical flow at the reduced resolution, and then rescale the resulting flow field back to the original size of the imagery. This example demonstrates how to apply this memory-efficient strategy, allowing you to use RAFT on larger images or resource-constrained hardware while preserving meaningful flow estimates.
Load Image Pair
Load two images and visualize their pixel-wise differences due to camera motion using a red-cyan composite image.
I1 = imread("yellowstone_left.png"); I2 = imread("yellowstone_right.png"); figure imshow(stereoAnaglyph(I1, I2)) title("Composite Image (Red - Left Image, Cyan - Right Image)")

Display the spatial dimensions of the images.
disp(size(I1, [1 2]))
480 640
Create opticalFlowRAFT Object
Create an opticalFlowRAFT object for computing optical flow between two images.
raft = opticalFlowRAFT;
Estimate Optical Flow on Full Resolution Images
Estimate optical flow on the images at original resolution. This gives the most accurate result but may cause into slow runtime and high memory consumption.
estimateFlow(raft, I1); flowFull = estimateFlow(raft, I2);
Estimate Optical Flow on Downsampled Images
Create Downscaled Images
Scale the image dimensions by a factor of 0.5 for illustrative purpose. A small resolution image can result in faster optical flow computation and less memory consumption.
I1Small = imresize(I1, 0.5); I2Small = imresize(I2, 0.5);
Display the resized image dimensions.
disp(size(I1Small, [1 2]))
240 320
Estimate Flow on Downscaled Images
Compute optical flow on downscaled images. Use the same opticalFlowRAFT model instantiated earlier after resetting it.
reset(raft); estimateFlow(raft, I1Small); flowLowRes = estimateFlow(raft, I2Small);
Scale Estimated Flow to Original Resolution
Upsample and scale the lower resolution optical flow back to the original image resolution.
origDims = size(I1, [1 2]); scaleX = origDims(2) / size(flowLowRes.Magnitude, 2); scaleY = origDims(1) / size(flowLowRes.Magnitude, 1); flowX = imresize(flowLowRes.Vx, origDims, "bilinear") * scaleX; flowY = imresize(flowLowRes.Vy, origDims, "bilinear") * scaleY; flowUpscaled = opticalFlow(flowX, flowY);
Compare Optical Flow at Original and Downscaled Resolutions
Visually compare optical flow computed directly on the original high-resolution images with optical flow computed on downscaled images and then rescaled back to the original size. This comparison illustrates how the downscale-upscale workflow approximates the original flow while reducing memory usage.
figure subplot(1,2,1) imshow(I1) hold on plot(flowFull, DecimationFactor=[40 40], ScaleFactor=0.75, Color="g"); hold off title("Optical Flow at Full Resolution") subplot(1,2,2) imshow(I1) hold on plot(flowUpscaled, DecimationFactor=[40 40], ScaleFactor=0.75, Color="g"); hold off title("Optical Flow at Half Resolution")

The bilinear interpolation in the image resizing operations can introduce numerical inaccuracies and overly-smoothed results in the upscaled optical flow. This reduced accuracy is a trade-off against the lower memory consumption when optical flow computation is performed on lower resolution imagery.
Input Arguments
Optical flow object, specified as an opticalFlowRAFT object.
Current video frame, specified as a 2-D grayscale or RGB image. When the input image
is of type uint8 or int16, the pixel values must
be in the range [0,255]. When the input image is of type
single or double, the pixels values must be in
the range [0,1]. The RAFT model requires input images to have a
minimum dimension of more than 57 pixels on the shortest side.
When initializing motion estimation in a video, the first frame is duplicated as its own "previous frame" to ensure the calculated motion (optical flow) starts from zero, as there is no actual prior frame to compare with.
Data Types: single | double | int16 | uint8
Name-Value Arguments
Specify optional pairs of arguments as
Name1=Value1,...,NameN=ValueN, where Name is
the argument name and Value is the corresponding value.
Name-value arguments must appear after other arguments, but the order of the
pairs does not matter.
Example:
estimateFlow(flowModel,I,MaxIterations=10) sets the number of refinement
iterations to 10.
Number of refinement iterations, specified as an integer. Increasing the number of
refinement iterations enhances the precision of the optical flow estimation from its
initial prediction by iteratively refining the calculation. Decreasing this value
accelerates the algorithm's execution but compromises on accuracy. A typical value is
12.
Acceptable difference between consecutive refinement iterations, specified as a scalar. The tolerance level set for iterations in estimating optical flow, beginning with an initial prediction, determines the acceptable deviation between each successive iteration. If the variation in optical flow between two successive updates falls below this tolerance threshold, the iteration process is halted. Opting for larger tolerance values can speed up the process but at the expense of reduced accuracy.
Processing execution environment to perform the model's inference, specified as
"cpu", "gpu", or "auto".
"auto"— Use a local GPU if one is available. Otherwise, use the local CPU."cpu"— Use the local CPU."gpu"— Use the local GPU.
Acceleration, specified as "auto" or "none".
The "auto" acceleration setting increases memory usage but also
speeds up execution.
Output Arguments
Optical flow velocity matrices, returned as an opticalFlow object.
Tips
Using RAFT for optical flow estimation on a GPU requires a minimum of 12 GB of memory.
The RAFT model, being fully convolutional, can process images of any size in theory, with the only limitation being the available GPU memory.
Extended Capabilities
This function fully supports GPU acceleration.
By default, the estimateFlow function uses a GPU if one is
available. You can specify the hardware that the estimateFlow function
uses by setting the ExecutionEnvironment (Deep Learning Toolbox) name-value argument.
For more information, see Scale Up Deep Learning in Parallel, on GPUs, and in the Cloud (Deep Learning Toolbox).
Version History
Introduced in R2024b
See Also
Objects
Functions
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)