使用matlab制作gif动图

目的:便于演示学术研究中仿真结果(以Fourier变换仿真图为例)

工具:Matlab

%% Define waveform properties
f = 1;          % Frequency (Hz)
t = 0:.001:2;   % Eval time (s)
Y_Fourier = zeros(size(t)); % Preallocate
 
%% Generate the frames
for k = 1:20;
    Y_Fourier = (4/pi)*sin(2*pi*(2*k-1)*f*t)/(2*k-1) + Y_Fourier;
    if k == 1
        % Only create the plot for 1st iteration, update wave for
        % subsequent
        figure();
        hold('on'); grid('on');
        ylim([-1.5 1.5]);
        set(gca, 'xtick', 0:0.5:2);
        h1 = plot(t, square(t*2*pi), 'LineWidth', 2);
        h2 = plot(t,Y_Fourier, 'LineWidth', 2);
        legend('Square Wave (1 Hz)', 'Fourier Approximation');
        xlabel('Time (s)');
        ylabel('Amplitude');
    else
        % Update y data
        set(h2, 'ydata', Y_Fourier)
    end
    title(['k = ' num2str(k)]);
    % Save as png with a resolution of 150 pixels per inch
    print(['Frame ' num2str(k)], '-dpng', '-r150');
end
 
%% Now time to generate the animated gif
GifName = 'SquareWaveAnimation.gif';
delay = 0.5;    % Delay between frames (s)
for ii = 1:20
    [A, ~] = imread(['Frame ' num2str(ii) '.png']);
    [X, map] = rgb2ind(A, 256);
    if ii == 1
        imwrite(X, map, GifName, 'gif', 'LoopCount', inf, 'DelayTime', delay)
    else
        imwrite(X, map, GifName, 'gif', 'WriteMode', 'append', 'DelayTime', delay)
    end
end

1.定义参数

2.产生视频帧

3.合成动图

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MATLAB制作GIF动态图通常涉及到使用imwrite和imread函数以及pause或waitforbuttonpress等暂停命令来逐帧保存和显示图像。以下是一个简单的步骤指南: 1. **创建或读取图像序列**: - 使用`imread`读取单张图片,或者创建多张图片数组。 - 如果需要自动生成动画,可以用for循环或cell数组生成一系列图片。 ```matlab frames = {}; % 创建一个空cell数组存储帧 for i = 1:total_frames % 假设你有一个名为'frame_'与帧数相关的文件名列表 frame = imread('frame_' + num2str(i) + '.jpg'); % 替换为你的文件路径 frames{i} = frame; % 将帧添加到cell数组 end ``` 2. **保存每一帧**: - 使用`imwrite`保存每帧为临时文件,例如`.png`,因为MATLAB的内建功能不直接支持GIF格式。 ```matlab % 假定临时目录为'temp_dir' temp_dir = 'temp_dir'; if ~exist(temp_dir, 'dir') mkdir(temp_dir); end for i = 1:length(frames) filename = fullfile(temp_dir, ['frame' num2str(i) '.png']); imwrite(frames{i}, filename); end ``` 3. **合并为GIF**: - 使用系统调用或者外部工具(如ImageMagick)将PNG帧转换为GIFMATLAB不直接支持这个操作。 ```matlab % 假定系统路径下有convert工具 [status, result] = system(['convert -delay 10 ' temp_dir '/*.png ' temp_dir '/animation.gif']); % 延迟时间10毫秒,替换为实际延迟值 if status ~= 0 error('Error converting to GIF'); end ``` 4. **清理临时文件**: - 完成GIF制作后,如果需要,删除临时PNG文件。 ```matlab files_to_delete = fullfile(temp_dir, 'frame_*.png'); delete(files_to_delete); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值