从Python生成电影,而无需将单个帧保存到文件
-
28-09-2019 - |
题
我想从Matplotlib中的Python脚本中创建的帧中创建H264或Divx电影。这部电影中大约有100k帧。
在网络上的示例中[例如。 1],我只看到将每个帧保存为PNG,然后在这些文件上运行mencoder或ffmpeg的方法。就我而言,保存每个帧是不切实际的。有没有办法将Matplotlib生成的图直接将其管道输送到FFMPEG,没有生成中间文件?
使用FFMPEG的C-API编程对我来说太难了[例如。 2]。另外,我需要一个具有良好压缩的编码,例如x264,因为电影文件对于后续步骤而言太大。因此,坚持使用Mencoder/ffmpeg/x264,这将是很棒的。
管道可以做些什么[3]?
[1] http://matplotlib.sourceforge.net/examples/animation/movie_demo.html
解决方案
现在,此功能是(至少在1.2.0,也许是1.1)通过 MovieWriter
班级,是子类 animation
模块。您还需要安装 ffmpeg
提前。
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
其他提示
在修补了FFMPEG之后(请参阅乔·金顿(Joe Kington)对我的问题的评论),我能够将管道PNG的ffmpeg送给:如下:
import subprocess
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
outf = 'test.avi'
rate = 1
cmdstring = ('local/bin/ffmpeg',
'-r', '%d' % rate,
'-f','image2pipe',
'-vcodec', 'png',
'-i', 'pipe:', outf
)
p = subprocess.Popen(cmdstring, stdin=subprocess.PIPE)
plt.figure()
frames = 10
for i in range(frames):
plt.imshow(np.random.randn(100,100))
plt.savefig(p.stdin, format='png')
没有 修补, ,它微不足道地修改了两个文件并添加 libavcodec/png_parser.c
. 。我不得不手动将补丁应用于 libavcodec/Makefile
. 。最后,我从 Makefile
为了让人页构建。使用编译选项,
FFmpeg version 0.6.1, Copyright (c) 2000-2010 the FFmpeg developers
built on Nov 30 2010 20:42:02 with gcc 4.2.1 (Apple Inc. build 5664)
configuration: --prefix=/Users/paul/local_test --enable-gpl --enable-postproc --enable-swscale --enable-libxvid --enable-libx264 --enable-nonfree --mandir=/Users/paul/local_test/share/man --enable-shared --enable-pthreads --disable-indevs --cc=/usr/bin/gcc-4.2 --arch=x86_64 --extra-cflags=-I/opt/local/include --extra-ldflags=-L/opt/local/lib
libavutil 50.15. 1 / 50.15. 1
libavcodec 52.72. 2 / 52.72. 2
libavformat 52.64. 2 / 52.64. 2
libavdevice 52. 2. 0 / 52. 2. 0
libswscale 0.11. 0 / 0.11. 0
libpostproc 51. 2. 0 / 51. 2. 0
转换为图像格式非常慢,并增加了依赖性。查看这些页面和其他页面后,我使用Mencoder(仍然想要FFMPEG解决方案)使用了未编码的缓冲液(仍然想要的FFMPEG解决方案)来工作。
详细信息: http://vokicodder.blogspot.com/2011/02/numpy-arrays-to-video.html
import subprocess
import numpy as np
class VideoSink(object) :
def __init__( self, size, filename="output", rate=10, byteorder="bgra" ) :
self.size = size
cmdstring = ('mencoder',
'/dev/stdin',
'-demuxer', 'rawvideo',
'-rawvideo', 'w=%i:h=%i'%size[::-1]+":fps=%i:format=%s"%(rate,byteorder),
'-o', filename+'.avi',
'-ovc', 'lavc',
)
self.p = subprocess.Popen(cmdstring, stdin=subprocess.PIPE, shell=False)
def run(self, image) :
assert image.shape == self.size
self.p.stdin.write(image.tostring())
def close(self) :
self.p.stdin.close()
我得到了一些不错的速度。
这些都是非常好的答案。这是另一个建议。 @user621442是正确的,瓶颈通常是图像的编写,因此,如果您将png文件写入视频压缩机,它也会很慢(即使您是通过管道发送而不是写入磁盘来发送它们)。我找到了使用纯FFMPEG的解决方案,我个人发现它比Matplotlib。动作或Mencoder更容易使用。
另外,就我而言,我只想将图像保存在轴上,而不是保存所有tick标签,图标题,图形背景等。基本上,我想使用matplotlib代码制作电影/动画,但没有它“看起来像图形”。我包括了 该代码 在这里,但是您可以制作标准图并将其输送到FFMPEG,如果需要的话。
import matplotlib.pyplot as plt
import subprocess
# create a figure window that is the exact size of the image
# 400x500 pixels in my case
# don't draw any axis stuff ... thanks to @Joe Kington for this trick
# https://stackoverflow.com/questions/14908576/how-to-remove-frame-from-matplotlib-pyplot-figure-vs-matplotlib-figure-frame
f = plt.figure(frameon=False, figsize=(4, 5), dpi=100)
canvas_width, canvas_height = f.canvas.get_width_height()
ax = f.add_axes([0, 0, 1, 1])
ax.axis('off')
def update(frame):
# your matplotlib code goes here
# Open an ffmpeg process
outf = 'ffmpeg.mp4'
cmdstring = ('ffmpeg',
'-y', '-r', '30', # overwrite, 30fps
'-s', '%dx%d' % (canvas_width, canvas_height), # size of image string
'-pix_fmt', 'argb', # format
'-f', 'rawvideo', '-i', '-', # tell ffmpeg to expect raw video from the pipe
'-vcodec', 'mpeg4', outf) # output encoding
p = subprocess.Popen(cmdstring, stdin=subprocess.PIPE)
# Draw 1000 frames and write to the pipe
for frame in range(1000):
# draw the frame
update(frame)
plt.draw()
# extract the image as an ARGB string
string = f.canvas.tostring_argb()
# write to pipe
p.stdin.write(string)
# Finish up
p.communicate()
这很棒!我想做同样的事情。但是,我永远无法用Mingw32+msys+PR Enviroment在Vista中编译经修补的FFMPEG源(0.6.1)... png_parser.c在编译过程中产生了错误1。
因此,我使用PIL提出了JPEG解决方案。只需将您的ffmpeg.exe放在与此脚本相同的文件夹中。这应该与ffmpeg一起使用,而无需窗口下的补丁。我必须使用stdin.write方法,而不是有关子过程的官方文档中建议的传达方法。请注意,第二-VCODEC选项指定编码编码器。管道由p.stdin.close()关闭。
import subprocess
import numpy as np
from PIL import Image
rate = 1
outf = 'test.avi'
cmdstring = ('ffmpeg.exe',
'-y',
'-r', '%d' % rate,
'-f','image2pipe',
'-vcodec', 'mjpeg',
'-i', 'pipe:',
'-vcodec', 'libxvid',
outf
)
p = subprocess.Popen(cmdstring, stdin=subprocess.PIPE, shell=False)
for i in range(10):
im = Image.fromarray(np.uint8(np.random.randn(100,100)))
p.stdin.write(im.tostring('jpeg','L'))
#p.communicate(im.tostring('jpeg','L'))
p.stdin.close()
这是@tacaswell答案的修改版。修改以下内容:
- 不需要
pylab
依赖性 - 修复多个位置ST此功能是直接运行的。 (原始的不能直接复制和播种,必须修复几个位置。)
非常感谢@tacaswell的出色答案!!!
def ani_frame():
def gen_frame():
return np.random.rand(300, 300)
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(gen_frame(), cmap='gray', interpolation='nearest')
im.set_clim([0, 1])
fig.set_size_inches([5, 5])
plt.tight_layout()
def update_img(n):
tmp = gen_frame()
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=72)
return ani