FuncAnimation类

class matplotlib.animation.FuncAnimation(

fig, func, frames=None, init_func=None,

fargs=None, save_count=None, **kwargs)

参数

fig : matplotlib.figure.Figure对象,可以理解为画布

func : 函数(callable),每一帧被调用一次

函数签名大概是这样的:def func(frame, *fargs) -> iterable_of_artists

第一个参数是frames中的元素,第二个是fargs参数设置的附件参数

返回值是可迭代的图形对象

frames : 可迭代对象, 整数, 生成函数或者None,传递给动画函数func的帧

如果是可迭代对象,可迭代对象的长度将覆盖save_count参数

如果是个整数,值就是range(frames)

如果是生成函数,签名必须是def gen_function() -> obj:

如果是None,frames=itertools.count,相当于整数从0开始步长1无限迭代

init_func : 函数(callable)

用来画一个完整的帧,如果没有给,使用的是frames中的第一个元素,在第一帧之前被调用

如果If blit == True, init_func 必须返回一个可迭代的图形对象

签名像:def init_func() -> iterable_of_artists:

fargs : 元组或None,每一次调用func的附加参数

save_count : 整数,缓存的帧的数量

interval : number, 2帧之间的延迟,默认200毫秒

repeat_delay : number, 重复延迟,默认None

repeat : bool, 是否重复,默认True

blit : bool, 是否使用blitting优化,默认False

blitting的含义是内存中图像的位块传输,指的是将某一表面的全部或部分图像复制到另一表面上

动图存储配置

# print matplotlib.matplotlib_fname()

# matplotlib\mpl-data\matplotlibrc

animation.writer : ffmpeg ## MovieWriter 使用

animation.ffmpeg_path: ffmpeg ## 可执行文件ffmpeg路径,会搜索$PATH

animation.convert_path: magick ## 可执行文件magick路径,会搜索$PATH

animation.convert_args: convert ## 执行magick的附件参数,因为新ImageMagick的没有convert命令了,所以使用的是convert参数

要保存动图和视频需要使用ImageMagick,后面有下载链接,下载安装之后的目录大概如下:

下载页面:

sin实例

# -*- coding:utf-8 -*-

import numpy as np

from matplotlib import pyplot as plt

from matplotlib import animation

import matplotlib

# print matplotlib.matplotlib_fname()

fig = plt.figure()

ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))

line, = ax.plot([], [], lw=2)

def init():

line.set_data([], [])

return line,

def animate(i):

#linespace(起始值(start),终止值(stop),数量(num)=50,是否包含终止值(endpoint)=True,是否返回步长(retstep)=False,数据类型(dtype)=None)

x = np.linspace(0, 2, 1000)

y = np.sin(2 * np.pi * (x - 0.01 * i))

line.set_data(x, y)

return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,frames=200, interval=20, blit=True)

anim.save('sin.gif', fps=75, writer='imagemagick')

plt.show()

circle实例

# -*- coding:utf-8 -*-

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.animation as animation

import matplotlib.path as mpath

import matplotlib.patches as mpatch

from matplotlib.patches import Circle

import random

fig,ax = plt.subplots()

ax.set_xticks([])

ax.set_yticks([])

ax.spines["left"].set_color("none")

ax.spines["top"].set_color("none")

ax.spines["right"].set_color("none")

ax.spines["bottom"].set_color("none")

ax.axis([-5,5,-5,5])

# ax.add_patch(mpatch.PathPatch(mpath.Path.circle()))

circle = Circle(xy = (0.0, 0.0), radius=0.5, alpha=0.5)

ax.add_patch(circle)

def init():

return Circle(xy = (0.0, 0.0), radius=0.5, alpha=0.5),

def animate(i):

circle.set_radius(i*0.5)

circle.set_facecolor(random.choice("rmcky"))

return circle,

# fig = plt.gcf()

# fg = range(1,11)

# fgr = range(1,11)

# fgr.reverse()

# fs = fg + fgr

fs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

ani = animation.FuncAnimation(fig, animate, init_func=init,frames=fs,interval=1000, blit=True)

# ani = animation.FuncAnimation(fig, animate, frames=360, init_func=init, interval=0.1, blit=True, save_count=50)

# ani = animation.FuncAnimation(fig, animate, frames=10, init_func=init, interval=0.1, blit=True, save_count=50,repeat=False)

ani.save('circle.gif', fps=2, writer='imagemagick')

plt.show()

rain实例

# -*- coding:utf-8 -*-

import numpy as np

import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation

# Fixing random state for reproducibility

np.random.seed(19680801)

# Create new Figure and an Axes which fills it.

