Rash
Rash

Reputation: 4336

Save animated warp as a GIF file in MATLAB

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

enter image description here

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,

enter image description here

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

Upvotes: 0

Views: 1337

Answers (1)

Ayb4btu
Ayb4btu

Reputation: 3378

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.

Upvotes: 1

Related Questions