MATLAB Answers

How can I create animated GIF images in MATLAB ?

조회 수: 3,664(최근 30일)
I would like to know if there is MATLAB functionality to create an animated GIF in MATLAB.

채택된 답변

MathWorks Support Team
MathWorks Support Team 2017년 6월 12일
Use the 'imwrite' function to create an animated GIF. An animated GIF contains a series of images all combined into one file. For this example,
1. Draw a series of plots for the function y = x^n for different values of n
2. Capture them as images
3. Write them into a GIF file
h = figure;
axis tight manual % this ensures that getframe() returns a consistent size
filename = 'testAnimated.gif';
for n = 1:0.5:5
% Draw plot for y = x.^n
x = 0:0.01:1;
y = x.^n;
plot(x,y)
drawnow
% Capture the plot as an image
frame = getframe(h);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
% Write to the GIF File
if n == 1
imwrite(imind,cm,filename,'gif', 'Loopcount',inf);
else
imwrite(imind,cm,filename,'gif','WriteMode','append');
end
end
For a more detailed description on creating an animated GIF File, see the example “Write Animated GIF” on the 'imwrite' function reference page:
  댓글 수: 12
Walter Roberson
Walter Roberson 2021년 9월 8일
prefix = 'abc_20190304'
dinfo = dir( [prefix '*.png']);
filenames = {dinfo.name};
for K = 1 : length(filenames)
work with file name in filenames{K}
end

댓글을 달려면 로그인하십시오.

추가 답변(3개)

Chad Greene
Chad Greene 2017년 6월 4일
Or, for a much simpler option, use the gif function on File Exchange.

Shashank Rai
Shashank Rai 2017년 5월 1일
편집: Chad Greene 2018년 10월 17일
x = 0:0.01:1;
figure(1)
filename = 'testnew51.gif';
for n = 1:0.5:5
y = x.^n;
plot(x,y)
drawnow
frame = getframe(1);
im = frame2im(frame);
[imind,cm] = rgb2ind(im,256);
if n == 1;
imwrite(imind,cm,filename,'gif', 'Loopcount',inf);
else
imwrite(imind,cm,filename,'gif','WriteMode','append');
end
end
  댓글 수: 1
Coleman Barrie
Coleman Barrie 2019년 6월 15일
Thank you for writing this very helpful as a framework to modify

댓글을 달려면 로그인하십시오.


Alec
Alec 2013년 12월 19일
So it appears that `imwrite` now supports writing animated grayscale GIFs "When writing multiframe GIF images, X should be an 4-dimensional M-by-N-by-1-by-P array, where P is the number of frames to write."
But if I try to pass it an M-by-N-by-3-by-P it seems to treat each RGB color channel as a separate grayscale frame. Is there now way to write an animated color GIF without a for loop over the frames?

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by