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 處理視頻的不錯的庫,希望可以給大家的工作 / 副業帶來一些效率上的提升。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。