DEV Community

Amit Verma
Amit Verma

Posted on Originally published at tayloramitverma.com on

Building a Python Script to Convert Videos to Instagram Reels Format

As a content creator, I often need to convert landscape or square videos into the vertical 9:16 format required for Instagram Reels. Manually converting dozens of videos is time-consuming, so I built a Python script to automate this process. In this blog post, I'll walk you through how to create a robust video conversion tool using Python and FFmpeg.

The Challenge

Instagram Reels require a specific aspect ratio (9:16) and resolution (1080x1920 pixels). When you have a collection of videos in various formats (landscape, square, or other aspect ratios), converting them manually would take hours. Automation is the key to efficiency.

The Solution: Python + FFmpeg

I created a Python script that:

Automatically finds all video files in a directory

Converts them to 9:16 format (1080x1920)

Maintains video quality with optimised encoding settings

Provides progress tracking and error handling

Saves all converted videos in a dedicated output folder

Prerequisites

Before we dive into the code, you'll need:

Python 3.7+ - The script uses modern Python features

FFmpeg - The powerful multimedia framework that does the actual conversion

Install via: brew install ffmpeg (macOS) or apt-get install ffmpeg (Linux)

Or download from ffmpeg.org

The Complete Script

Here's the full Python script with detailed comments:

#!/usr/bin/env python3
"""
Video to Reels Converter
Converts videos to Instagram Reels format (9:16 aspect ratio, 1080x1920)
"""

import os
import subprocess
import sys
from pathlib import Path
from typing import List, Tuple

def find_video_files(directory: str = ".", exclude: List[str] = None) -> List[Path]:
    """
    Find all video files in the specified directory.

    Args:
        directory: Directory to search for videos
        exclude: List of filenames to exclude from conversion

    Returns:
        List of Path objects for video files
    """
    if exclude is None:
        exclude = ["South_Africa_YouTube_Short_30sec.mp4"]

    video_extensions = [".mov", ".mp4", ".MOV", ".MP4"]
    video_files = []

    directory_path = Path(directory)

    for file_path in directory_path.iterdir():
        if file_path.is_file() and file_path.suffix in video_extensions:
            if file_path.name not in exclude:
                video_files.append(file_path)

    return sorted(video_files)

def check_ffmpeg() -> bool:
    """Check if ffmpeg is installed and available."""
    try:
        subprocess.run(
            ["ffmpeg", "-version"],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            check=True
        )
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False

def convert_video_to_reels(
    input_path: Path,
    output_dir: Path,
    width: int = 1080,
    height: int = 1920
) -> Tuple[bool, str]:
    """
    Convert a video to Instagram Reels format.

    Args:
        input_path: Path to input video file
        output_dir: Directory to save output file
        width: Output width in pixels (default: 1080)
        height: Output height in pixels (default: 1920)

    Returns:
        Tuple of (success: bool, message: str)
    """
    # Create output directory if it doesn't exist
    output_dir.mkdir(parents=True, exist_ok=True)

    # Generate output filename
    output_filename = f"{input_path.stem}_reels.mp4"
    output_path = output_dir / output_filename

    # FFmpeg command to convert to 9:16 format
    # Scale to fit height, then crop width, or scale to fit width and pad height
    ffmpeg_cmd = [
        "ffmpeg",
        "-i", str(input_path),
        "-vf", f"scale={width}:{height}:force_original_aspect_ratio=increase,crop={width}:{height}",
        "-c:v", "libx264",
        "-preset", "medium",
        "-crf", "23",
        "-c:a", "aac",
        "-b:a", "128k",
        "-movflags", "+faststart",
        "-y", # Overwrite output file if it exists
        str(output_path)
    ]

    try:
        # Run ffmpeg and capture output
        result = subprocess.run(
            ffmpeg_cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )

        if result.returncode == 0:
            return True, f"✓ Completed: {output_path}"
        else:
            return False, f"✗ Error converting: {input_path.name}\n {result.stderr[:200]}"

    except Exception as e:
        return False, f"✗ Exception: {str(e)}"