fig = plt.figure(figsize=(7, 7))

ax = fig.add_axes([0, 0, 1, 1], frameon=False)

ax.set_xlim(0, 1), ax.set_xticks([])

ax.set_ylim(0, 1), ax.set_yticks([])

# Create rain data

n_drops = 50

rain_drops = np.zeros(n_drops, dtype=[('position', float, 2),

('size', float, 1),

('growth', float, 1),

('color', float, 4)])

# Initialize the raindrops in random positions and with

# random growth rates.

rain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))

rain_drops['growth'] = np.random.uniform(50, 200, n_drops)

# Construct the scatter which we will update during animation

# as the raindrops develop.

scat = ax.scatter(rain_drops['position'][:, 0], rain_drops['position'][:, 1],

s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],

facecolors='none')

def update(frame_number):

# Get an index which we can use to re-spawn the oldest raindrop.

current_index = frame_number % n_drops

# Make all colors more transparent as time progresses.

rain_drops['color'][:, 3] -= 1.0/len(rain_drops)

rain_drops['color'][:, 3] = np.clip(rain_drops['color'][:, 3], 0, 1)

# Make all circles bigger.

rain_drops['size'] += rain_drops['growth']

# Pick a new position for oldest rain drop, resetting its size,

# color and growth factor.

rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)

rain_drops['size'][current_index] = 5

rain_drops['color'][current_index] = (0, 0, 0, 1)

rain_drops['growth'][current_index] = np.random.uniform(50, 200)

# Update the scatter collection, with the new colors, sizes and positions.

scat.set_edgecolors(rain_drops['color'])

scat.set_sizes(rain_drops['size'])

scat.set_offsets(rain_drops['position'])

# Construct the animation, using the update function as the animation director.

animation = FuncAnimation(fig, update, interval=10)

animation.save('rain.gif', fps=75, writer='imagemagick')

plt.show()

保存为mp4

# -*- coding:utf-8 -*-

import numpy as np

import matplotlib

matplotlib.use("Agg")

import matplotlib.pyplot as plt

from matplotlib.animation import FFMpegWriter

# Fixing random state for reproducibility

np.random.seed(19680801)

metadata = dict(title='Movie Test', artist='Matplotlib',comment='Movie support!')

writer = FFMpegWriter(fps=15, metadata=metadata)

fig = plt.figure()

l, = plt.plot([], [], 'k-o')

plt.xlim(-5, 5)

plt.ylim(-5, 5)

x0, y0 = 0, 0

with writer.saving(fig, "writer_test.mp4", 100):

for i in range(100):

x0 += 0.1 * np.random.randn()

y0 += 0.1 * np.random.randn()

l.set_data(x0, y0)

writer.grab_frame()

画心型mp4

# -*- coding:utf-8 -*-

import numpy as np

import matplotlib

matplotlib.use("Agg")

import matplotlib.pyplot as plt

from matplotlib.animation import FFMpegWriter

import math

metadata = dict(title='heart', artist='Matplotlib',comment='draw heart')

writer = FFMpegWriter(fps=15, metadata=metadata)

figure = plt.figure()

axes = plt.gca()

axes.set_xticks([])

axes.set_yticks([])

axes.spines["left"].set_color("none")

axes.spines["top"].set_color("none")

axes.spines["right"].set_color("none")

axes.spines["bottom"].set_color("none")

line1, = axes.plot([], [], color='red', linewidth=2,)

line2, = axes.plot([], [], color='red', linewidth=2,)

plt.xlim(-5, 5)

plt.ylim(-5, 5)

x0, y0 = 0, 0

with writer.saving(figure, "heart.mp4", 100):

for i in range(15):

t = np.linspace(0, i/math.pi, 100)

x = np.sin(t)

y = np.cos(t) + np.power(x, 2.0/3)

line1.set_data(x, y)

line2.set_data(-x, y)

writer.grab_frame()

视频没有办法上传,如果感兴趣可以自己尝试一下。

参考

