Home » Tutorial: Playing Videos Using OpenCV in Python

Tutorial: Playing Videos Using OpenCV in Python

Java SE 11 Programmer I [1Z0-815] Practice Tests
Spring Framework Basics Video Course
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer II [1Z0-816] Practice Tests
Oracle Java Certification
1 Year Subscription

OpenCV provides powerful tools to play videos, whether from a file or a camera feed.

This tutorial will guide you through reading, displaying, and processing videos using OpenCV.

What You’ll Learn

1. Introduction to Video Playback

The class cv2.VideoCapture in OpenCV is used to capture video from a file or webcam. Video playback involves reading video frames, displaying them with cv2.imshow, and handling playback controls.

2. Playing Videos from a File

Example: Basic Video Playback

import cv2

# Open the video file
video = cv2.VideoCapture("video.mp4")

if not video.isOpened():
    print("Error: Could not open video file.")
    exit()

while True:
    ret, frame = video.read()  # Read the next frame

    if not ret:  # Break the loop if no more frames
        print("End of video.")
        break

    cv2.imshow("Video Playback", frame)  # Display the frame

    # Wait for 30ms; press 'q' to exit
    if cv2.waitKey(30) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

3. Playing Videos from a Webcam

Example: Webcam Video Feed

import cv2

# Open the webcam (0 for default camera)
video = cv2.VideoCapture(0)

if not video.isOpened():
    print("Error: Could not open webcam.")
    exit()

while True:
    ret, frame = video.read()  # Capture frame-by-frame

    if not ret:
        print("Failed to capture frame.")
        break

    cv2.imshow("Webcam Feed", frame)  # Display the captured frame

    # Exit on 'q' key press
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

4. Controlling Playback

Example: Pause and Resume

import cv2

# Open video file
video = cv2.VideoCapture("video.mp4")

if not video.isOpened():
    print("Error: Could not open video file.")
    exit()

while True:
    ret, frame = video.read()

    if not ret:
        break

    cv2.imshow("Video Playback", frame)

    key = cv2.waitKey(30) & 0xFF
    if key == ord('q'):  # Quit
        break
    elif key == ord('p'):  # Pause
        cv2.waitKey(-1)  # Wait indefinitely until a key is pressed

video.release()
cv2.destroyAllWindows()

5. Processing Frames While Playing

Example: Convert Frames to Grayscale

import cv2

# Open video file
video = cv2.VideoCapture("video.mp4")

if not video.isOpened():
    print("Error: Could not open video file.")
    exit()

while True:
    ret, frame = video.read()

    if not ret:
        break

    # Convert the frame to grayscale
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    cv2.imshow("Grayscale Video", gray_frame)

    if cv2.waitKey(30) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

Example: Apply Edge Detection

import cv2

# Open video file
video = cv2.VideoCapture("video.mp4")

if not video.isOpened():
    print("Error: Could not open video file.")
    exit()

while True:
    ret, frame = video.read()

    if not ret:
        break

    # Apply Canny edge detection
    edges = cv2.Canny(frame, 100, 200)

    cv2.imshow("Edge Detection", edges)

    if cv2.waitKey(30) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

6. Handling Video Playback Errors

Example: Error Handling

import cv2

video = cv2.VideoCapture("nonexistent.mp4")

if not video.isOpened():
    print("Error: Could not open video file.")
    exit()

while True:
    ret, frame = video.read()

    if not ret:
        print("Error: Could not read frame. Ending playback.")
        break

    cv2.imshow("Video Playback", frame)

    if cv2.waitKey(30) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

7. Practical Examples

7.1 Save Video Frames

import cv2
import os

# Open video file
video = cv2.VideoCapture("video.mp4")
output_dir = "frames"
os.makedirs(output_dir, exist_ok=True)

frame_count = 0

while True:
    ret, frame = video.read()

    if not ret:
        break

    # Save every 10th frame as an image
    if frame_count % 10 == 0:
        frame_path = os.path.join(output_dir, f"frame_{frame_count}.jpg")
        cv2.imwrite(frame_path, frame)

    frame_count += 1

video.release()
print("Frames saved.")

7.2 Add Text Overlay to Video

import cv2

video = cv2.VideoCapture("video.mp4")

while True:
    ret, frame = video.read()

    if not ret:
        break

    # Add text overlay
    text = "OpenCV Video Playback"
    cv2.putText(frame, text, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    cv2.imshow("Video with Text Overlay", frame)

    if cv2.waitKey(30) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

7.3 Playback Video in Reverse

import cv2

# Open video file
video = cv2.VideoCapture("video.mp4")

# Get total frame count
frame_count = int(video.get(cv2.CAP_PROP_FRAME_COUNT))

# Playback video in reverse
for i in range(frame_count - 1, -1, -1):
    video.set(cv2.CAP_PROP_POS_FRAMES, i)
    ret, frame = video.read()

    if not ret:
        break

    cv2.imshow("Reverse Playback", frame)

    if cv2.waitKey(30) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

8. Summary

Key Functions

  • cv2.VideoCapture(): Opens a video file or webcam.
  • cv2.imshow(): Displays frames in a window.
  • cv2.waitKey(): Waits for a key press and controls frame display timing.
  • cv2.VideoCapture.read(): Reads the next frame.

Best Practices

  1. Check if the video source is valid with isOpened().
  2. Use waitKey() to control playback speed or capture key presses.
  3. Process frames on-the-fly for real-time applications like edge detection or object tracking.
  4. Handle errors gracefully to ensure robust applications.

By combining these techniques, you can build powerful video playback and processing systems with OpenCV!

 

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More