Save animated warp as a GIF file in MATLAB

て烟熏妆下的殇ゞ 提交于 2019-12-12 06:36:44

问题


I could finally manage to get ripple effect. I animated it and want to save the animation to a GIF file.

But I get a fixed image in the gif file.

The animation works great in MATLAB but I don't know why it won't get saved.

im = imread('peppers.png'); 
[m,n,~] = size(im);
n = linspace(-4 * pi,4 * pi,n);
m = linspace(-4 * pi,4 * pi,m);
[X,Y] = meshgrid(m,n);
d = (X .^ 2 + Y .^ 2) .^ .5;
d = d / max(d(:));
d = (d - .5) * 2 * pi;
j = 1;
figure(1);
for i = 0 : .2 : 2 * pi
    Z = cos(2 * d + i) .* exp(-.01 .* d);
    h = warp(X,Y,Z,im);
    axis equal; axis off;
    f = getframe;
    [I,~] = frame2im(f);
    [I,cm] = rgb2ind(I,256);
    if j == 1
        imwrite(I,cm,'B.gif','gif', 'Loopcount',inf);
    else
        imwrite(I,'B.gif','gif','WriteMode','append','DelayTime',1/24);
    end
    j = 0;
end

Question 1 How can I save it (or what is the problem with current code)?

Question 2 How can I save it in a way that there is no white background ?

(for example with view([0 45]) and a little zoom)

Thanks,

Edit Thanks to @Ayb4btu, I made some improvements,

However using close all slows thing down, even sometimes getframe captures my desktop!


回答1:


For some reason the imwrite doesn't like how the figure is being updated. The following inelegant code works by closing the figure and drawing a new one:

clear all, close all, clc

I = imread('peppers.png'); 
[m,n] = size(I);
n = linspace(-4 * pi,4 * pi,n);
m = linspace(-4 * pi,4 * pi,m);
[X,Y] = meshgrid(m,n);
d = (X .^ 2 + Y .^ 2) .^ .5;
d = d / max(d(:));
d = (d - .5) * 2 * pi;
j = 1;

for p = 0 : .2 : 4 * pi
    figure(1)
    Z = cos(2 * d + p) .* exp(-.01 .* d);
    h = warp(X,Y,Z,I);
    axis equal; axis off;   

    frame = getframe(1);
    im = frame2im(frame);
    [A,map] = rgb2ind(im,256);

    if j == 1
        imwrite(A,map,'B.gif','gif', 'Loopcount',Inf,'DelayTime',1/24);
    else
        imwrite(A,map,'B.gif','gif','WriteMode','append','DelayTime',1/24);
    end

    j = 0;
    close all
end

Use this as a basis and you might be able to figure out where the problem lies.

As for your question 2, this code uses the background color of the figure, though I believe imwrite has a color property that you can play with.



来源:https://stackoverflow.com/questions/27056373/save-animated-warp-as-a-gif-file-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!