個々のフレームをファイルに保存せずにPythonから映画を生成する
-
28-09-2019 - |
質問
MatplotlibのPythonスクリプトで生成するフレームからH264またはDivx映画を作成したいと思います。この映画には約10万フレームがあります。
Web上の例[例: 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の時点で)Matplotlibに焼き付けられています。 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にパッチを適用した後(私の質問にジョーキントンのコメントを参照)、次のように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')
それなしでは機能しません パッチ, 、2つのファイルを簡単に変更して追加します libavcodec/png_parser.c
. 。パッチを手動で適用する必要がありました libavcodec/Makefile
. 。最後に、「-number」から削除しました Makefile
Manページを構築するために。コンパイルオプションで、
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ソリューションがまだ希望)を使用して、生の未確認のバッファーを使用して動作しました。
詳細: 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.AnimationまたはMencoderよりも個人的に使いやすいと感じています。
また、私の場合、私はすべてのティックラベル、フィギュアタイトル、フィギュアの背景などを保存する代わりに、画像を軸に保存したかっただけです。 「グラフのように見えます」。私は含めました そのコード ここでは、標準グラフを作成し、必要に応じて代わりに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 ... PNG_PARSER.Cを使用して、Vistaのパッチ付きFFMPEGソース(0.6.1)をコンパイル中にコンパイルすることはできませんでした。
それで、私はPILを使用してこれに対するJPEGソリューションを思いつきました。このスクリプトと同じフォルダーにffmpeg.exeを置くだけです。これは、Windowsの下のパッチなしでFFMPEGで動作するはずです。サブプロセスに関する公式ドキュメントで推奨される通信方法ではなく、stdin.writeメソッドを使用する必要がありました。 2番目の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