将 PIL 图像通过管道传输到 ffmpeg 标准输入 - Python

Pipe PIL images to ffmpeg stdin - Python

我正在尝试将 html5 视频转换为 mp4 视频,并且随着时间的推移通过 PhantomJS 进行屏幕拍摄来做到这一点

我也在使用 PIL 裁剪图像,所以最终我的代码大致是:

while time() < end_time:
    screenshot_list.append(phantom.get_screenshot_as_base64())
.
.
for screenshot in screenshot_list:
    im = Image.open(BytesIO(base64.b64decode(screenshot)))
    im = im.crop((left, top, right, bottom))

现在我正在将所有这些图像保存到光盘并使用保存文件中的 ffmpeg:

os.system('ffmpeg -r {fps} -f image2 -s {width}x{height} -i {screenshots_dir}%04d.png -vf scale={width}:-2 '
      '-vcodec libx264 -crf 25 -vb 20M -pix_fmt yuv420p {output}'.format(fps=fps, width=width,
                                                                  screenshots_dir=screenshots_dir,
                                                                  height=height, output=output))

但是我不想使用那些保存的文件,而是希望能够将 PIL.Images 目录传送到 ffmpeg,我该怎么做?

赏金没有了,但我找到了解决方案。

在将所有屏幕截图获取为 base64 字符串后,我使用以下代码将它们写入子进程

import subprocess as sp

# Generating all of the screenshots as base64 
# in a variable called screenshot_list

cmd_out = ['ffmpeg',
           '-f', 'image2pipe',
           '-vcodec', 'png',
           '-r', '30',  # FPS 
           '-i', '-',  # Indicated input comes from pipe 
           '-vcodec', 'png',
           '-qscale', '0',
           '/home/user1/output_dir/video.mp4']

pipe = sp.Popen(cmd_out, stdin=sp.PIPE)

for screenshot in screenshot_list:
    im = Image.open(BytesIO(base64.b64decode(screenshot)))
    im.save(pipe.stdin, 'PNG')

pipe.stdin.close()
pipe.wait()

# Make sure all went well
if pipe.returncode != 0:
    raise sp.CalledProcessError(pipe.returncode, cmd_out)

如果执行时间有问题,您可以将图像另存为 JPEG,并为此使用适当的编解码器,但我设法实现的最高质量是通过这些设置