从python生成电影而不将单个帧保存到文件

时间:2010-11-04 00:30:21

标签: python numpy ffmpeg matplotlib x264

我想从我在matplotlib的python脚本中生成的帧创建一个h264或divx电影。这部电影大约有10万帧。

在网络上的例子中[例如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

[2] How does one encode a series of images into H264 using the x264 C API?

[3] http://www.ffmpeg.org/ffmpeg-doc.html#SEC41

6 个答案:

答案 0 :(得分:49)

此功能现在(至少从1.2.0开始,可能是1.1)通过MovieWriter类及其animation模块中的子类加入到matplotlib中。您还需要提前安装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

Documentation for animation

答案 1 :(得分:20)

在修补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')

如果没有patch,它将无法正常工作,{{3}}会轻易修改两个文件并添加libavcodec/png_parser.c。我必须手动将补丁应用到libavcodec/Makefile。最后,我从Makefile中删除了“-number”以获取构建的手册页。使用编译选项,

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

答案 2 :(得分:12)

转换为图像格式非常慢并且添加了依赖项。看完这些页面和其他后,我使用mencoder使用原始的未编码缓冲区工作(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()

我得到了一些不错的加速。

答案 3 :(得分:8)

这些都是非常好的答案。这是另一个建议。 @ user621442是正确的,瓶颈通常是图像的写入,因此如果您正在将png文件写入视频压缩器,它将非常慢(即使您通过管道而不是写入磁盘发送它们)。我找到了一个使用纯ffmpeg的解决方案,我个人觉得它比matplotlib.animation或mencoder更容易使用。

另外,在我的情况下,我想将图像保存在轴上,而不是保存所有刻度标签,图标题,图形背景等。基本上我想用matplotlib代码制作电影/动画,但没有它“看起来像一个图”。我在这里添加了that code,但如果你愿意的话,你可以制作标准图表并将它们传输到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()

答案 4 :(得分:5)

太好了!我也想这样做。但是,我永远无法使用MingW32 + MSYS +环境在Vista中编译修补的ffmpeg源(0.6.1)... png_parser.c在编译期间生成了Error1。

所以,我想出了一个使用PIL的jpeg解决方案。只需将您的ffmpeg.exe放在与此脚本相同的文件夹中即可。这应该适用于没有Windows下的补丁的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()

答案 5 :(得分:0)

这是@tacaswell答案的修改版本。修改了以下内容:

  1. 不需要pylab依赖项
  2. 固定几个位置此功能可直接运行。 (原始版本不能直接复制粘贴并运行,而必须修复多个位置。)

非常感谢@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