【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


相关推荐
梦曦i10 小时前
@meng-xi/create-uni-app vs unibest:轻量脚手架与重型框架的定位之争
前端·uni-app
平头哥技术团队10 小时前
Day 10 | 工欲善其事:VS Code 配置与项目归档
android·开发语言·前端·javascript·html·交互
乌恩大侠10 小时前
GH200 新增 NVMe SSD 分区、格式化与挂载完整流程
运维·服务器·前端
yume_sibai11 小时前
Element Plus 数据展示组件完全指南(15个核心组件)
前端·javascript·vue.js
Mr.朱鹏11 小时前
Linux 服务器 LVM 根分区在线动态扩容
linux·服务器·数据库
摇滚侠11 小时前
《SpringBoot 3:入门与应用实战》第 12 章 JDBC 与事务 数据库初始化机制 阅读笔记 36
数据库·spring boot·笔记
qiuhaipeng111 小时前
Claude code 升级后上下文长度变短问题
java·前端·数据库
zzz_236811 小时前
个人 AI 记忆如何跨工具复用:用 Markdown、索引和 Skill 搭一个可治理的记忆库
前端·人工智能·react.js·前端框架·agent·agent测评
weixin_3077791311 小时前
一维无粘 Burgers 方程的激波形成问题:MacCormack 格式求解
c++·算法·matlab
wxwx_bscxy32212 小时前
基于Python新冠疫情可视化分析系统的设计与实现
java·数据库·spring boot·python·微信小程序·sqlite