Python利用matplotlib.animation和matplotlib.pyplot和ffmpeg录制动画并保存为MP4文件
因为需要将结果动画保存为MP4视频文件需要ffmepg软件的的支持。
一:安装ffmpeg软件: ffmpeg是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。采用LGPL或GPL许可证。它提供了录制、转换以及流化音视频的完整解决方案。下载网址为:https://ffmpeg.zeranoe.com/builds/。本实验下载的是windows 64位Static的版本,下载的压缩包为ffmpeg-20190407-ecdaa4b-win64-static.zip,解压,然后将bin目录加入系统环境变量的路径中,例如解压后bin目录为C:\ProgramFiles\ffmpeg-20190407-ecdaa4b-win64-static\bin。 最后,测试ffmpeg是否配置成功:打开Windows的cmd窗口,输入:ffmpeg -version。如果能看到如下ffmpeg关于软件版本的信息表示成功了。 ffmpeg version N-93542-gecdaa4b4fa Copyright (c) 2000-2019 the FFmpeg developersbuilt with gcc 8.2.1 (GCC) 20190212 configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libblu ray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable -libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --ena ble-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-l ibvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --e nable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable -libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enab le-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enab le-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --ena ble-dxva2 --enable-avisynth --enable-libopenmpt libavutil 56. 26.100 / 56. 26.100 libavcodec 58. 48.101 / 58. 48.101 libavformat 58. 27.100 / 58. 27.100 libavdevice 58. 7.100 / 58. 7.100 libavfilter 7. 48.100 / 7. 48.100 libswscale 5. 4.100 / 5. 4.100 libswresample 3. 4.100 / 3. 4.100 libpostproc 55. 4.100 / 55. 4.100
二、运行保存Python示例程序
示例程序一:正弦波动画
""" A simple example of an animated plot """ import numpy as np from matplotlib import pyplot as plt from matplotlib import animation# First set up the figure, the axis, and the plot element we want to animate fig = plt.figure() # create our line object which will be modified in the animation ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) # we simply plot an empty line: we'll add data to the line later line, = ax.plot([], [], lw=2)# initialization function: plot the background of each frame def init():line.set_data([], [])return line,# animation function. This is called sequentially # It takes a single parameter, the frame number i def animate(i):x = np.linspace(0, 2, 1000)y = np.sin(2 * np.pi * (x - 0.01 * i)) # update the dataline.set_data(x, y)return line,# Makes an animation by repeatedly calling a function func # frames can be a generator, an iterable, or a number of frames. # interval draws a new frame every interval milliseconds. # blit=True means only re-draw the parts that have changed. # 在这里设置一个200帧的动画,每帧之间间隔20毫秒 anim = animation.FuncAnimation(fig, animate, init_func=init,frames=200, interval=20, blit=True) # save the animation as an mp4. This requires ffmpeg or mencoder to be # installed. The extra_args ensure that the x264 codec is used, so that # the video can be embedded in html5. You may need to adjust this for # your system: for more information, see # http://matplotlib.sourceforge.net/api/animation_api.html #保存的动画视频文件名为当前文件夹下的basic_animation.mp4,帧率为30帧每秒,格式为MP4。 anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])plt.show() # plt.show() 会一直循环播放动画
示例程序2:贝叶斯曲线动画
import mathimport numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimationdef beta_pdf(x, a, b):return (x ** (a - 1) * (1 - x) ** (b - 1) * math.gamma(a + b)/ (math.gamma(a) * math.gamma(b)))class UpdateDist(object):def __init__(self, ax, prob=0.5):self.success = 0self.prob = probself.line, = ax.plot([], [], 'k-')self.x = np.linspace(0, 1, 200)self.ax = ax# Set up plot parametersself.ax.set_xlim(0, 1)self.ax.set_ylim(0, 15)self.ax.grid(True)# This vertical line represents the theoretical value, to# which the plotted distribution should converge.self.ax.axvline(prob, linestyle='--', color='black')def init(self):self.success = 0self.line.set_data([], [])return self.line,def __call__(self, i):# This way the plot can continuously run and we just keep# watching new realizations of the processif i == 0:return self.init()# Choose success based on exceed a threshold with a uniform pickif np.random.rand(1, ) < self.prob:self.success += 1y = beta_pdf(self.x, self.success + 1, (i - self.success) + 1)self.line.set_data(self.x, y)return self.line,# Fixing random state for reproducibility np.random.seed(19680801)fig, ax = plt.subplots() ud = UpdateDist(ax, prob=0.7) anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init,interval=5, blit=True) #保存动画视频文件名为当前文件夹下的bayes_animation.mp4,帧率为30帧每秒,格式为MP4。 anim.save('bayes_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264']) plt.show()三:运行程序并查看结果。 请注意,以上程序直接在Python的IDE环境中运行,例如PyCharm和Jupyter Notebook,运行可能报错或者只显示一张静态的空白图。 正确的方式是在Windows的cmd命令窗口下,执行命令:python 代码文件名.py。才能看到动态的结果,并且得到相应的MP4文件。
Python利用matplotlib.animation和matplotlib.pyplot和ffmpeg录制动画并保存为MP4文件相关推荐
- 用Python从wind获取数据,转换成dataframe格式,并保存成excel文件
import openpyxl from openpyxl.workbook import Workbook from WindPy import * from pandas import * imp ...
- python提取wind数据_用Python从wind获取数据,转换成dataframe格式,并保存为Excel文件,excel...
import openpyxl from openpyxl.workbook import Workbook from WindPy import * from pandas import * imp ...
- 减肥人士福利,用python的gevent模块queue方法爬取食物热量表并保存为excel文件
大家好,我是天空之城.今天给大家带来小福利 from bs4 import BeautifulSoup from gevent import monkey monkey.patch_all() imp ...
- Python使用openpyxl库操作Excel之(一)创建并保存一个Excel文件
①安装openpyxl库 打开cmd,输入 pip install openpyxl 命令即可. ②创建并保存一个Excel文件 import openpyxl #生成一个 Workbook 的实例化 ...
- python批量保存网页为pdf_爬取微信公众号文章并保存为PDF文件(Python方法)
{title} {content_info['content_html']}
- Python + matplotlib.animation 模拟斜抛运动动画(含完整代码)
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 Abstract Introduction Matplotlib.animation Physics model and C ...
- Python 动图、动画制作 —— moviepy、matplotlib.animation
进入命令行界面(windows ⇒ cmd),下载安装,pip install moviepy 0. figure 的成员函数 # 创建 figure fig, ax = plt.subplots() ...
- 【Matplotlib】matplotlib.animation.FuncAnimation绘制动态图、交互式绘图汇总(附官方文档)
文章目录 零.文中用到的相关知识: 一.以sin举例,motplotlib绘制动图 1.绘制sin函数 2.动态画出sin函数曲线 3.点在曲线上运动 4.点,坐标运动 二.单摆例子 1.scipy中 ...
- 用python画雨滴_Python使用Matplotlib实现雨点图动画效果的方法
本文实例讲述了Python使用Matplotlib实现雨点图动画效果的方法.分享给大家供大家参考,具体如下: 关键点 win10安装ffmpeg animation函数使用 update函数 win1 ...
最新文章
- iOS下拉tableView实现上面的图片放大效果
- react-router-dom v6 中的Routes
- 跟我学XSL(二) -XSL的运算符
- Java中对象的深克隆和浅克隆
- 如何从管理IT服务提供商获得最大收益
- synchronized 中的 4 个优化,你知道几个?
- 仅30分钟,在同一台设备安装discourse和wordpress
- q learning 参数_Soft Q-Learning论文阅读笔记
- android studio 新建工程慢,关于AndroidStudio新建与编译项目速度慢解决办法
- 【TensorFlow】TensorFlow函数精讲之 tf.random_normal()
- 关于计算机网络与应用的相关片,网络技术与应用作业.doc
- 数据分析学习笔记—python函数、异常与处理
- window一键清理垃圾代码
- 全流程东方时尚C1考试经历
- 笔记本无线共享上网(网络是有线)
- 攻防世界mfw_攻防世界-Web-mfw
- “鞋王”百丽国际牵手美云智数固筑业权一体管理 以数字化共创鞋履产业新未来
- 爬取拉钩Java招聘数据
- 了解如何定义定义变量和调用函数
- Logic Pro 使用教程之实时循环乐段(非常详细)