【问题标题】:How to get GIF from figure如何从图中获取 GIF
【发布时间】:2018-10-24 03:35:09
【问题描述】:

我编写了下面的代码。它会生成我想要转换为 GIF 的想要的图表,但是这部分不起作用。如何调整它以使 GIF 正常工作?

function []=cyclotron()
t=0:0.01:27;
dt=[diff(t),eps];
figure, hold on
[x1,y1,z1] = sphere ;
xnew1=x1;ynew1=y1;znew1= -abs(z1);
s=surf(xnew1,ynew1,znew1);
s.FaceColor="yellow";
k=1;
[x,~,z] = sphere ; 
x0 =0.05*x;z0= 0.05*z-0.95; cenx=mean(mean(x0));cenz=mean(mean(z0));
r=arrayfun(@(x,z)imag(sqrt(0.95^2+0.05^2-2*(dot([cenx,cenz],[x,z])))),x0,z0); 
[ir,on,de] = sphere;
view(3)
f = getframe;
[im,map] = rgb2ind(f.cdata,256,'nodither');
im(1,1,1,2700) = 0;
for T = t
    xnew2=r*cos(10*T)*sin(-1.3*1.15^(-T)+1.3); 
    ynew2=r*sin(10*T)*sin(-1.3*1.15^(-T)+1.3); 
    znew2=r*cos(-1.3*1.15^(-T)+1.3);
    g=mean(mean(xnew2));
    ry=mean(mean(ynew2));
    s=mean(mean(znew2));
    ir2=0.05*ir-g;
    on2=0.05*on-ry;de2=0.05*de-s;
    h=surf(ir2,on2,de2);
    h.FaceColor="black";
    alpha 0.3;
    view(3)
    pause(dt(k));
    f = getframe;
    im(:,:,1,k) = rgb2ind(f.cdata,map,'nodither');
    delete(h)
    k=+1;
end
imwrite(im,map,'cyclotron.gif','DelayTime',0,'LoopCount',inf)
end

【问题讨论】:

    标签: matlab gif


    【解决方案1】:

    使用imwrite 函数创建动画GIF。动画 GIF 包含一系列图像,这些图像全部组合成一个文件。为此:

    1. 绘制一系列图

    2. 将它们捕获为图像

    3. 将它们写入 GIF 文件

    您当前的代码需要修改为:

    t=0:0.01:27;
    dt=[diff(t),eps];
    fig = figure; 
    hold on
    [x1,y1,z1] = sphere ;
    xnew1=x1;ynew1=y1;znew1= -abs(z1);
    s=surf(xnew1,ynew1,znew1);
    s.FaceColor="yellow";
    k=1;
    [x,~,z] = sphere ; 
    x0 =0.05*x;z0= 0.05*z-0.95; cenx=mean(mean(x0));cenz=mean(mean(z0));
    r=arrayfun(@(x,z)imag(sqrt(0.95^2+0.05^2-2*(dot([cenx,cenz],[x,z])))),x0,z0); 
    [ir,on,de] = sphere;
    view(3)
    
    % Capture the plot as an image 
    frame = getframe(fig);
    im = frame2im(frame);
    [imind,cm] = rgb2ind(im,256);
    
    % Write to the GIF File 
    imwrite(imind,cm,'test1.gif','gif', 'Loopcount',inf); 
    
    
    for T = t
        xnew2=r*cos(10*T)*sin(-1.3*1.15^(-T)+1.3); 
        ynew2=r*sin(10*T)*sin(-1.3*1.15^(-T)+1.3); 
        znew2=r*cos(-1.3*1.15^(-T)+1.3);
        g=mean(mean(xnew2));
        ry=mean(mean(ynew2));
        s=mean(mean(znew2));
        ir2=0.05*ir-g;
        on2=0.05*on-ry;de2=0.05*de-s;
        h=surf(ir2,on2,de2);
        h.FaceColor="black";
        alpha 0.3;
        view(3)
        pause(dt(k));
        % Capture the plot as an image 
        frame = getframe(fig);
        im = frame2im(frame);
        [imind,map] = rgb2ind(im,256);
        % Write to the GIF File 
        imwrite(imind,cm,filename,'gif','WriteMode','append'); 
        delete(h)
        k=+1;
    end
    

    【讨论】:

      猜你喜欢
      • 2016-05-12
      • 2017-03-08
      • 1970-01-01
      • 2014-12-01
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 2021-02-17
      相关资源
      最近更新 更多