The Wayback Machine - https://web.archive.org/web/20240628231454/https://www.geeksforgeeks.org/python-play-a-video-using-opencv/
Open In App

Python | Play a video using OpenCV

Last Updated : 04 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. 

Let’s see how to play a video using the OpenCV Python. To capture a video, we need to create a VideoCapture object. VideoCapture have the device index or the name of a video file. Device index is just the number to specify which camera. If we pass 0 then it is for first camera, 1 for second camera so on. We capture the video frame by frame.

 Syntax

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

Step 1: Import the required modules,

Python3




import cv2
import numpy as np


Step 2: Creating the object of the VideoCapture and read the input file

Python3




cap = cv2.VideoCapture('Spend Your Summer Vacations Wisely! Ft. Sandeep Sir _ GeeksforGeeks.mp4')


Step 3: Check if the camera is opened or not,

Python3




if (cap.isOpened()== False): 
# Give a error message


Step 4: Entire file is read frame by frame,

Python3




# Read the entire file until it is completed
while(cap.isOpened()):
  # Capture each frame
    ret, frame = cap.read()
      if ret == True:
      # Display the resulting frame


Below is the complete implementation

Python3




# importing libraries
import cv2
import numpy as np
  
# Create a VideoCapture object and read from input file
cap = cv2.VideoCapture('Spend Your Summer Vacations\
Wisely! Ft. Sandeep Sir _ GeeksforGeeks.mp4')
  
# Check if camera opened successfully
if (cap.isOpened()== False):
    print("Error opening video 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()


Output:

Output video frames

Output video frames

Note : Video file should have in same directory where program is executed.

Explanation:

Here we are first importing the required modules first and using the VideoCapture() method to read the input video file and raise a error if the file didn’t open and imshow() to present the frame that was fetched.



Previous Article
Next Article

Similar Reads

Python | Play a video in reverse mode using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV's application areas include : 1) Facial recognition system 2) motion tracking 3) Artificial neural network 4) Deep neural network 5) video streaming etc. In Python, one can use an OpenCV library named C
3 min read
OpenCV C++ Program to play a video
The following is the explanation to the C++ code to play a video in C++ using the tool OpenCV. Things to know: (1) The code will only compile in Linux environment. (2) To run in windows, please use the file: 'play_video.o' and run it in cmd. However if it does not run(problem in system architecture) then compile it in windows by making suitable and
3 min read
Python | Create video using multiple images using OpenCV
As we know OpenCV is a widely used library for image processing. It provides a wide sense of image processing. Let's see how to create video using multiple images using OpenCV. Install the following libraries: PIL cv2 Also, check the path before running the code otherwise you will be full with errors. How it works ? Using PIL library we are opening
3 min read
MoviePy – Turning on auto play for video clip file
In this article we will see how we can turn on the auto play of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Video is formed by the frames, combination of frames creates a video each frame is an individual image. We can display a video with the help of ipyt
2 min read
Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
6 min read
Converting Color video to grayscale using OpenCV in Python
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will see how to convert a colored video to a gray-scale format. Approach: Import the cv2 module.Read the video file to be converted usi
1 min read
Python - Displaying real time FPS at which webcam/video file is processed using OpenCV
We will be displaying the real-time processing FPS of the video file or webcam depending upon our choice.FPS or frame per second or frame rate can be defined as number of frames displayed per second. A video can be assumed as a collection of images or we can say frames which are displayed at some rate to produce motion. if you wish to identify the
4 min read
Get video duration using Python - OpenCV
OpenCV is one of the most popular cross-platform libraries and it is widely used in Deep Learning, image processing, video capturing, and many more. In this article, we will learn how to get the duration of a given video using python and computer vision. Prerequisites: Opencv moduledatetime moduleInstallation Opencv can be downloaded by running the
1 min read
How to draw Filled rectangle to every frame of video by using Python-OpenCV?
In this article, we will discuss how to draw a filled rectangle on every frame of video through OpenCV in Python. Stepwise Implementation:Import the required libraries into the working space.Read the video on which you have to write. Syntax: cap = cv2.VideoCapture("path") Create an output file using cv2.VideoWriter_fourcc() method. Here you will ha
2 min read
Click response on video output using Events in OpenCV – Python
OpenCV is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. In this article, we will create a program with a click response on video output using events in OpenCV Python library. We will be using “cv2.EVENT_LBUTTONDOWN” in case wh
3 min read
three90RightbarBannerImg