2021-02-06 Python通过matplotlib包和gif包生成gif动画
Python通过matplotlib包和gif包生成gif动画
使用matplotlib
生成gif动画的方法有很多,一般常规使用matplotlib
的animation
模块的FuncAnimation
函数实现。在matplotlib
官网看到了第三方动画包gif
的介绍。
gif
包概述
gif
包是支持 Altair
, matplotlib
和Plotly
的动画扩展。
gif
依赖PIL
,即pillow
,要求Pillow>=7.1.2
。
安装gif
包,pip install gif
动画原理
所有动画
都是由帧(frame)
构成的,一帧就是一幅静止的画面,连续的帧就形成动画。我们通常说帧数,简单地说,就是在1秒钟时间里传输的图片的帧数,也可以理解为图形处理器每秒钟能够刷新几次,通常用fps(Frames Per Second)
表示。制作动画的关键:如何生成帧,每秒多少帧。
gif
包解读
gif
包非常简洁,只有一个单独的文件gif.py
,文件主要包含options
类、frames
和save
两个函数。
options
类
提供精简版 的Altair
, matplotlib
和Plotly
的保存或输出设置。以matplotlib
为例,提供以下设置。
dpi (int): The resolution in dots per inch
facecolor (colorspec): The facecolor of the figure
edgecolor (colorspec): The edgecolor of the figure
transparent (bool): If True, the axes patches will all be transparent
设置方法:gif.options.matplotlib["dpi"] = 300
原理:options
在构造函数中创建matplotlib
字典保存配置,随后传递给底层的matplotlib
包。
frames
函数
装饰器函数,通过对应包编写自定义绘图函数生成单帧图像。
save
函数
根据帧序列生成动画。
def save(frames, path, duration=100, unit="milliseconds", between="frames", loop=True):
"""Save decorated frames to an animated gif.
- frames (list): collection of frames built with the gif.frame decorator
- path (str): filename with relative/absolute path
- duration (int/float): time (with reference to unit and between)
- unit {"ms" or "milliseconds", "s" or "seconds"}: time unit value
- between {"frames", "startend"}: duration between "frames" or the entire gif ("startend")
- loop (bool): infinitely loop the animation
frames
即根据@gif.frame
装饰的绘图函数生成的帧的序列,此处根据需要自定义。
duration
即持续时间,由单位unit
和模式between
决定,默认为frames
为帧间的时间间隔。
unit
即持续时间单位,支持毫秒和秒,默认为毫秒。
between
即持续时间计算模式,默认frames
即duration
为帧之间的时间间隔,startend
模式时duration=duration /len(frames)
,即duration
为所有帧—整个动画的持续时间。
gif
包生成gif动画实践
import random
from matplotlib import pyplot as plt
import gif
# 构造数据
x = [random.randint(0, 100) for _ in range(100)]
y = [random.randint(0, 100) for _ in range(100)]
# 设置选项
gif.options.matplotlib["dpi"] = 300
# 使用gif.frame装饰器构造绘图函数,即如何生成静态的帧
@gif.frame
def plot(i):
xi = x[i * 10:(i + 1) * 10]
yi = y[i * 10:(i + 1) * 10]
plt.scatter(xi, yi)
plt.xlim((0, 100))
plt.ylim((0, 100))
# 构造帧序列frames,即把生成动画的所有帧按顺序放在列表中
frames = []
for i in range(10):
frame = plot(i)
frames.append(frame)
# 根据帧序列frames,动画持续时间duration,生成gif动画
gif.save(frames, 'example.gif', duration=3.5, unit="s", between="startend")
以心形曲线为例比较gif
包和animation
模块实现动画的差异
心形曲线绘制
from matplotlib import pyplot as plt
import numpy as np
t = np.linspace(0, 6, 100)
x = 16 * np.sin(t) ** 3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)
fig = plt.figure(figsize=(5, 3), dpi=100)
plt.scatter(x, y)
plt.show()
gif
包的实现方式
import numpy as np
import gif
from matplotlib import pyplot as plt
t = np.linspace(0, 6, 100)
x = 16 * np.sin(t) ** 3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)
@gif.frame
def plot_love(x, y):
plt.figure(figsize=(5, 3), dpi=100)
plt.scatter(x, y, 60, c="r", alpha=0.7, marker=r"$\heartsuit$")
plt.axis("off")
frames = []
for i in range(1, len(x)):
of = plot_love(x[:i], y[:i])
frames.append(of)
gif.save(frames, "love.gif", duration=80)
matplotlib
常规FuncAnimation
函数实现方式
from matplotlib import pyplot as plt
import matplotlib.animation as animation
import numpy as np
t = np.linspace(0, 6, 100)
x = 16 * np.sin(t) ** 3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)
data=[i for i in zip(x,y)]
def plot_love(data):
x, y = data
plt.scatter(x, y, 60, c="r", alpha=0.7, marker=r"$\heartsuit$")
fig=plt.figure(figsize=(5, 3), dpi=100)
plt.axis("off")
animator = animation.FuncAnimation(fig, plot_love, frames=data, interval=80)
animator.save("love.gif", writer='pillow')
matplotlib
底层PillowWriter
类实现方式
from matplotlib import pyplot as plt
import matplotlib.animation as animation
import numpy as np
t = np.linspace(0, 6, 100)
x = 16 * np.sin(t) ** 3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)
def plot_love(x, y):
plt.scatter(x, y, 60, c="r", alpha=0.7, marker=r"$\heartsuit$")
fig = plt.figure(figsize=(5, 3), dpi=100)
plt.axis("off")
writer = animation.PillowWriter(fps=15)
with writer.saving(fig, "love21.gif", dpi=100):
for i in range(1, len(x)):
plot_love(x[i], y[i])
writer.grab_frame()
通过比较可知gif
包的实现方式和matplotlib
中利用PillowWriter
实现方式类似,更偏底层一些,这样遇到比较复杂的绘图时更灵活。
2021-02-06 Python通过matplotlib包和gif包生成gif动画相关推荐
- python gif_python 将png图片格式转换生成gif动画
先看知乎上面的一个连接 用Python写过哪些[脑洞大开]的小工具? 这个哥们通过爬气象网站的气象雷达图,生成一个gif的动态图.非常有趣且很实用,那咱也实现下. 我们先实现一个从GIF提取帧的代码 ...
- 06 Python numpy matplotlib 绘制立体玫瑰花
七夕就要来了,不论你是不是一个人,都祝你开学快乐~~~ 可自定义输入内容 代码: """ * @Author: xiaofang """ i ...
- Go语言的当前状态(2021) | Gopher Daily (2021.02.07) ʕ◔ϖ◔ʔ
每日一谚:Don't ignore errors in test code. When something unexpected happens, it'll fail silently and yo ...
- linux python matplotlib 使用,关于Linux:如何在Python的matplotlib中设置“后端”?
我是matplotlib的新用户,我的平台是Ubuntu 10.04 Python 2.6.5 这是我的代码 import matplotlib matplotlib.use('Agg') impor ...
- Py之matplotlib:python包之matplotlib库图表绘制包的简介、安装、使用方法(matplotlib颜色大全)详细攻略
Py之matplotlib:python包之matplotlib库图表绘制包的简介.安装.使用方法(matplotlib颜色大全)详细攻略 目录 matplotlib简介 matplotlib安装 m ...
- 断网python第三方库安装_Python离线断网情况下安装numpy、pandas和matplotlib等常用第三方包...
联网情况下在命令终端CMD中输入"pip install numpy"即可自动安装,pandas和matplotlib同理一样方法进行自动安装. 工作的电脑不能上外网,所以不能通过 ...
- JAVA三维可视化组件:Matplot 3D for JAVA(V3.0) 一个纯JAVA开发的科学数据可视化组件包 类似 Python 的matplotlib(含示例代码)
目录 概述 组件下载及项目地址 效果展示和示例代码 概述 Matplot3D for JAVA(V3.0) 是一个基于JAVA SE 1.8环境开发的三维图形图表组件. 组件由纯JAVA SE 实现( ...
- 【愚公系列】2021年12月 Python教学课程 17-模块与包
文章目录 一. 什么是模块 二. 模块的使用 1. import xx.xx 2. from xx.xx import xx.xx 3. from xx.xx import xx as rename ...
- python获取matplotlib、tensorflow、pandas、numpy等的版本version
python获取matplotlib.tensorflow.pandas.numpy的版本version python包.库之间会发生版本冲突.那么你就需要查明版本,然后确定是降级还是升级: 使用__ ...
最新文章
- 软件架构师证书有用吗_健康管理师证书在求职时有用吗?
- JavaScript arguments对象
- GDB 格式化结构体输出
- Python性能分析指南——中
- 无需用户输入!Adobe提出自动生成高质量合成图像新方法
- mybaitis 通过Mapping 实现多表查询
- 可视化界面编程idea_BAT 的程序员用了这些 IDEA 插件, 志玲姐姐天天鼓励, 工作效率提高 320%...
- ADO.NET、ODP.NET、Linq to SQL、ADO.NET Entity 、NHibernate在Oracle下的性能比较
- 【Oracle学习笔记】常用知识梳理
- 不止 JavaScript 与 React,前端程序员必备的 9 大技能!
- 解决安装office2007的各种工具时提示“安装程序找不到office.zh-cn/*”的问题
- 系统的x86与x64是什么意思以及他们的区别?
- Sql中的left函数、right函数
- Elasticsearch 聚合搜索技术深入
- UEFI 是什么?硬盘的EFI分区? .efi格式的文件?UEFI 标准定义了一种可执行文件格式:efi格式
- 折腾安装archlinx记录
- javascript案例16——判断输入的年份是否是闰年、判断闰年
- 为什么web网页会被劫持,网页被劫持的解决方法有哪些?
- 没有权限访问网络资源/Windows7虚拟机共享文件
- 客户端解析html5,基于HTML5的WebGIS实时客户端设计
热门文章
- 机器学习算法与Python实践之(二)支持向量机(SVM)初
- tf_geometric的安装
- 小白入门深度学习 | 第三篇:30分钟入门深度学习 - TensorFlow版
- 【Python刷题】_3
- QCustomplot设置背景为透明色
- 【机器学习算法-python实现】Adaboost的实现(1)-单层决策树(decision stump)
- Solr -- query和filter query
- 从0开始构建你的api网关--Spring Cloud Gateway网关实战及原理解析
- Docker源码分析(四):Docker Daemon之NewDaemon实现
- 1号店11.11:从应用架构落地点谈高可用高并发高性能--转载