Estimate Optical Flow Using Farneback Method

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 Farneback method. The output is an object specifying the optical flow estimation method and its properties.

opticFlow = opticalFlowFarneback
opticFlow = 
  opticalFlowFarneback with properties:

    NumPyramidLevels: 3
        PyramidScale: 0.5000
       NumIterations: 3
    NeighborhoodSize: 5
          FilterSize: 15

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 = rgb2gray(frameRGB);  
    flow = estimateFlow(opticFlow,frameGray);
    hold on
    plot(flow,'DecimationFactor',[5 5],'ScaleFactor',2,'Parent',hPlot);
    hold off