【matlab】生成 GIF 的函数(已封装可直接调用)


文章目录


前言

生成 gif 图片时遇到的问题,为了后续调用方便,封装为函数


一、函数输入与输出

  • 输入:
    • cell_figure: cell 数组,数组元素是活动窗口的结构体
      • 由 drawnow; F=getframe(gcf) 得到
    • name: string, 图片的名称
  • 输出
    • 无输出,生成一张名为 name 的 GIF 图像

二、函数代码

matlab 复制代码
%% write_gif() function,可以生成 GIF 的函数
%
% 输入参数:
%   input1: cell(struct), stru. describe the graph frame
%   input2: string, name of file
%
% 输出参数:
%   无输出,生成一个 GIF 图片


function write_gif(cell_figure, name)
    % init
    pic_num = 1;
    name = string(name); % be str

    for i = 1: length(cell_figure)
        graph_struct_i = cell_figure{i};
        
        % frame 2 image
        I=frame2im(graph_struct_i);
        [I,map]=rgb2ind(I,256);
    
        % 写入 gif 文件
        if pic_num == 1
            imwrite(I, map, name + '.gif', 'gif', 'Loopcount', inf, 'DelayTime', 0.2);
        else
            imwrite(I, map, name + '.gif', 'gif', 'WriteMode', 'append', 'DelayTime', 0.2);
        end
    
        % pic_num add
        pic_num = pic_num + 1;
    end
end

三、例程(可直接运行)

matlab 复制代码
clear; clc; close all;

%% create line

% init
cell_figure = {};

for i = 1:5
    
    % create fig
    fig = plot([i, 2 + i*2, -3 + i*3, 7 - i*4]);
    ylim([-20, 20])

    % draw & write cell
    drawnow;
    F=getframe(gcf);
    cell_figure{end+1} = F;

end

% invoke
write_gif(cell_figure, 'test_1')


%% write_gif() function,可以生成 GIF 的函数
%
% 输入参数:
%   input1: cell(struct), stru. describe the graph frame
%   input2: string, name of file
%
% 输出参数:
%   无输出,生成一个 GIF 图片


function write_gif(cell_figure, name)
    % init
    pic_num = 1;
    name = string(name); % be str

    for i = 1: length(cell_figure)
        graph_struct_i = cell_figure{i};
        
        % frame 2 image
        I=frame2im(graph_struct_i);
        [I,map]=rgb2ind(I,256);
    
        % 写入 gif 文件
        if pic_num == 1
            imwrite(I, map, name + '.gif', 'gif', 'Loopcount', inf, 'DelayTime', 0.2);
        else
            imwrite(I, map, name + '.gif', 'gif', 'WriteMode', 'append', 'DelayTime', 0.2);
        end
    
        % pic_num add
        pic_num = pic_num + 1;
    end
end
  • 输出结果

参考文献

1\] https://blog.csdn.net/lusongno1/article/details/78632457


相关推荐
bu_shuo18 小时前
启动Simulink的几种方法
matlab·simulink
ytttr87318 小时前
MATLAB的流体动力学与热传导模拟仿真实现
开发语言·matlab
zhuà!18 小时前
uv-picker在页面初始化时,设置初始值无效
前端·javascript·uv
Amumu1213818 小时前
React应用
前端·react.js·前端框架
码农学院18 小时前
使用腾讯翻译文本
服务器·数据库·c#
摸鱼的春哥18 小时前
实战:在 Docker (Windows) 中构建集成 yt-dlp 的“满血版” n8n 自动化工作流
前端·javascript·后端
小酒星小杜18 小时前
在AI时代,技术人应该每天都要花两小时来构建一个自身的构建系统
前端·vue.js·架构
测试游记18 小时前
基于 FastGPT 的 LangChain.js + RAG 系统实现
开发语言·前端·javascript·langchain·ecmascript
@zulnger19 小时前
正则表达式
数据库·正则表达式
阿奇__19 小时前
elementUI table 多列排序并保持状态样式显示正确(无需修改源码)
前端·vue.js·elementui