def main():
    """Main function to convert all videos to Reels format."""
    print("=" * 50)
    print("Video to Instagram Reels Converter")
    print("=" * 50)
    print()

    # Check if ffmpeg is available
    if not check_ffmpeg():
        print("Error: ffmpeg is not installed or not in PATH.")
        print("Please install ffmpeg: https://ffmpeg.org/download.html")
        sys.exit(1)

    # Find all video files
    video_files = find_video_files()

    if not video_files:
        print("No video files found to convert.")
        sys.exit(0)

    total = len(video_files)
    print(f"Found {total} videos to convert...")
    print("Starting conversion to 9:16 format (1080x1920)...")
    print()

    # Create output directory
    output_dir = Path("reels")

    # Convert each video
    converted = 0
    successful = 0
    failed = 0

    for idx, video_file in enumerate(video_files, 1):
        print(f"[{idx}/{total}] Converting: {video_file.name}")

        success, message = convert_video_to_reels(video_file, output_dir)
        print(f" {message}")
        print()

        converted += 1
        if success:
            successful += 1
        else:
            failed += 1

    # Print summary
    print("=" * 50)
    print("Conversion Summary")
    print("=" * 50)
    print(f"Total videos processed: {converted}")
    print(f"Successfully converted: {successful}")
    print(f"Failed: {failed}")
    print(f"All files saved in: {output_dir.absolute()}/")
    print("=" * 50)

if __name__ == " __main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Key Features Explained

1. File Discovery

The find_video_files() function uses Python's pathlib module to scan the directory for video files. It supports common formats (.mov, .mp4) and allows you to exclude specific files from conversion.

2. FFmpeg Integration

The script uses Python's subprocess module to execute FFmpeg commands. The conversion uses a video filter (-vf) that:

Scales the video to fit the 1080x1920 frame

Crops to ensure exact 9:16 aspect ratio

Maintains the original aspect ratio while fitting the new dimensions

3. Encoding Settings

The script uses optimized encoding parameters:

Codec : H.264 (libx264) - widely compatible

Preset : Medium - good balance between speed and file size

CRF : 23 - constant rate factor for quality (lower = better quality, larger file)

Audio : AAC at 128kbps - standard for web video

Faststart : Enables streaming-friendly playback

4. Error Handling

The script includes comprehensive error handling:

Checks if FFmpeg is installed before starting

Captures and displays conversion errors

Tracks successful vs. failed conversions

Provides a summary at the end

Usage

Save the script as convert_to_reels.py

Make it executable (optional):

chmod +x convert_to_reels.py
Enter fullscreen mode Exit fullscreen mode

Run it in a directory containing your videos:

python3 convert_to_reels.py
Enter fullscreen mode Exit fullscreen mode

Find your converted videos in the reels/ directory

Example Output

==================================================
Video to Instagram Reels Converter
==================================================

Found 25 videos to convert...
Starting conversion to 9:16 format (1080x1920)...

[1/25] Converting: video1.mov
  ✓ Completed: reels/video1_reels.mp4

[2/25] Converting: video2.mp4
  ✓ Completed: reels/video2_reels.mp4

...

==================================================
Conversion Summary
==================================================
Total videos processed: 25
Successfully converted: 25
Failed: 0
All files saved in: /path/to/reels/
==================================================
Enter fullscreen mode Exit fullscreen mode

Customization Options

You can easily customise the script:

Change output resolution : Modify the width and height parameters

Adjust quality : Change the CRF value (18-28 range, lower = better quality)

Change output directory : Modify the output_dir variable

Add more video formats : Extend the video_extensions list

Modify encoding preset : Change from "medium" to "fast" or "slow"

Performance Tips

Batch Processing : The script processes videos sequentially. For faster processing on multi-core systems, you could modify it to use Python's multiprocessing module.

Storage : Ensure you have enough disk space - converted videos can be large

Quality vs. Speed : The "medium" preset offers a good balance. Use "fast" for quicker conversions or "slow" for better compression

Conclusion

This Python script demonstrates how automation can save hours of manual work. By combining Python's ease of use with FFmpeg's powerful video processing capabilities, we've created a tool that efficiently converts videos to the Instagram Reels format.

The script is modular, well-documented, and easy to extend. You could add features like:

Progress bars using tqdm

Parallel processing for faster conversions

GUI interface using tkinter or PyQt

Integration with cloud storage APIs

Automatic upload to Instagram

Feel free to use this script as a starting point for your own video processing projects!


_If you found this helpful, check out more of my projects and tutorials on [_tayloramitverma.com](https://tayloramitverma.com/)


Originally published at www.tayloramitverma.com.

Top comments (0)