Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

There are a few different ways to generate movies/videos/animations with MATLAB.  Below is one method that works with Linux/Ubuntu.

There are two basic steps:

  1. In MATLAB, generate a sequence of images.  Save those images as sequentially named files (ex, image-001.png, image-002.png, etc.).
  2. In Linux use a tool like ffmpeg or avconv to generate a movie file from the image sequence.

The code for these examples is at https://github.com/bsb808/matlabmovie

Step 1: Generating Image Sequence with MATLAB

Here is an example script that uses export_fig (described here) to generate a sequence of images in the "movie" directory.

Code Block
% Example of creating a MATLAB animation
% For the example we will create a sequence of images, saving each image in
% the sequence to a file.  Then, externally (not in MATLAB) we will combine
% the images into a video file.

% Create a sequence of images
N = 100;
figure(1);
clf();
YY = [];
for ii = 1:N
    YY(ii) = rand();
    plot(1:ii,YY,'o-')
    xlabel('Distance [m]')
    ylabel('Force [N]')
    title(sprintf('Step %d',ii));
    grid on;
    axis([0 N 0 1])
    
    % Save each figure as a image file (.png) 
    % The number of the image is included in the file name
    % Make sure there is a directory called "movie" in your current working
    % directory.
    fname = sprintf('movie/image-%05d',ii);
    % Saves each image at 72 dpi.  May want to adjust the resolution
    cmd = sprintf('export_fig %s -png -r72 -painters',fname);
    eval(cmd)
end

Now you should have a bunch of image.  The directory should look like this...

Image Added

Step 2: Generating a Movie from Image Sequence

The following command should find these images and convert them to a movie with the file name out.mp4

Code Block
 avconv -framerate 4 -i "./movie/image-%05d.png" -c:v libx264 -r 20 -pix_fmt yuv420p -crf 20 -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" out.mp4

The syntax is equivalent for ffmpeg.  There are a bunch of cryptic options here.

If all goes well you should have the out.mp4 file as a movie...

out.mp4

Multimedia
nameout.mp4

Note the the video quality is not terribly high.  To increase the quality you can adjust the image resolution in MATLAB and or the command line options for the avconv/ffmpeg call.