使用PPT 做汇报和报告的时候,通常需要用到动态图来展示数据的动态变化过程,gif格式的图片较视频文件而言占用内存小,用起来也方便,那如何使用MATLAB将生成的数据做成动画并保存为 .gif格式的文件呢?
一、方法:
核心函数:
- imwrite :该函数功能是“将图像写入图形文件”,包括(1)将灰度图像写入PNG,。(2)将索引图像写入到PNG。(3)将RGB图写入到JPEG。(4)将多个图像写入到TIFF文件。(5)制作GIF动画。函数语法:imwrite(A, map, filename)等,imwrite(A, map, filename)是将A中的索引图像及其关联的颜色图写入由map和filename指定的文件。
- getframe: 函数功能是“捕获坐标区或图窗作为影片帧“。函数语法:F=getframe(*),*=gcf时可捕获当前图窗,指定为图窗对象;*=gca时,可捕获坐标区,指定为坐标区域(坐标轴没有标尺,没有轴标签等)。需要捕获指定大小区域的图像时,使用F=getframe(gcf,[left bottom width height]);其中F为影片帧结构体。
- frame2im:该函数功能是”返回与影片帧关联的图像数据“。函数语法:[X,Map]=frame2im(F),X是索引图像数据,Map为关联的颜色图。
- rgb2ind:函数功能是”将RGB图像转换为索引图像“。语法:[X,map]=rgb2ind(RGB,n)等。map最多包含n个颜色,n<=65536。
二、示例
- 幂函数
,底数x在区间[0,1]范围内,函数图像随指数n的变化情况,n=1:0.5:5。
方法一[1]:
x
方法二 [2]:
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
效果图:
2.螺旋线
close
效果图:
参考
- ^[1] https://ww2.mathworks.cn/help/matlab/ref/imwrite.html?s_tid=srchtitle
- ^[2] https://ww2.mathworks.cn/matlabcentral/answers/94495-how-can-i-create-animated-gif-images-in-matlab