How to Flip a Video with Python

flip video python

Video flipping is a technique for creating a mirror effect of an original video footage. One of the common uses of video flipping is to make text photographed backward (e.g., in a mirror, through glass, or using a reverse-facing camera) to face the right way. You can also use video flipping to add creative effects to your video clips, for example, to invert gravity.

In this article, we’ll explore different methods of video flipping in Python, using libraries and tools like OpenCV, FFmpeg, and Cloudinary.

In this article:

Flipping videos with OpenCV

OpenCV (Open Source Computer Vision) is a Python library that provides methods for image and video processing, including reading video data, accessing video properties, and performing frame operations.

Here’s the video we will be using for this article: https://res.cloudinary.com/demo/video/upload/dog.mp4.

If you haven’t installed OpenCV yet, you can install it with the command below:

pip install opencv-python

Next, create a main.py file and add the following code to it:

import cv2

# Open the video file
video_input = cv2.VideoCapture('dog.mp4')

# Get video properties including width, height, and frames per second (FPS)
fps = video_input.get(cv2.CAP_PROP_FPS)
frame_width = int(video_input.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(video_input.get(cv2.CAP_PROP_FRAME_HEIGHT))

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
output_video = cv2.VideoWriter('flipped-video.mp4', fourcc, fps, (frame_width, frame_height))

# A loop to read frames from the input video and flip each frame one by one
while video_input.isOpened():
    ret, frame = video_input.read()
    if not ret:
        break
    flipped_frame = cv2.flip(frame, 0)  # Use '0' for vertical flipping and '1' for horizontal flipping and '-1' for both.
    output_video.write(flipped_frame)

# After the loop ends, release the video capture and writer objects and close all windows
video_input.release() 
output_video.release()
cv2.destroyAllWindows()

Below is the flipped video output:

flip video python

If you noticed, the audio in the original video doesn’t play in the flipped video. This is because OpenCV doesn’t handle audio streams by default. To fix this, we can use alternatives such as FFmpeg or movie.py to flip the video while preserving the audio output.

flip video python

Flipping Videos with FFmpeg

FFmpeg is a popular and powerful multimedia framework that provides command-line utilities for processing audio and video files. It offers extensive capabilities for video manipulation, including flipping operations. One advantage of using FFmpeg over OpenCV is that the audio is preserved when flipping a video with the former.

You can download it from the official website here if you don’t already have it installed.

To flip a video vertically or horizontally using FFmpeg, we can use the vflip or hflip filters, respectively.

Here’s the command to flip the example video from before vertically:

ffmpeg -i dog.mp4 -vf "vflip" flipped-video-ffmpeg.mp4

Here’s the output of the command:

https://res.cloudinary.com/dqlql3rhr/video/upload/v1713459910/etc3j3b93k1foncfrhl4.mp4

Flipping Videos with Cloudinary

Video flipping and rotation are some of the features available on Cloudinary. Flipping videos with Cloudinary is pretty straightforward. Unlike the other Python libraries, you can rotate and flip your videos to any angle with Cloudinary. What’s more, the audio in your video is preserved, and you can even add other transformations, such as overlays, to your videos before flipping them.

In the steps below, we’ll show you how to use Cloudinary to flip videos in a Python application.

Step 1 – Setting up the Project

To get started, create a new directory where you’d like to have the project and run the command below in the terminal to create a virtual environment and activate it:

python3 -m venv env
source env/bin/activate

Step 2 – Install Necessary Packages

Now, let’s install the package dependencies we need to build the application.

Run the command below to install the packages with pip:

python3 -m pip install fastapi python-multipart cloudinary 
pydantic-settings python-dotenv uvicorn[standard]

ul>

  • FastAPI: A Python framework for creating web servers and APIs.
  • python-multipart: A Python library for handling multipart/form-data POST requests.
  • python-dotenv: A Python library for managing environment variables.
  • pydantic-settings: A Python library managing application settings and configurations using Pydantic models.
  • Cloudinary: A cloud-based service that provides image and video management solutions. It offers features like image upload, storage, manipulation, optimization, and delivery.
  • Uvicorn: An ASGI web server implementation for creating web servers in Python.
  • Step 3 – Create a Server

    After the installation is complete, create a file named main.py in the root of the project and add the following code to it to create a server:

    from fastapi import FastAPI
    from fastapi import FastAPI, File, UploadFile
    from pydantic_settings import BaseSettings
    import cloudinary
    
    class Settings(BaseSettings):
        CLOUDINARY_CLOUD_NAME: str
        CLOUDINARY_API_KEY: int
        CLOUDINARY_API_SECRET: str
        class Config:
            env_file = ".env"
    
    settings = Settings()
    
    config = cloudinary.config(cloud_name = settings.CLOUDINARY_CLOUD_NAME, api_key = settings.CLOUDINARY_API_KEY, api_secret = settings.CLOUDINARY_API_SECRET)
    
    import cloudinary.uploader
    import cloudinary.api
    
    app = FastAPI()
    
    @app.get("/")
    async def root():
    	return {"message": "Hello, World!"}
    

    Step 4 – Add Environment Variables

    Before we start the server, create a .env file in the root directory and add your Cloudinary credentials to it as follows:

    CLOUDINARY_API_KEY = 
    <YOUR_CLPOUDINARY_API_KEY>CLOUDINARY_CLOUD_NAME = 
    <YOUR_CLOUDINARY_CLOUD_NAME>CLOUDINARY_API_SECRET = 
    <YOUR_CLOUDINARY_API_SECRET>

    You can get your credentials by logging in to your Cloudinary dashboard and copying your API key, Cloud name, and API secret

    Next, run the command below in the terminal to start up the server:

    uvicorn main:app --reload

    Next, navigate to http://127.0.0.1:8000 in your browser, and you should see the following JSON response:

    {"message": "Hello, World!"}

    Step 5 – Flipping the video programmatically

    Modify the entire content of main.py to the following:

    from fastapi import FastAPI, File, UploadFile
    from pydantic_settings import BaseSettings
    import cloudinary
    import os
    
    class Settings(BaseSettings):
        CLOUDINARY_CLOUD_NAME: str
        CLOUDINARY_API_KEY: int
        CLOUDINARY_API_SECRET: str
        class Config:
            env_file = ".env"
    
    settings = Settings()
    
    config = cloudinary.config(cloud_name = settings.CLOUDINARY_CLOUD_NAME, api_key = settings.CLOUDINARY_API_KEY, api_secret = settings.CLOUDINARY_API_SECRET)
    
    import cloudinary.uploader
    import cloudinary.api
    
    app = FastAPI()
    
    async def cloudinary_upload(file):
         # Upload the video to Cloudinary and flip it
        flipped_video = cloudinary.uploader.upload(file, angle='vflip', resource_type="video") # Use 'vflip' for vertical fliping and 'hflip' for horizontal flipping
        return flipped_video
    
    @app.get("/")
    async def root():
        return {"message": "Hello, World!"}
    
    @app.post("/upload")
    async def create_video(video: UploadFile = File(...)):
        # Create a directory called "videos" if it doesn't exist.
        os.makedirs("videos", exist_ok=True)
    
    
    	# Save the uploaded video to disk
        file_location = f"videos/{video.filename}"
        with open(file_location, "wb+") as file_object:
            file_object.write(video.file.read())
    
        result = await cloudinary_upload(file_location)
    
    
    	# Extract the secure URL of the flipped video from the result returned by Cloudinary
        video_file = result["secure_url"]
    
        return f"The flipped video can be found here: {video_file}"
    

    Here’s what the code above does.

    1. In the first five lines, we import the required modules and packages to build the application.
    2. Next, we define a Settings class that inherits from BaseSettings. Inside the class, we define the Cloudinary credential variable types, and the Config nested class specifies that these variables should be loaded from a .env file.
    3. Next, we define an asynchronous function cloudinary_upload that takes a file argument. It uses the cloudinary.uploader.upload method to upload the file (in this case, a video) to Cloudinary.
    4. The angle='vflip' parameter tells Cloudinary to flip the video vertically, and the resource_type="video" specifies that the file we’re uploading is a video.
    5. We also define a route handler for the /upload endpoint that accepts the uploaded video and uses the cloudinary_upload function to flip the video.

    Step 6 – Trying it out

    Now, let’s see the result of our code so far. If you use VS Code, download the Postman extension to make API calls to our application.

    When we upload a video to the /upload endpoint in Postman, we get the URL to the flipped video as shown below:

    Flipped video URL: https://res.cloudinary.com/cloudinarymich/video/upload/v1712485336/r6wnzr0bmlpytecohzsu.mp4

    Wrapping Up

    Congratulations if you made it this far! In this article, we explore various methods of flipping videos in Python. We walk through how to use Python libraries such as OpenCV and command-line tools like FFmpeg. Additionally, we demonstrated how to achieve the same objective using Cloudinary and highlighted its efficiency and simplicity compared to the other methods.

    We hope this article will provide you with a solid foundation in video flipping techniques. Happy coding!

    Optimize, transform, and manage your media assets like a pro with Cloudinary. Sign up for free today!

QUICK TIPS
Matthew Noyes
Cloudinary Logo Matthew Noyes

In my experience, here are tips that can help you better flip videos using Python:

1. Ensure correct color space handling
When flipping videos using OpenCV, pay attention to the color space of your video. OpenCV works with BGR by default, so if your input video uses a different color space (like RGB or YUV), convert it appropriately to avoid color distortions in the flipped output.

2. Parallelize video processing
If you’re working with large or high-resolution videos, consider parallelizing the frame processing. Use Python’s multiprocessing library to split the video into segments and process multiple frames simultaneously, significantly speeding up the flipping operation.

3. Preserve metadata with FFmpeg
When using FFmpeg to flip videos, ensure you preserve important metadata like frame rate, aspect ratio, and color profile by explicitly passing them as parameters during the command execution. This avoids compatibility issues when playing back the flipped video on different devices.

4. Combine flipping with other transformations
Leverage FFmpeg’s filter chains to apply multiple transformations simultaneously. For example, you can flip, resize, and adjust the brightness of the video in a single command, reducing the need for multiple processing steps and improving efficiency.

5. Utilize hardware acceleration
Enable hardware acceleration in FFmpeg by adding flags like -hwaccel and specifying your GPU (e.g., cuda or vaapi). This can drastically reduce the processing time when flipping videos, especially for high-definition or 4K footage.

6. Optimize Cloudinary transformations
When flipping videos with Cloudinary, take advantage of its on-the-fly transformation capabilities to dynamically serve flipped versions without needing to store additional copies. Use responsive URLs to automatically serve the optimal resolution and format based on the viewer’s device.

7. Handle audio-video sync issues
Ensure that the audio stream remains perfectly synchronized with the video after flipping. This is particularly important when using OpenCV, which does not handle audio natively. You may need to use FFmpeg to mux the original audio back with the flipped video.

8. Batch processing for bulk video flipping
When dealing with multiple videos, automate the flipping process by scripting batch operations using FFmpeg or Cloudinary’s API. This approach can save time and ensure consistency across all processed videos.

9. Test different flipping methods for performance
Depending on the size and format of your videos, one method (OpenCV, FFmpeg, or Cloudinary) may outperform the others. Test all methods on a sample video to determine which one offers the best balance between processing time and output quality for your specific use case.

10. Integrate with CI/CD pipelines
If your video flipping is part of a larger media workflow, integrate the process into your CI/CD pipeline. Use tools like GitHub Actions or Jenkins to automatically trigger video flipping when new videos are added, ensuring that all content is consistently processed before deployment.

Last updated: Sep 8, 2024