How to Display a Video File in Python — With and Without OpenCV

5/5 - (3 votes)

In this post, I will show you how you can display a video file in Python – with and without OpenCV. I will also explain the codes and show you step by step.

What is Opencv?

OpenCV is one of the most widely used open-source libraries for computer vision tasks such as image processing, object detection, face detection, image segmentation, face recognition, and many more

According to the creators’ website, OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in commercial products.

OpenCV written natively in C++, also has multiple programming language interfaces such as Python, Java and MATLAB. It also supports Windows, Linux, Android and Mac OS operating systems.

OpenCV and Machine Learning with Python

If you are writing Python scripts in machine learning, OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even handwriting of a human.

Now that we know the importance and applications of OpenCV to machine learning, let us dive into the steps by which we can display a video file in Python.

Working with a video file with python, we can display video with and without OpenCV. The main purpose of this post is to show you steps for both methods using python.  

How to Display a Video File in Python – with OpenCV

Step 1: Import the required modules

import cv2

import numpy as np

Step 2: Create a VideoCapture object.

# Create a VideoCapture object and read from input file
# If the input is the camera, pass 0 instead of the video file name
cap = cv2.VideoCapture('chaplin.mp4')

There are three (3) variations of arguments that can be passed along with the VideoCapture function:

  • cv2.VideoCapture(0): Means first camera or webcam.
  • cv2.VideoCapture(1):  Means second camera or webcam.
  • cv2.VideoCapture('file name.mp4'): Means video file

 After the VideoCapture object is created, we can then capture the video frame by frame.

Step 3: Check if camera opened successfully or the video file is opened.

if (cap.isOpened() == False):
    print("Error opening video stream or file")

Step 4: Read video file frame by frame

# Read until video is completed
while (cap.isOpened()):
    # Capture frame-by-frame
    ret, frame = cap.read()
    if ret == True:

Step 5: Display the read frame

After reading a video file, we can display the video frame by frame. A frame of a video is simply an image, and we display each frame the same way we display images, i.e., we use the function imshow()

# Display the resulting frame
cv2.imshow('Frame', frame)
# Press Q on keyboard to  exit
if cv2.waitKey(25) & 0xFF == ord('q'):
    break

We use the waitKey() function to pause each frame in the video.

For an image, it is okay to pass ‘0’ to the waitKey() function, but for a moving image such as the video, it is necessary to pass a number greater than “0” to the waitKey() function. This is because ‘0’ would pause the frame in the video for an infinite amount of time and in the video, we need each frame to be shown only for some finite interval of time.

The full Python source code for reading and displaying a video file using OpenCV is as follows. 

import cv2
import numpy as np


# Create a VideoCapture object and read from input file
# If the input is the camera, pass 0 instead of the video file name
cap = cv2.VideoCapture('filename.mp4')

# Check if camera opened successfully
if (cap.isOpened() == False):
    print("Error opening video stream or file")

# Read until video is completed
while (cap.isOpened()):
    
    # Capture frame-by-frame
    ret, frame = cap.read()
    if ret == True:

        # Display the resulting frame
        cv2.imshow('Frame', frame)

        # Press Q on keyboard to  exit
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break

    # Break the loop
    else:
        break

# When everything done, release the video capture object
cap.release()

# Closes all the frames
cv2.destroyAllWindows()

How to Display a Video File in Python – without OpenCV

We already know OpenCV is widely used to read and display a video file with Python, and has a wide spectrum of functions to do also. But what if we want to process a video file with some other python libraries. Let’s see how we can achieve this.

In this second method, I will be showing you, we will be implementing displaying a video with 2 python libraries.

You can install both libraries from your command prompt with the pip install command.

👉 Recommended Tutorial: How to Install a Library in Python?

After you have installed both libraries, the next step is to import them so they can be used.

Step 1: Import the libraries and make the video play

import moviepy
from moviepy.editor import *
import pygame

Step 2: Pass the file name to the VideoFileClip() function to load it and use the preview method to watch it.

clip = VideoFileClip('filename.mp4')
clip.preview()

Step 3: Use the pygame.quit() function to close the window

pygame.quit()

Resize the movie screen window

To resize the window, scaling the movie images, you just have to use resize, like this

clip = VideoFileClip('filename.mp4').resize(0.5)
clip.preview()
pygame.quit()

The full Python source code for reading and displaying a video file using Pygame Library and Moviepy Library, is as follows.

import moviepy
from moviepy.editor import *
import pygame

clip = VideoFileClip('mqA2xflUWgpX2Z8A.mp4').resize(0.5)
clip.preview()

pygame.quit()

Conclusion

From the two methods I showed you above, you can see that one is shorter and more straightforward than the other. And as such, in my opinion, the OpenCV method will be much more robust and powerful than the Moviepy library.

Newcomers in Python programming will find this procedure easier to learn and understand. But it also has disadvantages and shortcomings when it comes down to processing videos involving many successive frames of a movie.