Creating a Slow motion Video Using OpenCV in Python

In this tutorial, we are gonna create a slow-motion video using OpenCV module in Python. This is a very easy method to create a slow-motion video. Before we start let me tell you how this works. All we are doing is, opening the video and displaying it in higher frames (i.e the time between each frame is increased).

Play video in slow motion in Python using OpenCV

import cv2

fileName=input("Enter the file name \n")     
slomo_frame = int(input("Enter the frames you want to change to \n"))  
cap = cv2.VideoCapture(fileName)       # load the video
while(cap.isOpened()):                    # play the video by reading frame by frame
    ret, frame = cap.read()
    if ret==True:
        cv2.imshow('frame',frame)              # show the video
        if cv2.waitKey(slomo_frame) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
cv2.destroyAllWindows()

I have attached the documentation of OpenCV here. This is a very useful module which is used for real-time computer vision-related problems. Look into the link for more understanding about OpenCV. Now let’s get started with the program.

Let’s see it line by line.

  1. To use OpenCV first we need to import OpenCV and it is called “cv2“.
  2. Now we need to take our inputs that’s gonna be the filename and the frames.
  3. And then we load the video using the VideoCapture function and store it in a variable called “cap“.
  4. And now we read each frame from the video and display it with a delay, this creates the slow-motion effect. So to read the frame one by one we use an infinite while loop.
  5. Now we check if the frame is available or not using the if statement, if it exists then we display the frame
  6. And now of the main and interesting part,  we use the wait key to put a time interval between the frames and 0xFF == ord (‘q’) tells us that we need to press the key  “q” to exit from the program.
  7. Now after all the frames are read and displayed “ret” will become false and the while loop is exited.
  8. Since we are loading the video to “cap” we need to release it or it will stay in the memory as junk.
  9. And at last, we need to Destroy the window which is opened as output.

Note: The video and the program should be in the same file or directory and the type of file should be mentioned in the input of filename (eg myvideo.mp4 or myvideo.avi).

Leave a Reply

Your email address will not be published. Required fields are marked *