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):
|
Step 4: Entire file is read frame by frame,
Python3
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
|
Below is the complete implementation
Python3
import cv2
import numpy as np
cap = cv2.VideoCapture('Spend Your Summer Vacations\
Wisely! Ft. Sandeep Sir _ GeeksforGeeks.mp4')
if (cap.isOpened()== False):
print("Error opening video file")
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
cv2.imshow('Frame', frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
else:
break
cap.release()
cv2.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.
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Last Updated :
04 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...