How to Auto Crop Videos with FFmpeg and Bash
Removing black bars from videos manually can be tedious, but the
process can be fully automated using a Bash script. This article
provides a step-by-step guide and a complete Bash script that runs
FFmpeg’s cropdetect filter on a video file, extracts the
optimal cropping coordinates, and automatically outputs a newly cropped
video.
How the Automation Works
FFmpeg includes a filter called cropdetect that analyzes
video frames to find non-black pixels and calculates the appropriate
crop dimensions. To automate this, a Bash script must:
- Analyze a small portion of the video (skipping the beginning to avoid black opening credits).
- Extract the
cropparameter values from FFmpeg’s console output. - Apply those coordinates to the final video using the
cropfilter.
The Automated Bash Script
Save the following code as autocrop.sh and make it
executable with chmod +x autocrop.sh.
#!/bin/bash
# Check if an input file is provided
if [ -z "$1" ]; then
echo "Usage: $0 <input_video> [output_video]"
exit 1
fi
INPUT_FILE="$1"
# Determine output filename if not provided
if [ -z "$2" ]; then
FILENAME="${INPUT_FILE%.*}"
EXTENSION="${INPUT_FILE##*.}"
OUTPUT_FILE="${FILENAME}_cropped.${EXTENSION}"
else
OUTPUT_FILE="$2"
fi
echo "Analyzing video to detect black bars..."
# Run cropdetect on 10 frames starting 30 seconds into the video
# This avoids intro logos and blank screens
CROP_VALUES=$(ffmpeg -ss 00:00:30 -i "$INPUT_FILE" -vframes 10 -vf cropdetect -f null - 2>&1 | grep -o "crop=[0-9]*:[0-9]*:[0-9]*:[0-9]*" | tail -n 1)
if [ -z "$CROP_VALUES" ]; then
echo "Error: Could not detect crop parameters. The video might not have black bars."
exit 1
fi
echo "Detected crop parameters: $CROP_VALUES"
echo "Processing video..."
# Crop the video and copy the audio track without re-encoding it
ffmpeg -i "$INPUT_FILE" -vf "$CROP_VALUES" -c:v libx264 -crf 18 -c:a copy "$OUTPUT_FILE"
echo "Finished! Cropped video saved as: $OUTPUT_FILE"Script Breakdown
ffmpeg -ss 00:00:30: Seeks 30 seconds into the video. This ensures the detection happens on actual video content rather than pure black opening frames.-vframes 10: Analyzes 10 consecutive frames, which is enough to determine the aspect ratio accurately while keeping detection near-instant.-vf cropdetect: Initiates the crop detection filter.grep -o "crop=..." | tail -n 1: Parses FFmpeg’s output, isolating the final determined crop values (e.g.,crop=1920:800:0:140).-vf "$CROP_VALUES": Applies the detected crop configuration to the entire video.-c:a copy: Copies the audio stream directly without re-encoding to save time and preserve original audio quality.