Batch File for FFmpeg: Output Every 5th Frame

Abstract: Extract every fifth frame from a video file using FFmpeg and a reusable batch script to create time-lapse sequences or reduce data size.

Created: 2026-08-10 by
Use FFmpeg with the select video filter and eq expression to extract every fifth frame. The command structure is ffmpeg -i input.mp4 -vf "select=not(mod(n\,5))" -vsync vfr output_%03d.png. This approach isolates specific frames without re-encoding the entire video stream, making it highly efficient for creating time-lapse sequences or reducing data size.

Understanding Frame Selection Logic

The core of this operation relies on FFmpeg's ability to evaluate expressions for each frame processed. The select filter accepts a boolean expression that determines whether a frame should be passed through to the output or discarded. In this specific scenario, we need a mechanism to count frames sequentially and trigger an output only when the count meets our criteria. FFmpeg provides a special variable called n, which represents the number of the input frame, starting from 0. To identify every fifth frame, we utilize the modulo operator (mod). The modulo operation returns the remainder of a division. For example, if you divide 10 by 5, the remainder is 0. If you divide 11 by 5, the remainder is 1. By checking if mod(n, 5) equals zero, we can pinpoint frames at indices 0, 5, 10, 15, and so on. However, since we often want to include the very first frame (index 0) and subsequent multiples, the logic must be precise. The expression not(mod(n, 5)) evaluates to true when the remainder is zero, effectively selecting frames 0, 5, 10, etc. If you prefer to start counting from the first frame as "one" rather than zero, you might adjust the offset, but standard indexing usually aligns well with direct modulo checks for regular intervals.

Constructing the Batch Script

Creating a reusable batch file allows you to process multiple videos without typing commands manually. Below is a robust script template that handles input and output naming conventions automatically.
@echo off
setlocal enabledelayedexpansion

REM Define input file
set INPUT=%~1

if "%INPUT%"=="" (
    echo Please provide an input video file.
    exit /b 1
)

REM Extract filename without extension
for %%F in ("%INPUT%") do set NAME=%%~nF

REM Run FFmpeg command
ffmpeg -i "%INPUT%" -vf "select='not(mod(n\,5))'" -vsync vfr "%NAME%_every5th_frame_%%03d.png"

echo Processing complete.
pause
This script uses Windows batch syntax. It takes the first argument passed to it as the input video. It then extracts the base name of the file to use as a prefix for the output images. The critical part is the -vf argument. Note the backslash before the comma in \,5. In many shell environments and batch files, the comma inside the expression needs to be escaped or quoted properly to prevent parsing errors. The -vsync vfr flag is crucial here. It tells FFmpeg to preserve the original timestamps of the selected frames. Without this, the output might have incorrect timing information, although for static image extraction, it ensures consistent frame rates if you were converting back to video later.

Handling Output Formats and Efficiency

When extracting frames, you typically want individual image files rather than a new video file, unless you are specifically building a slow-motion effect. Saving to PNG format preserves quality, while JPEG would introduce compression artifacts. If your goal is to create a GIF, you can pipe the output directly into another FFmpeg instance. It is important to note that this method does not reduce the processing load significantly in terms of CPU usage during decoding. FFmpeg still has to decode every single frame to determine if it matches the selection criteria. However, it saves disk I/O and storage space because only the selected frames are written to the disk. This is particularly useful when dealing with high-resolution source material where storing every frame would require terabytes of space. For more complex editing tasks, such as combining these extracted frames with audio or other media, you may find related techniques useful. See Combining Video and Audio with FFmpeg for details on merging streams. Additionally, if you need to resize these frames during extraction, refer to Resizing Video with FFmpeg: Two Passes, Without Aspect Ratio, Without Black Borders to maintain aspect ratios correctly.

Troubleshooting Common Issues

Users often encounter issues with frame numbering or missing frames. Ensure that your input video does not have variable frame rates that might confuse the counter. While select counts decoded frames, some containers or codecs might drop frames during playback or conversion. Always verify the output sequence by checking the filenames. If you notice gaps in the numbering, it is likely due to how the output filename pattern is formatted. Using %03d ensures that numbers are padded with zeros (e.g., 001, 002), which helps in sorting and sequential processing. If you are working with time-lapse photography, consider using Converting Rec.709 Time-Lapse Images using FFmpeg to ensure color spaces are handled correctly during the export phase. Another common error is forgetting to escape special characters in the filter expression. In Windows Command Prompt, the backslash before the comma is sometimes optional depending on the version of FFmpeg, but it is safer to include it. In Linux or macOS terminal scripts, you should wrap the expression in single quotes to prevent the shell from interpreting the comma or parentheses as special characters.

Advanced Filtering Options

Beyond simple interval selection, the select filter supports complex mathematical expressions. You can combine conditions using and, or, and gte (greater than or equal), lte (less than or equal). For instance, to select every fifth frame only after the first ten seconds, you would incorporate the t variable, which represents the timestamp of the frame in seconds. The expression might look like select='gte(t\,10)*not(mod(n\,5))'. This allows for precise control over which parts of the video contribute to the final output.

Frequently Asked Questions

How do I save the frames as a single video instead of images?

Replace the output filename extension with .mp4 or .avi and remove the -vsync vfr flag if you want constant frame rate. You may also need to add -r 24 to specify the desired output frame rate explicitly, ensuring smooth playback when the sparse frames are played back as a continuous stream.

Can I select every Nth frame starting from a different index?

Yes, you can modify the modulo expression. To start from frame 2 and then pick every 5th thereafter, use select='(n-2)*not(mod(n-2\,5))'. This shifts the counting window so that frame 2 becomes the new reference point for the modulo calculation.

Why are my output images black or corrupted?

This usually happens if the filter expression is syntactically incorrect or if the codec used for output does not support the pixel format. Try adding -pix_fmt yuv420p to the command line to force a widely compatible pixel format, especially if you are saving to formats other than PNG.

Does this method work for WebM or MKV containers?

The select filter operates on the decoded video stream, so container format does not matter for the filtering step. However, ensure that the output container supports the codec you are using. WebM requires VP8 or VP9 codecs, so you would need to specify -c:v libvpx if exporting to WebM.

How can I apply this to multiple files in a folder?

You can extend the batch script using a for loop. In Windows, use for %%f in (*.mp4) do ffmpeg .... In Linux or macOS, use a for f in *.mp4; do ffmpeg ...; done loop. This automates the process across all video files in the current directory.

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