管道图像到ffmpeg stdin -python



我正在尝试将HTML5视频转换为MP4视频,并通过屏幕拍摄随着时间的推移而进行屏幕射击

我也使用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,并为此使用适当的编解码器,但是我设法实现的最高质量是这些设置

最新更新