Effortlessly Extract Video Frames with FFMPEG and Python
Written on
Chapter 1: Introduction to Frame Extraction
In this guide, we'll explore how to extract frames from a video at regular intervals using Python in conjunction with FFMPEG. This method can be particularly useful for quickly reviewing a video or programmatically creating a trailer by stitching the frames back together into a short clip.
To begin, ensure you have both Python and FFMPEG installed on your system. For guidance on this setup, refer to my article on streaming to the browser using FFMPEG CLI and Python.
Section 1.1: Preparing to Extract Frames
To extract images from your video, you'll utilize the ffmpeg-python module. Below is a sample code snippet that demonstrates how to achieve this:
import ffmpeg
YOUR_FILE = 'sample-mov-file.mov'
probe = ffmpeg.probe(YOUR_FILE)
duration = float(probe['streams'][0]['duration']) // 2
width = probe['streams'][0]['width']
# Define the number of frames to extract.
parts = 7
intervals = int(duration // parts)
interval_list = [(i * intervals, (i + 1) * intervals) for i in range(parts)]
i = 0
for item in interval_list:
(
ffmpeg
.input(YOUR_FILE, ss=item[1])
.filter('scale', width, -1)
.output('Image' + str(i) + '.jpg', vframes=1)
.run()
)
i += 1
Make sure the video file you want to extract images from is located in the same directory as your script. Replace 'sample-mov-file.mov' with the actual filename of your video.
We begin by using ffmpeg.probe to gather metadata about the video, particularly its duration, which helps determine the spacing between the extracted frames.
Next, set parts to the number of frames you wish to extract. The list comprehension generates a list of intervals in seconds. The for loop targets the end of each interval to capture the corresponding frame. Each image is saved with a filename format of ImageZ, where Z represents the image count starting from 0 up to the total number of images requested.
You can later combine these images into a video using a different code sample, which is designed for assembling videos from a series of frames.
Now, let’s see some practical applications through videos.
Learn how to extract frames or images from videos using FFmpeg in this detailed tutorial.
Section 1.2: Video Frame Extraction in Action
For those looking to master the art of frame extraction, the following tutorial dives deeper into the process.
This tutorial walks you through the steps of extracting video frames and saving them effectively with FFmpeg.
Chapter 2: Wrapping Up
Now that you have the tools and knowledge to extract frames from videos, feel free to experiment with different interval settings and see what creative outputs you can generate. Have fun with your projects!