# How to flip a video in Python

Here we are going to learn how to flip a video clockwise or anticlockwise in Python.

The video is at first captured from the camera then stored before flipping it upside down. In many situations, you may require to flip a video like during detection or face recognition etc. If you have to analyze a video then this a very basic step.

## Basic Logic Behind Flipping a Video in Python

Now what we need to do to flip a video is:

1. Capture each instant of a video
2. Store each captured image
3. Flip each image (rotate each image)
4. Store the flipped image/ View the video

We need these following steps at every instant of the video.

Now how to flip an image?

It is quite simple. We have to shift each and every pixel to a different location which is given by the rotation matrix. The equation is given as follows:

[x*, y*]=[[cosx ,sinx], [-sinx ,cosx]][x, y]

where,

x,y= original pixel location(before flip)

x*,y*= flipped pixel location

This is how the flip function works.

## Python program to flip a video using OpenV

Now it’s time to code. See our Python program given below:

```import numpy as np
import cv2
import cv

# capture video
cap = cv2.VideoCapture(0)

#descripe a loop
#read video frame by frame
while True:
cv2.imshow('Original Video',img)
#flip for truning(fliping) frames of video
img2=cv2.flip(img,-1)
cv2.imshow('Flipped video',img2)

k=cv2.waitKey(30) & 0xff
#once you inter Esc capturing will stop
if k==27:
break
cap.release()
cv2.destroyAllWindows()```

Let us now understand how the above code works.

At first, we are capturing a video using cv2.VideoCapture(0). Here 0 argument refers to the default camera of the machine you are using. you can also give a path name if you want to capture a video of your desired choice.

Next, we start an infinite while loop that executes as long as we don’t stop the video(press esc). Then we do the required steps involved to flip a video(as stated above).

Also, read: Video streaming in Tkinter with Python

Finally, we need to release the space occupied due to storing the videos. And once we press esc both the windows get closed. This is done by destroying all the windows.

Now below is our image after the flip event: ### 2 responses to “How to flip a video in Python”

1. John says:

why import cv … doesn’t work with python 3

• Sarbajit De says:

This has happened because cv module is not installed in your python library. Trying installing cv through pip.