【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


相关推荐
杨荧33 分钟前
基于Python的电影评论数据分析系统 Python+Django+Vue.js
大数据·前端·vue.js·python
excel1 小时前
迭代器与生成器全面理解
前端
可口码农1 小时前
MixOne:Electron Remote模块的现代化继任者
java·前端·electron
发如雪-ty1 小时前
Bash常用操作总结
前端·chrome
冲!!1 小时前
使用nvm查看/安装node版本
前端·node.js·node·nvm
LilyCoder2 小时前
HTML5二十四节气网站源码
前端·javascript·html·html5
Bruce_Liuxiaowei2 小时前
跨站脚本攻击(XSS)高级绕过技术与防御方案
前端·网络安全·xss
EF@蛐蛐堂2 小时前
【vue3】v-model 的 “新玩法“
前端·javascript·vue.js
两个月菜鸟2 小时前
vue+微信小程序 五角星
前端·vue.js·微信小程序
GISer_Jing4 小时前
React手撕组件和Hooks总结
前端·react.js·前端框架