Directly using the ffmpeg library in Python is better. Without further ado, let's use it to try it out.
Introduction#
FFmpeg is a powerful audio and video processing program and is the foundation of many audio and video software. In fact, FFmpeg has become the industry standard for audio and video processing. However, using FFmpeg through the command line has a certain learning curve, and the ffmpeg-python library solves this problem well.
After installing it simply with pip, you can use ffmpeg in Python code.
pip3 install ffmpeg-python
Get Video Information#
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)
We can use the stream to obtain some basic information about the video, such as dimensions, duration, frame rate, etc.
Mirror Processing#
# Horizontal flip
ffmpeg.input(path).hflip().output('output.mp4').run()
# Vertical flip
ffmpeg.input(path).vflip().output('output.mp4').run()
You can simply understand it as the abbreviation of the English words "horizontal" and "vertical".
Add Watermark#
main = ffmpeg.input(path)
logo = ffmpeg.input('logo.png')
ffmpeg.filter([main, logo], 'overlay', 0, 500).output('out.mp4').run()
This command means placing the logo watermark image above the main video, with coordinates (0,500). You can consider the top left corner of the video as the origin (0,0), where moving right and down represents the x-axis and y-axis, respectively.
Of course, if the logo is made large enough, larger than the video, and then the positions of both sides are swapped, it will become placing the video on the logo, which is actually equivalent to adding a background image to the video.
ffmpeg.filter([logo, main], 'overlay', 0, 500).output('out.mp4').run()
Video Trimming#
ffmpeg.input(path).trim(start_frame=10,end_frame=20).output('out3.mp4').run()
This command is easy to understand, where start_frame and end_frame represent the starting and ending frames, respectively.
Video Concatenation#
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()
Video concatenation can be done using the concat function.
Summary
Today, I shared a good library for video processing in Python, hoping to bring some efficiency improvements to your work or side projects.