MEDIA GUIDES / Video effects

3 Ways to Compress Video in Python

With Millennials and Gen Z consuming far more video content than older generations, it’s no wonder video has become the internet’s leading medium. Smooth streaming, rapid load times, and reasonable storage all depend on efficient video compression, which consumes a lot of bandwidth. Python steps up to the plate with a toolbox of powerful libraries, each ready to tackle video compression for your specific needs.

In this article, we’ll explore three effective methods to compress videos in Python: using FFmpeg, integrating Cloudinary for scalable compression and delivery, and leveraging MoviePy for simpler, Pythonic video editing and compression tasks. These tools provide varying levels of control over the compression process, allowing you to choose the best fit for your needs.

In this article:

Why Video Compression is Essential in Media Workflows

Video files can be massive, slowing down uploads, processing, and delivery across the web. Compression shrinks these files while preserving quality, enabling faster uploads, smoother streaming, and efficient storage:

  • Faster Uploads: Compressed videos reduce upload times, streamlining content creation and sharing.
  • Smoother Streaming: Smaller files ensure seamless playback, even on slower internet connections.
  • Efficient Storage: Compression minimizes storage needs, cutting costs for hosting high-resolution video collections.
  • Enhanced Scalability: Optimized videos improve performance, supporting global audiences and large-scale media platforms.

Method 1: Using FFmpeg with Python for Video Compression

FFmpeg is one of the most widely used command-line tools for video and audio processing. It supports a variety of codecs and formats and is extremely efficient for compressing video files. In Python, you can interact with FFmpeg using the subprocess library, which provides a Pythonic interface to FFmpeg’s command-line functionality.

To get started with FFmpeg, head over to the official FFmpeg website. Next, download and install FFmpeg using the instructions on the website.

Once FFmpeg is installed, create a Python file in the directory of your choosing and start by importing the subprocess library. Next, create a function that takes in 2 parameters: your input file directory and the output file directory.

import subprocess

def compress_video(input_file, output_file, bitrate='500k', resolution='1280x720'):
...

Here we are also taking in two optional parameters, the bitrate, and the resolution, that will allow us to control these parameters in the function.

Next, create a Python list defining the FFmpeg command and the options you want to run. Finally, run the subprocess using the subprocess.run() method. Here is what our code looks like:

import subprocess

def compress_video(input_file, output_file, bitrate='500k', resolution='1280x720'):
    command = [
        "ffmpeg",
        "-i", input_file,
        "-vf", f"scale={resolution}",
        "-b:v", bitrate,
        "-c:a", "copy",  # Copy audio without re-encoding
        output_file
    ]
    subprocess.run(command, check=True)

# Example usage
compress_video('input_video.mp4', 'output_video.mp4', '500k', '1280x720')

This approach allows you to have a high level of control over video compression, allowing you to adjust bitrate, resolution, codecs, and more to optimize video quality and file size.

Method 2: Integrating Cloudinary to Compress and Deliver Videos At Scale

If you’re dealing with video files at scale, especially for a web or mobile application, integrating Cloudinary can simplify video compression and optimization. Cloudinary is a powerful cloud service that offers video compression, transformation, and delivery features for images and videos. It automates the process, allowing you to focus on other aspects of your application.

Cloudinary can dynamically compress and deliver videos in optimized formats without having to manage the compression process manually. This is particularly useful for applications that handle large numbers of user-uploaded videos or need to stream videos to a global audience.

Looking for a custom solution to meet your Enterprise needs? Reach out and talk to an expert to find out how we can help.

To compress an image using Cloudinary, start by heading over to Cloudinary and logging in to your account. If you don’t have one, then you can head to the signup page and sign up for free. Once you’ve logged in, head over to the Programmable Media tab and click on the Go to API Keys button, where you will find your API credentials. Copy these, as we will need them later.

Now, to compress videos in Python using Cloudinary, first, you need to set up a Cloudinary account and obtain your credentials. Then, install the cloudinary Python SDK using pip:

pip install cloudinary

Once the library is installed, create a new file in your project directory and start by importing Cloudinary and initializing your API:

import cloudinary
import cloudinary.uploader
import cloudinary.api

# Configure Cloudinary with your account details
cloudinary.config(
  cloud_name="your-cloud-name",
  api_key="your-api-key",
  api_secret="your-api-secret"
)

Once the library is installed, create a new file in your project directory and start by importing Cloudinary and initializing your API:Remember to replace your-cloud-name, your-api-key, and your-api-secret with your actual API credentials.

After you’ve configured your API, you can use Cloudinary’s uploader.upload method to upload your video to the Cloudinary cloud. Set the quality parameter to 'auto', which tells Cloudinary to adjust the video quality dynamically based on the device and network conditions. Here is what our code looks like:

import cloudinary
import cloudinary.uploader
import cloudinary.api

# Configure Cloudinary with your account details
cloudinary.config(
  cloud_name="your-cloud-name",
  api_key="your-api-key",
  api_secret="your-api-secret"
)

# Upload and compress video
response = cloudinary.uploader.upload("path_to_your_video.mp4", resource_type="video", quality="auto", fetch_format="mp4")

# Output the URL of the compressed video
print("Compressed video URL:", response['secure_url'])

In this example, we also set the fetch_format to "mp4" which ensures the video is delivered in the widely supported MP4 format. Cloudinary’s API handles the compression and optimization for you, making it an ideal solution for delivering high-quality videos at scale with minimal effort.

Method 3: Compressing Video with MoviePy

