从 python 生成电影而不将单个帧保存到文件 [英] Generating movie from python without saving individual frames to files
问题描述
我想从我在 matplotlib 中的 Python 脚本中生成的帧创建 h264 或 divx 电影.这部电影大约有 10 万帧.
I would like to create an h264 or divx movie from frames that I generate in a python script in matplotlib. There are about 100k frames in this movie.
在网络上的例子中[例如.1],我只见过将每一帧保存为png然后在这些文件上运行mencoder或ffmpeg的方法.就我而言,保存每一帧是不切实际的.有没有办法获取从 matplotlib 生成的图并将其直接通过管道传输到 ffmpeg,而不生成中间文件?
In examples on the web [eg. 1], I have only seen the method of saving each frame as a png and then running mencoder or ffmpeg on these files. In my case, saving each frame is impractical. Is there a way to take a plot generated from matplotlib and pipe it directly to ffmpeg, generating no intermediate files?
使用 ffmpeg 的 C-api 编程对我来说太难了 [例如.2].此外,我需要一个具有良好压缩的编码,例如 x264,否则电影文件对于后续步骤来说太大了.所以坚持使用 mencoder/ffmpeg/x264 会很棒.
Programming with ffmpeg's C-api is too difficult for me [eg. 2]. Also, I need an encoding that has good compression such as x264 as the movie file will otherwise be too large for a subsequent step. So it would be great to stick with mencoder/ffmpeg/x264.
有什么可以用管道做的事情[3]吗?
Is there something that can be done with pipes [3]?
[1] http://matplotlib.sourceforge.net/examples/animation/movie_demo.html
[2] 如何使用 x264 C API 将一系列图像编码为 H264?
[3] http://www.ffmpeg.org/ffmpeg-doc.html#SEC41
推荐答案
这个功能现在(至少从 1.2.0 开始,也许是 1.1)通过 MovieWriter
类被烘焙到 matplotlib 中,它是子- animation
模块中的类.您还需要提前安装ffmpeg
.
This functionality is now (at least as of 1.2.0, maybe 1.1) baked into matplotlib via the MovieWriter
class and it's sub-classes in the animation
module. You also need to install ffmpeg
in advance.
import matplotlib.animation as animation
import numpy as np
from pylab import *
dpi = 100
def ani_frame():
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_aspect('equal')
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
im = ax.imshow(rand(300,300),cmap='gray',interpolation='nearest')
im.set_clim([0,1])
fig.set_size_inches([5,5])
tight_layout()
def update_img(n):
tmp = rand(300,300)
im.set_data(tmp)
return im
#legend(loc=0)
ani = animation.FuncAnimation(fig,update_img,300,interval=30)
writer = animation.writers['ffmpeg'](fps=30)
ani.save('demo.mp4',writer=writer,dpi=dpi)
return ani
这篇关于从 python 生成电影而不将单个帧保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!