make gif from mp4 video

I like to make video clips with Matlab for some visualization. However, to publish it with a .mp4 format is not always a good idea.

It would be much easy to insert .gif files in a web-page.

Here’s the way to convert .mp4 files into .gif using ImageMagick.

First, change directory to the location of the .mp4 file. For example,

cd /Users/roy/Documents/MATLAB/fun

Create a new folder to store the temporary files.

mkdir frames

Next, extract images from video,

ffmpeg -i waveInterference.mp4  -r 20 'frames/frame-%03d.jpg'

where -r 20 stands for 20 frames per second (fps), and %03d is the regular rule for naming: integer number with 3 field width, and padding to field width with zeros before the value.

At last, convert image to gif,

cd frames
convert -delay 5 -loop 0 *.jpg waveInterference.gif

-delay 5 means the time between each frame is 0.05 seconds, which match 20 fps above (in general 100/delay = fps). -loop 0 means repeat forever.

Most of the time, the .gif file created this way is with big size, and you could optimize the frames following the manual here, Optimize gif frame.

This is the example I made illustrating two wave interference. Converted from the original Mathematica code to Matlab.

two wave interference

code here:

nPoints = 2^7;
x = linspace(0, 16, nPoints);
y = linspace(-8, 8, nPoints);
[X, Y] = meshgrid(x, y);

nLoop = 2^4;
t = linspace(0, 1, nLoop);

fig = figure();
writer = VideoWriter('waveInterference.mp4', 'MPEG-4');
writer.FrameRate = 10;
open(writer);

for iL = 1 : nLoop
    eField = sin(2*pi*(sqrt(X.^2 + (Y-4).^2) - t(iL))) ...
    + sin(2*pi*(sqrt(X.^2 + (Y+4).^2) - t(iL)));
    pcolor(X, Y, eField)
    axis off
    shading interp
    colormap(gray)
    frame = getframe(fig);
    writeVideo(writer, frame);
end
close(writer);