banner
andrewji8

Being towards death

Heed not to the tree-rustling and leaf-lashing rain, Why not stroll along, whistle and sing under its rein. Lighter and better suited than horses are straw sandals and a bamboo staff, Who's afraid? A palm-leaf plaited cape provides enough to misty weather in life sustain. A thorny spring breeze sobers up the spirit, I feel a slight chill, The setting sun over the mountain offers greetings still. Looking back over the bleak passage survived, The return in time Shall not be affected by windswept rain or shine.
telegram
twitter
github

Python小工具:给视频批量加水印

直接用 python 的 ffmpeg 库更香,话不多说,咱就拿它来试试水。

简介#

FFmpeg 是一套强大的音视频处理程序,也是很多音视频软件的基础,事实上,FFmpeg 已经成为业界音视频处理的标准了。但命令行使用 FFmpeg 是有一定学习成本的,而 ffmpeg-python 库则很好的解决了这个问题。

通过 pip 简单安装之后即可在 python 代码中使用 ffmpeg。

pip3 install ffmpeg-python

获取视频信息#

path = 'main.mp4'
probe = ffmpeg.probe(path)
video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
width = int(video_stream['width'])
height = int(video_stream['height'])
print(width, height)

我们可以通过 stream 来获取视频的一些基础信息,比如尺寸、时长、帧率等。

镜像处理#

# 左右镜像
ffmpeg.input(path).hflip().output('output.mp4').run()

# 上下镜像
ffmpeg.input(path).vflip().output('output.mp4').run()

可以简单的理解为英文单词横向(horizontal)和纵向(vertical)的首字母缩写。

添加水印#

main = ffmpeg.input(path)
logo = ffmpeg.input('logo.png')
ffmpeg.filter([main, logo], 'overlay', 0, 500).output('out.mp4').run()

这条命令的意思是,将 logo 水印图片放置在 main 视频的上方,坐标为(0,500)。可以把视频的左上角理解为原点(0,0)的位置,从原点向右和向下分别表示 x 轴和 y 轴。

当然,如果把 logo 做的足够大,比视频还要大,然后换一下双方的位置,那就会变成将视频放到 logo 上了,其实相当于给视频加了一个背景图。

ffmpeg.filter([logo, main], 'overlay', 0, 500).output('out.mp4').run()

视频截取#

ffmpeg.input(path).trim(start_frame=10,end_frame=20).output('out3.mp4').run()

这条命令看起来就很容理解,start_frame 和 end_frame 分别代表起始结束帧。

视频拼接#

base = ffmpeg.input(path)
ffmpeg.concat(
    base.trim(start_frame=10, end_frame=20),
    base.trim(start_frame=30, end_frame=40),
    base.trim(start_frame=50, end_frame=60)
).output('out3.mp4').run()

视频拼接使用 concat 函数即可。
总结
今天给大家分享了一个 python 处理视频的不错的库,希望可以给大家的工作 / 副业带来一些效率上的提升。

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。