我正在使用 ffmpeg 将视频转换为图像。这些图像然后由我的 Python 程序处理。本来我是用ffmpeg先把图片存到磁盘,然后用Python一张一张读取的。
这很好用,但为了加快程序速度,我试图跳过存储步骤,只处理内存中的图像。
我使用以下 ffmpeg 和 Python 子进程命令将输出从 ffmpeg 传输到 Python:
command = "ffmpeg.exe -i ADD\\sg1-original.mp4 -r 1 -f image2pipe pipe:1"
pipe = subprocess.Popen(ffmpeg-command, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
image = Image.new(pipe.communicate()[0])
然后我的程序就可以使用图像变量了。问题是,如果我从 ffmpeg 发送超过 1 张图像,所有数据都存储在这个变量中。我需要一种方法来分离图像。我能想到的唯一方法是在文件末尾 (0xff、0xd9) 的 jpeg 标记上拆分。这有效,但不可靠。
关于带有子进程的管道文件,我错过了什么。有没有办法一次只从管道读取一个文件?
请您参考如下方法:
一个解决方案是使用 ppm 格式,它具有可预测的大小:
ffmpeg -i movie.mp4 -r 1 -f image2pipe -vcodec ppm pipe:1
此处指定格式:http://netpbm.sourceforge.net/doc/ppm.html
看起来像这样:
P6 # magic number
640 480 # width height
255 # colors per channel
<data>
正好是 640 * 480 * 3 字节(假设每个 channel 有 255 种或更少的颜色)。
请注意,此 是一种未压缩格式,因此如果您一次性阅读它,它可能会占用相当多的内存。您可以考虑将算法切换为:
pipe = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, stderr=sys.stderr)
while True:
chunk = pipe.stdout.read(4096)
if not chunk:
break
# ... process chunk of data ...
注意子进程的stderr设置为当前进程的stderr;这很重要,因为如果我们不这样做,stderr 缓冲区可能会填满(因为没有任何内容在读取它)并导致死锁。
