【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


相关推荐
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
ew452182 小时前
ElementUI表格表头自定义添加checkbox,点击选中样式不生效
前端·javascript·elementui
suibian52352 小时前
AI时代:前端开发的职业发展路径拓宽
前端·人工智能
Moon.92 小时前
el-table的hasChildren不生效?子级没数据还显示箭头号?树形数据无法展开和收缩
前端·vue.js·html
垚垚 Securify 前沿站2 小时前
深入了解 AppScan 工具的使用:筑牢 Web 应用安全防线
运维·前端·网络·安全·web安全·系统安全
工业甲酰苯胺5 小时前
Vue3 基础概念与环境搭建
前端·javascript·vue.js
IT古董6 小时前
【开源向量数据库】Milvus简介
数据库·开源·milvus
mosquito_lover16 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt
web150850966416 小时前
SQL 建表语句详解
java·数据库·sql
宇智波云7 小时前
mysql增加字段操作以及关键字报错
java·数据库·mysql