Extracting Frames from Multiple Videos using FFmpeg: A Step-by-Step Guide

Abstract: Extracts exactly four frames from multiple video files using a Bash loop and FFmpeg for efficient batch processing.

Created: 2026-09-06 by

To extract frames from multiple videos using FFmpeg, you can use a simple Bash loop that iterates through each file and applies the -vf fps=1/4 filter to select four specific frames. This approach ensures consistent output naming and handles batch processing efficiently without manual intervention for every individual clip.

Prerequisites and Environment Setup

Before executing any commands, ensure that FFmpeg is installed on your system. Most Linux distributions provide FFmpeg via their package managers, while macOS users typically install it via Homebrew using brew install ffmpeg. Windows users should download the static build from the official website and add the binary directory to their system PATH environment variable.

You will also need a terminal or command prompt with access to basic shell utilities like ls, find, or dir, depending on your operating system. The script provided below assumes a Unix-like environment (Linux or macOS) using Bash, as it leverages standard loop constructs that are native to these shells. If you are on Windows, you may need to adapt the syntax slightly or use PowerShell equivalents, but the core FFmpeg logic remains identical.

Constructing the Batch Processing Script

The most efficient way to handle multiple files is by creating a small shell script. This avoids repetitive typing and reduces the risk of typos in filenames. Create a new file named extract_frames.sh and open it in your preferred text editor. Inside this file, we will define a function or a direct loop that processes all video files in the current directory.

First, determine which video formats you want to process. Common extensions include .mp4, .mov, .avi, and .mkv. For simplicity, let us assume you want to process all .mp4 files in the current directory. You can list them using the wildcard *.mp4. The loop structure in Bash looks like this:

for file in *.mp4; do
    # Check if the file exists to avoid errors if no matches are found
    [ -e "$file" ] || continue
    
    # Extract the filename without extension
    base_name="${file%.*}"
    
    echo "Processing $file..."
    
    # Run the FFmpeg command here
    ffmpeg -i "$file" -vf "fps=1/4" -frames:v 4 "${base_name}_frame_%03d.png"
done

This script iterates through every .mp4 file. It strips the extension to create a unique prefix for the output images. The variable ${file%.*} removes the last dot and everything after it, ensuring that a file named video_01.mp4 results in outputs prefixed with video_01_frame.

Understanding the FFmpeg Command Components

Let us break down the critical parts of the FFmpeg command used inside the loop: ffmpeg -i "$file" -vf "fps=1/4" -frames:v 4 "${base_name}_frame_%03d.png".

  • -i "$file": Specifies the input video file. The quotes around $file are crucial if your filenames contain spaces.
  • -vf "fps=1/4": This is the video filter graph. The fps filter sets the frame rate of the output. By setting it to 1/4, you tell FFmpeg to keep one frame every four seconds. This effectively thins out the video stream to capture distinct moments rather than consecutive identical-looking frames.
  • -frames:v 4: This flag limits the number of video frames written to the output. Combined with the fps filter, it ensures that exactly four frames are extracted per video, regardless of the total duration.
  • "${base_name}_frame_%03d.png": Defines the output filename pattern. The %03d part is a placeholder for a zero-padded three-digit number (001, 002, etc.). This ensures the images are sorted correctly when viewed in a file explorer.

If you prefer to extract frames at specific intervals other than time-based ones, you might look into keyframe extraction methods. For more details on how timestamps and keyframes interact, see our guide on Understanding FFmpeg's ss, -t, -to, Streamcopy, and Keyframe Differences.

Handling Edge Cases and Errors

When processing multiple videos, not all files may be valid or readable. The script includes a check [ -e "$file" ] || continue to skip non-existent files, which happens if the glob pattern *.mp4 matches nothing. However, FFmpeg itself may fail if a file is corrupted or has an unsupported codec.

To make the script more robust, you can add error handling. Append && echo "Success: $file" to the end of the FFmpeg command. This ensures that the success message only prints if the FFmpeg command exits with a status code of 0. If you encounter issues with specific codecs, such as H.265 HEVC, ensure your FFmpeg build supports them, or consider converting the video first.

Another common issue is disk space. Extracting high-resolution frames generates many PNG files. If you run out of space, consider reducing the resolution by adding -s 640x480 before the output filename. This downscales the frames during extraction, saving significant storage compared to extracting full HD frames.

For those interested in manipulating video sequences further after extraction, such as combining them back together, refer to our article on How to Concatenate Videos with FFmpeg.

Running the Script and Verifying Output

Once the script is saved, make it executable by running chmod +x extract_frames.sh in your terminal. Then, execute it with ./extract_frames.sh. Watch the terminal output to monitor progress. Each line starting with "Processing" indicates a file being handled.

After completion, navigate to the directory containing your original videos. You should see a series of PNG files named filename_frame_001.png, filename_frame_002.png, and so on. Open a few samples to verify that they represent distinct moments in the video. If the frames appear too similar, increase the denominator in the fps filter (e.g., fps=1/10 for one frame every ten seconds).

If you need to stack these videos vertically instead of extracting frames, check out our tutorial on Efficient Way of Stacking Two Videos Vertically Using FFmpeg.

Frequently Asked Questions

Can I extract frames at exact second markers instead of intervals?

Yes, you can replace the fps filter with the select filter combined with expr to target specific times. However, for batch processing multiple unknown durations, the interval method is generally more reliable and easier to automate without calculating precise timestamps for each file.

Why are my extracted frames black or blank?

This usually happens if the video has no keyframes at the selected intervals or if the codec requires hardware acceleration that is unavailable. Ensure your FFmpeg version is up to date and try removing hardware-specific flags if present in your input pipeline.

How do I change the output format from PNG to JPEG?

Simply change the file extension in the output filename pattern from .png to .jpg. FFmpeg automatically detects the desired format based on the extension and adjusts the encoding parameters accordingly, though you may need to add -q:v 2 to control JPEG quality.

What if my videos have different durations?

The script handles varying durations gracefully because the fps filter operates independently of total length. Shorter videos will simply yield fewer potential frames, but the -frames:v 4 limit ensures you never get more than four, even if the video is very long.

Is there a way to extract frames only from the middle of the video?

You can use the -ss and -t options to seek to the middle and extract a segment. For example, -ss 50% -t 10 starts at the halfway point and extracts 10 seconds worth of content, which the fps filter then reduces to four frames.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More