Ali P
Ali P

Reputation: 519

Car Tracking using Optical Flow. Why isnt the vectors plotting properly

I am new to optical flow and computer vision in general and I started to work with a simple demo example from Matlab.

The objective of it is to use a video and plot the motion vectors onto the screen. I am using the following code:

%% initialization
close all
clear all

% Create reader

reader = vision.VideoFileReader;
reader.Filename = 'viptraffic.avi';

   % Create viewer
   viewer = vision.DeployableVideoPlayer;
   %%viewer.FrameRate = 10;

%Create Optical Flow
optical = vision.OpticalFlow; %how pixels are moving from one frame to the next
optical.OutputValue = 'Horizontal and vertical components in complex form'; %will allow         us to draw a vector
%%%on the vision so that we see how the pixels are moving from one frame to the next

%%We pass the horizontal and vertical components to the shape inserter
%%below

% Display vector fields
shapes = vision.ShapeInserter;
shapes.Shape = 'Lines';
shapes.BorderColor = 'white';

R = 1:4:120;%%downsample the optical flow field
C = 1:4:160;%%downsample the optical flow field

[Cv, Rv] = meshgrid (C, R); %%% display a grid on the image and take every fourth value


Rv = Rv(:)';
Cv = Cv(:)';

 %% Execution
 reset(reader)

 %Set up for stream
 while ~isDone(reader)

 I = step(reader);
 of = step(optical,rgb2gray(I));
 size(of)

 ofd = of(R,C);
 size(ofd)


 H = imag(ofd)*20;
 V = real(ofd)*20;


 %Draw lines on top of image
 lines = [Rv;Cv; Rv+H(:)'; Cv+V(:)']; %%start and a finish , start+movement,   end+movement
 % lines = [Cv;Rv;Cv;Rv];
 Ishp = step(shapes,I,lines);

 step(viewer,Ishp);

 end
 release(viewer);

I do not why the vector lines are not plotting properly.

Can anyone help me?

Thanks

PS: here is the result: enter image description here

Upvotes: 1

Views: 929

Answers (1)

Dima
Dima

Reputation: 39389

Try using

lines = [Rv(:); Cv(:); Rv(:)+H(:); Cv(:)+V(:)];

instead of

lines = [Rv;Cv; Rv+H(:)'; Cv+V(:)'];

Better yet, if you have a recent version of Matlab, try using the insertShape function instead of vision.ShapeInserter.

Edit: If you have a recent version of the Computer Vision System Toolbox, try the new optical flow functions: opticalFlowHS, opticalFlowLK, opticalFlowLKDoG, and opticalFlowFarneback.

Upvotes: 1

Related Questions