Main Content


Object for estimating optical flow using Lucas-Kanade method


Create an optical flow object for estimating the direction and speed of a moving object using the Lucas-Kanade method. Use the object function estimateFlow to estimate the optical flow vectors. Using the reset object function, you can reset the internal state of the optical flow object.



opticFlow = opticalFlowLK returns an optical flow object that you can use to estimate the direction and speed of the moving objects in a video. The optical flow is estimated using the Lucas-Kanade method.


opticFlow = opticalFlowLK('NoiseThreshold',threshold) returns an optical flow object with the property 'NoiseThreshold' specified as a Name,Value pair. Enclose the property name in quotes.

For example, opticalFlowLK('NoiseThreshold',0.05)


expand all

Threshold for noise reduction, specified as a positive scalar. As you increase this number, the movement of the objects has less impact on optical flow calculation.

Object Functions

estimateFlowEstimate optical flow
resetReset the internal state of the optical flow estimation object


collapse all

Read a video file. Specify the timestamp of the frame to be read.

vidReader = VideoReader('visiontraffic.avi','CurrentTime',11);

Create an optical flow object for estimating the optical flow using Lucas-Kanade method. Specify the threshold for noise reduction. The output is an optical flow object specifying the optical flow estimation method and its properties.

opticFlow = opticalFlowLK('NoiseThreshold',0.009);

Create a custom figure window to visualize the optical flow vectors.

h = figure;
hViewPanel = uipanel(h,'Position',[0 0 1 1],'Title','Plot of Optical Flow Vectors');
hPlot = axes(hViewPanel);

Read the image frames and convert to grayscale images. Estimate the optical flow from consecutive image frames. Display the current image frame and plot the optical flow vectors as quiver plot.

while hasFrame(vidReader)
    frameRGB = readFrame(vidReader);
    frameGray = im2gray(frameRGB);
    flow = estimateFlow(opticFlow,frameGray);
    hold on
    plot(flow,'DecimationFactor',[5 5],'ScaleFactor',10,'Parent',hPlot);
    hold off


expand all

To compute the optical flow between two images, you must solve this optical flow constraint equation:



  • Ix, Iy, and It are the spatiotemporal image brightness derivatives.

  • u is the horizontal optical flow.

  • v is the vertical optical flow.


[1] Barron, J. L., D. J. Fleet, S. S. Beauchemin, and T. A. Burkitt. “ Performance of optical flow techniques.” In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR),236-242. Champaign, IL: CVPR, 1992.

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Version History

Introduced in R2015a