Flipping videos is a common technique in multimedia processing, useful for correcting mirrored footage, creating creative effects, or adjusting orientation. In Python, you can flip videos using several methods and tools, including OpenCV’s cv2.flip() function, FFmpeg command-line utilities, and Cloudinary’s cloud-based transformations.
This guide covers how to use cv2.flip() to flip video frames programmatically, explains its syntax and parameters, and demonstrates alternative approaches with FFmpeg and Cloudinary. Whether you need to flip videos vertically, horizontally, or both, you’ll find practical code examples and step-by-step instructions for each method, helping you choose the best solution for your workflow.
In this article:
- Flipping videos with OpenCV
- Using cv2.flip() in OpenCV
- Flipping Videos with FFmpeg
- Flipping Videos with Cloudinary
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:
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.
Using cv2.flip() in OpenCV
The cv2.flip() function in OpenCV is used to flip a 2D array, such as an image or a video frame, around vertical, horizontal, or both axes. Its syntax is:
cv2.flip(src, flipCode[, dst])
- src: The input array (for example, a frame read from a video using cv2.imread() or cv2.VideoCapture).
- flipCode: An integer flag that determines the flip direction:
- 0: Flips around the x-axis (vertical flip).
- 1: Flips around the y-axis (horizontal flip).
- -1: Flips around both axes (vertical and horizontal).
- dst: (Optional) Output array to store the result. If not provided, a new array is created.Example usage:
import cv2 # Load an image img = cv2.imread('image.jpg') # Flip horizontally flipped_horizontally = cv2.flip(img, 1) # Flip vertically flipped_vertically = cv2.flip(img, 0) # Flip both horizontally and vertically flipped_both = cv2.flip(img, -1) # Display the flipped images (optional) cv2.imshow('Original Image', img) cv2.imshow('Flipped Horizontally', flipped_horizontally) cv2.imshow('Flipped Vertically', flipped_vertically) cv2.imshow('Flipped Both', flipped_both) cv2.waitKey(0) cv2.destroyAllWindows()In the video-flipping code above,
cv2.flip(frame, 0)flips each frame vertically. You can change the flipCode parameter to 1 for horizontal flipping or -1 for both directions, depending on your requirements.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
vfliporhflipfilters, 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.pyin 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
.envfile 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:8000in 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.pyto 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.
- In the first five lines, we import the required modules and packages to build the application.
- Next, we define a
Settingsclass that inherits fromBaseSettings. Inside the class, we define the Cloudinary credential variable types, and theConfignested class specifies that these variables should be loaded from a.envfile. - Next, we define an asynchronous function
cloudinary_uploadthat takes afileargument. It uses thecloudinary.uploader.uploadmethod to upload the file (in this case, a video) to Cloudinary. - The
angle='vflip'parameter tells Cloudinary to flip the video vertically, and theresource_type="video"specifies that the file we’re uploading is a video. - We also define a route handler for the
/uploadendpoint that accepts the uploaded video and uses thecloudinary_uploadfunction 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
/uploadendpoint 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!