如何在 python 中为视频添加白色背景?

Posted

技术标签:

【中文标题】如何在 python 中为视频添加白色背景?【英文标题】:How can I add a white background to a video in python? 【发布时间】:2020-01-12 14:00:17 【问题描述】:

我正在寻找一种通过添加白色背景而不是更改其比例来调整视频大小的方法。

(比例为 250x300 像素的视频将通过在视频的每一侧添加白带转换为 300x300 像素)

我尝试使用 ffmpeg 实现我在这个线程上找到的代码,但没有结果,我对图像/视频处理非常陌生: Thread

def Reformat_Image(ImageFilePath):

from PIL import Image
image = Image.open(ImageFilePath, 'r')
image_size = image.size
width = image_size[0]
height = image_size[1]

if(width != height):
    bigside = width if width > height else height

    background = Image.new('RGBA', (bigside, bigside), (255, 255, 255, 255))
    offset = (int(round(((bigside - width) / 2), 0)), int(round(((bigside - height) / 2),0)))

    background.paste(image, offset)
    background.save('out.png')
    print("Image has been resized !")

else:
    print("Image is already a square, it has not been resized !")

基本上我希望能够完成该线程中所做的事情,但要使用视频。

非常感谢任何帮助

【问题讨论】:

【参考方案1】:

您可以将ffmpeg-python 与pad视频过滤器一起使用:

import ffmpeg

input = ffmpeg.input('in.avi')
output = ffmpeg.output(input, 'out.mp4', vcodec='libx264', vf='pad=w=iw+50:h=ih:x=25:y=0:color=white')

output.run()

测试:

在命令行中使用FFmpeg创建in.avi进行测试:

ffmpeg -y -r 10 -f lavfi -i mandelbrot=rate=10:size=250x300 -t 5 -c:v rawvideo -pix_fmt bgr24 in.avi

Python执行结果(out.mp4的最后一帧):

备注:

该示例将in.avi 构建为原始视频格式(未压缩)。 该示例使用 x264 编解码器对out.mp4 进行编码(x264 / H.264,默认编码参数为 FFmpeg)。

【讨论】:

以上是关于如何在 python 中为视频添加白色背景?的主要内容,如果未能解决你的问题,请参考以下文章