Python利用matplotlib.animation和matplotlib.pyplot和ffmpeg录制动画并保存为MP4文件
生活随笔
收集整理的這篇文章主要介紹了
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文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ubuntu搜狗输入法, 输入中文时只显
- 下一篇: 素性测试的Miller-Rabin算法完