Thursday, December 21, 2017

[Matlab] Animate a plot and Play a video

A plot can be animated along with x axis, and a video also can be played in Matlab.

Three basic techniques are used for creating animations.
1. Update the properties of a graphics object and display the updates on the screen. This is useful for creating animations when most of the graph remains the same.
2. Apply transforms to objects. This is useful when you want to operate on the position and orientation of a group of objects together.
3. Create a movie. Movies are useful if you have a complex animation that does not draw quickly in real time, or if you want to store an animation to replay it. Use the getframe and movie functions to create a movie.

Below are examples for animations.

1. Plot animation

%% Real time floating axis
h = animatedline;
% axis([0,12,-1,1]); 
timestep = 0.1;
x = 0:timestep:12;%4*pi;
y = sin(x);
tic; % start timer
% h = animatedline(x,y,'Color','r','LineWidth',2);

for k = 1:length(x)
    addpoints(h,x(k),y(k));
    b=toc;% check timer
    if k==1
        timestep = 0;       
    else
        if b < timestep % Calculated time is bigger than timer?
            pause(timestep - b); % Then, pause until time = timer
            drawnow % update
        else
            drawnow
        end
    end
    %timestep;
    timestep = timestep + 0.1;
end

2. Play a video

% Load a video file
video = 'C:\movie.avi';
% Read a file
v = VideoReader(video);
vWid = v.Width; vHei = v.Height;
% Frame per second
fps = get(v, 'FrameRate');
currAxes = axes;
v.CurrentTime = 0;% Specify the starting time [sec]
v.Duration % [sec] Unable to set ths property. Read-only property. Total play time
tic;
k=0;
while hasFrame(v)
  vidFrame = readFrame(v);
  ts = toc;
  image(vidFrame, 'Parent', currAxes);% Display each frame
  currAxes.Visible = 'off';
  if ts <= k
    pause(k-ts); % Wait until time = timer
  end
  k=k+1/fps; % Calculate time
end








No comments:

Post a Comment