【问题标题】:Pipe PIL images to ffmpeg stdin - Python管道 PIL 图像到 ffmpeg 标准输入 - Python
【发布时间】:2017-09-24 20:09:54
【问题描述】:

我正在尝试将 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,而不是使用那些保存的文件,我该怎么做?

【问题讨论】:

  • ffmpeg 部分应该以ffmpeg -f image2pipe -vcodec png -i - -vf .... 开头。如果 PIL 输出正确的 PNG 语法,则不需要指定输入图像大小。
  • 我指定是因为有时它不能被 2 整除,这会产生问题,所以我处理它然后指定它
  • 比例过滤器参数负责 mod 2 要求。这与摄取图像无关。
  • 谢谢,我会解决的

标签: python ffmpeg phantomjs python-imaging-library


【解决方案1】:

赏金没了,但我找到了解决办法。

在获取所有截图为 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,并为此使用适当的编解码器,但我设法达到的最高质量是使用这些设置

【讨论】:

  • 感谢您的回答——真的很有帮助!我认为在您的 cmd_out 列表中,第二个 vcodec 行(适用于输出)应该是 '-vcodec', 'libx264', 而不是 '-vcodec', 'png',,不是吗?
猜你喜欢
  • 2019-05-17
  • 1970-01-01
  • 2019-09-11
  • 1970-01-01
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多