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:

  1. Analyze a small portion of the video (skipping the beginning to avoid black opening credits).
  2. Extract the crop parameter values from FFmpeg’s console output.
  3. Apply those coordinates to the final video using the crop filter.

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