MoviePy is another Python library for video editing that provides a simple and high-level interface for video processing. It can be used for tasks like cutting, concatenating, and compressing videos. While MoviePy doesn’t provide the low-level control that FFmpeg does, it’s a great option when you need a simple and Pythonic approach to video compression.

To use MoviePy, start by installing its Python library using pip:

pip install moviepy

Now, open up a new file and start by importing the VideoFileClip class from the library. Next, create a function that takes four parameters: the input file, the output file, and two optional parameters. This will help define the paths to your video files, as well as adjust the resolution and bitrate, if needed:

from moviepy.editor import VideoFileClip

def compress_video(input_file, output_file, resolution=(1280, 720), bitrate="500k"):

Now using VideoFlipClip, load your input file and use the resize method to resize your video as needed. Finally, export your video file using the write_videofile method while adjusting your bitrate. Here is what our code looks like:

from moviepy.editor import VideoFileClip

def compress_video(input_file, output_file, resolution=(1280, 720), bitrate="500k"):
    clip = VideoFileClip(input_file)
    clip_resized = clip.resize(resolution)  # Resize the video
    clip_resized.write_videofile(output_file, bitrate=bitrate)

# Example usage
compress_video('input_video.mp4', 'output_video.mp4', resolution=(1280, 720), bitrate="500k")

MoviePy is a powerful, high-level tool for simple video compression tasks. It’s best for scenarios where you need basic control over video properties like resolution and bitrate, and it’s especially useful when working with other types of video editing in Python.

Picking the Best Video Format For Compression

Choosing the right video format is just as important as the compression method itself. Some formats are inherently better suited for efficient compression, depending on your goals–whether that’s preserving quality, maximizing compatibility, or achieving the smallest possible file size. Here are a few common formats to consider:

  • MP4 (H.264 codec): This is the most widely used format for compressed videos. It offers an excellent balance between quality and file size and is compatible with nearly all devices and browsers.
  • WebM (VP9 codec): WebM is great for web-based applications. It provides high compression efficiency and is supported by modern browsers, though less so on mobile devices.
  • AVI and MOV: While these formats can deliver high quality, they’re generally not ideal for compression due to larger file sizes and compatibility limitations.

If you’re looking to compress videos in Python while maintaining good compatibility and file size, MP4 with H.264 is usually your best bet.

Balance Speed and Quality with Compression and Encoding

When you compress videos in Python, it’s important to balance speed, file size, and visual quality. Too much compression leads to pixelation; too little means larger files and slower load times. The best compression method depends on your use case:

  • FFmpeg gives you deep control and professional-grade results.
  • MoviePy offers simplicity and ease of use for light editing and quick compression.
  • Cloudinary stands out if you need fast, scalable compression with automatic optimization and built-in CDN delivery.

By integrating Cloudinary’s video transformation API, you can offload compression tasks, streamline delivery, and ensure videos are optimized for every device, with no need to manually tweak bitrate, resolution, or codecs.

Ready to simplify your video workflow? Create an account to try Cloudinary’s Python SDK and see how effortless compression can be.

Learn more:

Python Image Processing, Compression, and Resizing

Auto Generate Subtitles Based on Video Transcript

QUICK TIPS
Matthew Noyes
Cloudinary Logo Matthew Noyes

In my experience, here are tips that can help you better optimize and extend the capabilities of Python-based video compression:

  1. Use two-pass encoding for FFmpeg
    Improve compression efficiency by performing a two-pass encode, especially for final delivery files. The first pass gathers stats to optimize quality, and the second actually compresses based on that data.
  2. Analyze content type before choosing compression settings
    Motion-heavy content (sports, action) requires different settings than static or talking-head videos. Tailor bitrate and GOP size accordingly for optimal quality-to-size ratios.
  3. Leverage GPU acceleration with FFmpeg
    If you’re compressing multiple or high-resolution videos, use hardware acceleration (e.g., NVENC for NVIDIA GPUs). Add flags like -hwaccel cuda or use -c:v h264_nvenc to massively speed up processing.
  4. Integrate perceptual quality metrics in your workflow
    Instead of only relying on bitrate, use SSIM or VMAF to evaluate visual quality after compression. These metrics help balance perceived quality against file size more effectively.
  5. Auto-adjust resolution using Python and FFprobe
    Dynamically query video metadata with ffprobe and downscale based on screen-size targets (e.g., mobile vs. desktop). This prevents hardcoding and adapts content to the delivery context.
  6. Use Cloudinary transformation presets for consistent delivery
    Define and reuse transformation presets in Cloudinary’s dashboard to standardize compression quality across uploads. This reduces risk of quality inconsistency and simplifies deployment.
  7. Batch compress with threading or multiprocessing in Python
    For large batches of videos, use Python’s concurrent.futures or multiprocessing to parallelize compression tasks—this can significantly reduce processing time.
  8. Create visual diff previews for quality validation
    Generate side-by-side thumbnails (pre/post compression) to visually inspect degradation. Use PIL or OpenCV to automate this process and flag problematic frames.
  9. Use audio compression separately for optimal control
    Instead of copying audio (-c:a copy), use targeted audio compression (-b:a 96k) when bandwidth is constrained. This ensures audio doesn’t consume excessive size in optimized files.
  10. Automate fallback handling for codec support
    Build logic that tries modern codecs first (e.g., H.265, VP9), then gracefully falls back to H.264 or MP4 if the environment doesn’t support them. This improves future-proofing and compatibility.
Last updated: May 15, 2025