Crop video with FFmpeg using dynamic variables
This guide explains how to use the FFmpeg crop filter
with dynamic variables to create responsive or moving video crops. By
leveraging built-in expressions and variables like frame number, time,
and input dimensions, you can automate cropping patterns without
manually calculating static pixel values for every frame.
Understanding the FFmpeg Crop Filter Syntax
The basic syntax for the FFmpeg crop filter is:
crop=w:h:x:y
w: The width of the output crop (defaults to input widthiw).h: The height of the output crop (defaults to input heightih).x: The horizontal position of the left edge of the crop area (defaults to central).y: The vertical position of the top edge of the crop area (defaults to central).
Key Dynamic Variables
FFmpeg allows you to use mathematical expressions and constants in these parameters. The most useful dynamic variables include:
iw/in_w: Input video width in pixels.ih/in_h: Input video height in pixels.ow/out_w: Output (cropped) video width.oh/out_h: Output (cropped) video height.n: The frame number (starting from 0).t: The timestamp of the current frame in seconds.
Practical Examples of Dynamic Cropping
1. Centering a Crop Relative to Input Dimensions
You can dynamically calculate the center of any video, regardless of its original size, by using the input and output dimensions.
ffmpeg -i input.mp4 -vf "crop=640:480:(iw-ow)/2:(ih-oh)/2" output.mp4In this command, (iw-ow)/2 automatically calculates the
correct starting x coordinate, and (ih-oh)/2
calculates the y coordinate to keep the 640x480 crop
perfectly centered.
2. Panning Across a Video Over Time
To create a “pan” or “slide” effect, you can use the time variable
(t) to continuously change the x or
y coordinates.
ffmpeg -i input.mp4 -vf "crop=400:400:t*50:0" output.mp4This crops a 400x400 area that moves horizontally to the right at a rate of 50 pixels per second.
3. Creating a Bouncing or Sinusoidal Movement
You can use trigonometric functions like sin() or
cos() to create oscillating movements.
ffmpeg -i input.mp4 -vf "crop=300:300:(iw-ow)/2+(iw-ow)/2*sin(t):(ih-oh)/2" output.mp4This keeps the crop height centered on the y-axis while making the crop window slide back and forth horizontally across the input video based on the sine wave of the current time.
4. Cropping Based on Frame Count
If you prefer to link the crop position to the exact frame number
rather than elapsed time, use the n variable.
ffmpeg -i input.mp4 -vf "crop=iw-2*n:ih-2*n" output.mp4This command creates a continuous digital zoom-in effect by shrinking both the crop width and height by 2 pixels with every passing frame.