Matlab:如何将动画情节保存为 gif
Matlab: how to save animated plot to a gif
考虑以下函数,该函数绘制了一个动画图。
function animate1()
clear, clc
R = 1;
na = -pi/2;
t = 0:0.05:6;
v = 4;
for i = 1:length(t)
x0 = v*t(i);
y0 = R;
na = -v*t(i)/R;
fi = linspace(na,na+2*pi,100);
x = x0 + R*cos(fi);
y = y0 + R*sin(fi);
xc(i) = x0 + R*cos(na);
yc(i) = y0 + R*sin(na);
plot(x,y,'b',...
xc(i),yc(i),'*m',...
xc,yc,'r')
axis([-1 25 0 1.5])
axis equal
pause(0.01)
end
是否可以修改代码使其输出动画情节,例如到 gif?
提前致谢!
是的,imwrite
支持 GIF 动画。与 AVI 视频一样,您可以通过 getframe
顺序抓取帧。然后将它们传递给 imwrite
,但对于 GIF,您必须先将它们从 RGB 转换为 256 色图。像这样:
for i = 1:nFrames
% draw stuff
frame = getframe(gcf);
img = frame2im(frame);
[img,cmap] = rgb2ind(img,256);
if i == 1
imwrite(img,cmap,'animation.gif','gif','LoopCount',Inf,'DelayTime',1);
else
imwrite(img,cmap,'animation.gif','gif','WriteMode','append','DelayTime',1);
end
end
查看 openExample('matlab/WriteAnimatedGIFExample')
和 doc imwrite
了解更多信息。
考虑以下函数,该函数绘制了一个动画图。
function animate1()
clear, clc
R = 1;
na = -pi/2;
t = 0:0.05:6;
v = 4;
for i = 1:length(t)
x0 = v*t(i);
y0 = R;
na = -v*t(i)/R;
fi = linspace(na,na+2*pi,100);
x = x0 + R*cos(fi);
y = y0 + R*sin(fi);
xc(i) = x0 + R*cos(na);
yc(i) = y0 + R*sin(na);
plot(x,y,'b',...
xc(i),yc(i),'*m',...
xc,yc,'r')
axis([-1 25 0 1.5])
axis equal
pause(0.01)
end
是否可以修改代码使其输出动画情节,例如到 gif?
提前致谢!
是的,imwrite
支持 GIF 动画。与 AVI 视频一样,您可以通过 getframe
顺序抓取帧。然后将它们传递给 imwrite
,但对于 GIF,您必须先将它们从 RGB 转换为 256 色图。像这样:
for i = 1:nFrames
% draw stuff
frame = getframe(gcf);
img = frame2im(frame);
[img,cmap] = rgb2ind(img,256);
if i == 1
imwrite(img,cmap,'animation.gif','gif','LoopCount',Inf,'DelayTime',1);
else
imwrite(img,cmap,'animation.gif','gif','WriteMode','append','DelayTime',1);
end
end
查看 openExample('matlab/WriteAnimatedGIFExample')
和 doc imwrite
了解更多信息。