Crop Video to Aspect Ratio with FFmpeg on Linux
Cropping a video to a specific aspect ratio using FFmpeg on Linux is
a straightforward process achieved primarily through the video filter
(-vf) flag and the crop filter. This guide
provides a quick overview of how the crop filter works,
details the precise command syntax required to change a video’s aspect
ratio, and offers practical examples for common formats like 16:9, 1:1,
and 9:16.
Understanding the FFmpeg Crop Filter
To change the aspect ratio of a video, FFmpeg redefines the width and height of the video frame, often cutting off the edges to fit the new dimensions. The core syntax for the crop filter is:
-vf "crop=w:h:x:y"
w: The width of the output video.h: The height of the output video.x: The horizontal position from where to start the crop (default is the center).y: The vertical position from where to start the crop (default is the center).
FFmpeg allows the use of internal variables like in_w
(input width) and in_h (input height) to calculate these
values dynamically.
Common Aspect Ratio Formulas
When cropping, you usually want to keep the output centered. By
omitting the x and y parameters, FFmpeg
automatically centers the crop area.
Here are the standard commands for common aspect ratio conversions:
1. Square Aspect Ratio (1:1)
To crop a widescreen video into a perfect square (ideal for certain social media platforms), you need to make the width equal to the height. This command forces the output width to match the original input height:
ffmpeg -i input.mp4 -vf "crop=in_h:in_h" output.mp4
2. Vertical Aspect Ratio (9:16)
To convert a standard landscape video into a vertical video (often used for mobile formats), the height needs to be greater than the width. The formula sets the width based on the input height multiplied by the 9:16 ratio:
ffmpeg -i input.mp4 -vf "crop=in_h*(9/16):in_h" output.mp4
3. Widescreen Aspect Ratio (16:9)
If you have a vertical or square video that you want to crop into a standard widescreen format, you calculate the height based on the input width:
ffmpeg -i input.mp4 -vf "crop=in_w:in_w*(9/16)" output.mp4
Advanced Positioning
If the subject of your video is not dead-center, you can manually
specify the x and y coordinates to shift the
cropping window.
For example, to crop a video to a 4:3 aspect ratio but align the crop
to the far-left edge of the original frame instead of the center, set
the x coordinate to 0:
ffmpeg -i input.mp4 -vf "crop=in_h*(4/3):in_h:0:0" output.mp4
Streamlining the Export
By default, FFmpeg will re-encode the video to apply the crop filter.
To ensure optimal quality and compatibility, you can explicitly state
your preferred video codec (such as H.264) using the -c:v
flag:
ffmpeg -i input.mp4 -vf "crop=in_h:in_h" -c:v libx264 -crf 23 -c:a copy output.mp4
In this command, -crf 23 maintains a good balance of
video quality and file size, while -c:a copy copies the
audio stream directly without re-encoding, saving processing time.