在 MATLAB 中将动画变形保存为 GIF 文件 [英] Save animated warp as a GIF file in MATLAB

查看:47
本文介绍了在 MATLAB 中将动画变形保存为 GIF 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于可以得到连锁反应了.我为它设置了动画并想将动画保存到 GIF 文件中.

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

但是我在 gif 文件中得到了一个固定的图像.

But I get a fixed image in the gif file.

动画在 MATLAB 中效果很好,但我不知道为什么它不会被保存.

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

问题 1 如何保存(或当前代码有什么问题)?

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

问题 2 如何以没有白色背景的方式保存?

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

(例如使用 view([0 45]) 和一点点缩放)

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

谢谢,

编辑感谢@Ayb4btu,我做了一些改进,

Edit Thanks to @Ayb4btu, I made some improvements,

但是使用 close all 会减慢速度,甚至有时 getframe 会捕获我的桌面!

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

推荐答案

出于某种原因, imwrite 不喜欢图形的更新方式.以下不雅代码的工作原理是关闭图形并绘制一个新图形:

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.

至于您的问题 2,此代码使用图形的背景颜色,但我相信 imwrite 具有您可以使用的颜色属性.

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.

这篇关于在 MATLAB 中将动画变形保存为 GIF 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