python动图存储为视频_matplotlib动态图和视频保存相关推荐

  1. python怎么存为动图_Python将视频或者动态图gif逐帧保存为图片的方法

    本文是基于opencv将视频和动态图gif保存为图像帧.可以根据输入视频格式的不同,修改第21行. 对动图的处理不同于视频,PIL库包含对图像序列的基本支持.当打开gif图像时,自动加载第一帧.当图像 ...

  2. 怎么把动态图从python弄下来_Python将视频或者动态图gif逐帧保存为图片的方法

    本文是基于opencv将视频和动态图gif保存为图像帧.可以根据输入视频格式的不同,修改第21行. 对动图的处理不同于视频,PIL库包含对图像序列的基本支持.当打开gif图像时,自动加载第一帧.当图像 ...

  3. Python将视频或者动态图gif逐帧保存为图片

    本文是基于opencv将视频和动态图gif保存为图像帧.可以根据输入视频格式的不同,修改第21行. 对动图的处理不同于视频,PIL库包含对图像序列的基本支持.当打开gif图像时,自动加载第一帧.当图像 ...

  4. 关于在python的tkinter界面中镶嵌mayplotlib动态图

    关于在python的tkinter界面中镶嵌mayplotlib动态图 很多的时候,我们需要给客户展示一些比较美观的界面,中间就必然需要一些精美的图表,让客户看起来更加的专业,因此,我们就需要tkin ...

  5. python实现新冠疫情各国人数动态图

    python实现新冠疫情各国人数动态图 文章目录 python实现新冠疫情各国人数动态图 前言效果 一.代码 1.建立好我们的数据 总结 前言效果 今天用python实现新冠疫情各国人数动态图 一.代 ...

  6. DL之CNN:卷积神经网络算法简介之原理简介(步幅/填充/特征图)、七大层级结构(动态图详解卷积/池化+方块法理解卷积运算)、CNN各层作用及其可视化等之详细攻略

    DL之CNN:卷积神经网络算法简介之原理简介(步幅/填充/特征图).七大层级结构(动态图详解卷积/池化+方块法理解卷积运算).CNN各层作用及其可视化等之详细攻略 目录 CNN 的层级结构及相关概念 ...

  7. python合成gif动图_Python图像处理之gif动态图的解析与合成操作详解

    本文实例讲述了Python图像处理之gif动态图的解析与合成操作.分享给大家供大家参考,具体如下: gif动态图是在现在已经司空见惯,朋友圈里也经常是一言不合就斗图.这里,就介绍下如何使用python ...

  8. 哪个相机可以拍gif动图_直接拍出GIF动态图的相机

    原标题:直接拍出GIF动态图的相机 GIF格式动态图片其实现在已经有超过27年的历史了,不过时至今日它依然还在发挥着自己的魔力.制作GIF动画的方法有很多,但你有没有想过用照相机直接拍出GIF动画?这 ...

  9. ffmpeg视频截取动态图

    ffmpeg -y -ss 00:00:10.000 -i input.mp4 -pix_fmt rgb24 -r 7 -s 750*420 -t 00:00:7.000 -vf "tran ...

最新文章

  1. pythonbool运算教学_python,_pandas Series bool与运算,python - phpStudy
  2. ASP.NET MVC Framework体验(2):显示列表数据
  3. html地图周边搜索,html5 百度地图定位关键字搜索附近
  4. Promise对象的创建与使用
  5. EZ的间谍网络(codevs 4093)
  6. 收集10个顶级的CSS3代码生成器
  7. BCVP开发者社区2022专属周边第一弹
  8. [蓝桥杯][算法提高VIP]数的划分-dp
  9. Java学习笔记之:Java String类
  10. 删除对象键值_JavaScript的解构技巧:排除对象属性、避免命名冲突、交换……...
  11. 使用Android简单实现有道电子词典
  12. java新手笔记6 示例for
  13. IIS 7.5学习笔记(二)IIS简史:从IIS 1.0到IIS 7.5
  14. linux系统新磁盘可视化挂载方法
  15. 网络靶场攻防综合实验
  16. 天马行空脚踏实地,阿里巴巴有群百里挑一的天才应届生...
  17. linaro 网站资源
  18. 内部收益率计算公式用计算机,用EXCEL计算财务内部收益率
  19. 朋友圈一杠中间一个点_朋友圈看到这条线,大概率是被删了
  20. SpringBoot基础学习之SpringBoot配置(上篇)

热门文章

  1. 写了个“开始充电就 Xxx 的功能”,结果测试把充电口拔坏了~
  2. 代码备份20190123
  3. 把电脑Matlab的内容移到iPad,如何借助“随航”功能将电脑画面转移至 iPad?
  4. 对import与require用法
  5. 用“生物进化论”来阐述“恶意代码进化论”
  6. linux系统怎么禁用键盘,桌面应用|如何在 Linux 下锁住键盘和鼠标而不锁屏
  7. 地下城与勇士(DNF)月轮山副本(纳特拉的复仇、双子巨人的背叛、圣地:龙之魂)
  8. Day3-水仙花和三种循环
  9. 泛微移动平台火热体验 第19届软博会获领先企业奖
  10. 【2020 ACM Fellow 华人学者】 Wang Yi 乌普萨拉大学