Python | Play a video using OpenCV
Last Updated :
04 Dec, 2025
OpenCV (Open Source Computer Vision) is a powerful computer-vision library used for working with images and videos. One of its common uses is playing video files inside a Python window. To do this, we use the VideoCapture class, which allows OpenCV to open and read videos frame by frame.
We will be using this sample video for demonstration. To download it, click here.
When working with videos, OpenCV reads each frame sequentially in a loop, displaying them just like a regular media player.
Module Installation
We are going to use cv2 library for this project, install it using the folowing pip command:
pip install cv2
Syntax
- cv2.VideoCapture(0) → Opens the default webcam
- cv2.VideoCapture(1) → Opens the second webcam
- cv2.VideoCapture("file.mp4") → Loads a video file
Step-by-Step Process
Step 1: Import the required modules,
Python
Step 2: Load the video file
Python
cap = cv2.VideoCapture(cap = cv2.VideoCapture("video.mp4")
Step 3: Check if the video was loaded successfully
Python
if not cap.isOpened():
print("Error: Could not open video file.")
exit()
Step 4: Read and display video frame-by-frame
Python
while True:
ret, frame = cap.read()
if not ret:
break # No more frames → end of video
cv2.imshow("Video", frame)
# Press Q to quit
if cv2.waitKey(25) & 0xFF == ord('q'):
break
Step 5: Release and close
Python
cap.release()
cv2.destroyAllWindows()
Complete Working Code
Python
import cv2
# Load the video file
cap = cv2.VideoCapture("video.mp4")
# Check if the video opened correctly
if not cap.isOpened():
print("Error: Could not open video file.")
exit()
# Read and display video frames
while True:
ret, frame = cap.read()
if not ret:
break # No more frames -> exit loop
cv2.imshow("Video", frame)
# Press Q to quit
if cv2.waitKey(25) & 0xFF == ord('q'):
break
# Release resources
cap.release()
cv2.destroyAllWindows()
Output
Note : Video file should have in same directory where program is executed.
Explanation:
- VideoCapture() loads the video.
- cap.read() fetches each frame.
- imshow() displays the frame.
- waitKey(25) adds a small delay between frames to create a video effect.
- Pressing Q exits the loop.
- After the video ends, OpenCV releases the video and closes all windows.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice