Extract video frames as collection of images

Let's just say i was trying to learn how to better use ffmpeg, and started asking myself "What are the things i needed when working with video content?".

And this is one of the things that came to mind. A simple way to extract several video frames from a video file, and exporting those into a directory of my choice.

Very useful when making thumbnails from video content, and needing to choose the best one from a certain timespan.

Here are some ways on how i managed to do exactly that.

Using ffmpeg

#!/usr/bin/env bash

INPUT_FILEPATH="${1}"
FRAME_TIME="${2}"
FRAME_COUNT="${3:-60}"
OUTPUT_DIR_FILEPATH="${4:-./extracted_frames/}"
OUTPUT_FILEPATH_TEMPLATE="${OUTPUT_DIR_FILEPATH}/%d.png"

mkdir \
--parents \
"${OUTPUT_DIR_FILEPATH}"

ffmpeg \
-i "${INPUT_FILEPATH}" \
-ss "${FRAME_TIME}" \
-frames:v ${FRAME_COUNT} \
"${OUTPUT_FILEPATH_TEMPLATE}"

The Bash script takes 4 arguments in total, with the third being optional:

  • The 1. one is the filepath to the video file.
  • The 2. one is the starting time, from which to extract the video frame. The expected input format is HH:MM:SS, meaning hours, minutes and seconds with exactly two digits.
  • The 3. one is the amount of frames to extract from the starting time onwards. If not set, will extract a total of 60.
  • The 4. is the output directory path. Gets created if it doesn't exist. If not set, will store the extracted frames in ./extracted_frames/ .

The output frames (saved as PNG images) are enumerated in the output directory, starting with 1 as their filename.

Using MoviePy

This approach uses the MoviePy Python3 library, which is pretty good for scripting general purpose video editing.

Adapt the Python v3 script to your needs.

#!./venv/bin/python3
from pathlib import Path

from moviepy import VideoFileClip


def save_images_sequence(input_filepath, start_time, end_time, output_directory_path = "extracted_frames", name_format = "frame%d.png") -> None:
    input_filepath = Path(input_filepath)
    output_directory_path = Path(output_directory_path)

    output_directory_path.mkdir(
        parents=True,
        exist_ok=True,
    )

    with VideoFileClip(input_filepath) as source_clip:
        new_clip = source_clip.subclipped(
            start_time=start_time,
            end_time=end_time,
        )
        new_clip.write_images_sequence(
            name_format=f"{Path(output_directory_path)}/{name_format}",
        )


save_images_sequence(
    input_filepath="./test.mp4",
    start_time=(0, 11),
    end_time=(0, 20),
)

Links

Social