Python | Play a video using OpenCV
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 cv2import 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 completedwhile(cap.isOpened()): # Capture each frame ret, frame = cap.read() if ret == True: # Display the resulting frame |
Below is the complete implementation
Python3
# importing librariesimport cv2import numpy as np# Create a VideoCapture object and read from input filecap = cv2.VideoCapture('Spend Your Summer Vacations\Wisely! Ft. Sandeep Sir _ GeeksforGeeks.mp4')# Check if camera opened successfullyif (cap.isOpened()== False): print("Error opening video file")# Read until video is completedwhile(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 objectcap.release()# Closes all the framescv2.destroyAllWindows() |
Output:

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.



Please Login to comment...