目录
一、粗略版
使用“ imwrite”功能创建动画GIF。
动画GIF包含一系列图像,这些图像全部组合成一个文件。
在这个例子中
1.为n的不同值绘制函数y = x ^ n的一系列图
2.捕获图像
3.将图像写入GIF文件
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
二、详解版
绘制一系列图、将它们捕获为图像,然后写入 GIF 动画文件。
1、绘制
,其中
。
x = 0:0.01:1;
n = 3;
y = x.^n;
plot(x,y,'LineWidth',3)
title(['y = x^n, n = ' num2str(n) ])
2、捕获
值递增时的一系列绘图。
n = 1:0.5:5;
nImages = length(n);
fig = figure;
for idx = 1:nImages
y = x.^n(idx);
plot(x,y,'LineWidth',3)
title(['y = x^n, n = ' num2str( n(idx)) ])
drawnow
frame = getframe(fig);
im{idx} = frame2im(frame);
end
close;
3、将多个系列的图像显示在一个图窗中
figure;
for idx = 1:nImages
subplot(3,3,idx)
imshow(im{idx});
end
4、将九个图像保存到一个 GIF 文件中
因为 GIF 文件不支持三维数据,所以应调用 rgb2ind
,使用颜色图 map
将图像中的 RGB 数据转换为索引图像 A
。
要将多个图像添加到第一个图像中,请使用名称-值对组参数 'WriteMode','append'
调用 imwrite
。
filename = 'testAnimated.gif'; % Specify the output file name
for idx = 1:nImages
[A,map] = rgb2ind(im{idx},256);
if idx == 1
imwrite(A,map,filename,'gif','LoopCount',Inf,'DelayTime',1);
else
imwrite(A,map,filename,'gif','WriteMode','append','DelayTime',1);
end
end
imwrite
将 GIF 文件写入当前文件夹。
名称-值对组 'LoopCount',Inf
使动画连续循环。
'DelayTime',1
在每个动画图像显示之间指定了一秒的时滞。
版权声明:本文为weixin_45770896原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。