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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
04 Jan, 2023
Like Article
Save Article