Ora

How to Handle Video in Python: Capture, Play, and Process

Published in Python Video Processing 6 mins read

Python offers powerful libraries, most notably OpenCV (Open Source Computer Vision Library), to effortlessly capture video from cameras, play existing video files, and perform various processing tasks. This allows you to integrate video functionalities directly into your applications, from security systems to media players.

Essential Tools for Video Handling in Python

The primary library for video manipulation in Python is OpenCV. It provides robust functions for real-time video capture, image processing, and video file handling.

Here's a quick overview of key libraries:

Library Primary Use Cases Key Features
OpenCV Video Capture, Playback, Image Processing, Analysis Real-time camera access, file I/O, vast array of image/video filters
MoviePy Video Editing, Compositing, Clip Manipulation Non-linear editing, effects, transitions, creating videos from images/audio
Pillow/PIL Image Processing (often used with MoviePy) Image manipulation, resizing, filters (not directly video)
imageio Reading/Writing various image/video formats Simple interface for I/O, supports many formats

To get started, you'll typically need to install OpenCV:

pip install opencv-python

Capturing Video from a Webcam

To capture live video from your computer's camera in Python, you utilize OpenCV's VideoCapture object. This object acts as an interface to your camera device.

  1. Initialize VideoCapture: You create a VideoCapture object, passing either a device index or a video file name. A device index is a number that specifies which camera to use. 0 typically refers to the first camera (often the default webcam), 1 to the second, and so on.

  2. Read Frames: Video is essentially a sequence of images (frames). You read these frames in a loop.

  3. Display Frames: Each captured frame can then be displayed in a window.

  4. Release Resources: After capturing, it's crucial to release the camera and destroy any windows to free up system resources.

Here's a practical example:

import cv2

def capture_webcam_video():
    """
    Captures live video from the default webcam and displays it.
    Press 'q' to quit the video feed.
    """
    # Create a VideoCapture object (0 for the default webcam)
    cap = cv2.VideoCapture(0)

    # Check if the webcam is opened successfully
    if not cap.isOpened():
        print("Error: Could not open webcam.")
        return

    print("Webcam feed started. Press 'q' to quit.")

    while True:
        # Read a frame from the webcam
        ret, frame = cap.read() # 'ret' is a boolean, 'frame' is the image data

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

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

        # Wait for 1 millisecond and check for 'q' key press to exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # Release the VideoCapture object and destroy all OpenCV windows
    cap.release()
    cv2.destroyAllWindows()
    print("Webcam feed stopped.")

if __name__ == "__main__":
    capture_webcam_video()

Saving Captured Video

Beyond just displaying the live feed, you can also save the captured video to a file. This involves using OpenCV's VideoWriter object.

  1. Define Output Parameters: Specify the output filename, codec (e.g., MJPG), frame rate, and frame dimensions.
  2. Create VideoWriter: Initialize the VideoWriter object with these parameters.
  3. Write Frames: In your capture loop, write each captured frame to the VideoWriter.
  4. Release VideoWriter: Important to release it after writing is complete.
import cv2

def record_webcam_video(output_filename="output.avi", frame_width=640, frame_height=480, fps=20):
    """
    Records video from the default webcam and saves it to a file.
    Press 'q' to stop recording.
    """
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        print("Error: Could not open webcam.")
        return

    # Define the codec and create VideoWriter object
    # FourCC is a 4-byte code used to specify the video codec.
    # 'MJPG' is a common and widely supported codec.
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    out = cv2.VideoWriter(output_filename, fourcc, fps, (frame_width, frame_height))

    if not out.isOpened():
        print("Error: Could not create video writer.")
        cap.release()
        return

    print(f"Recording started to '{output_filename}'. Press 'q' to stop.")

    while True:
        ret, frame = cap.read()
        if not ret:
            print("Failed to grab frame.")
            break

        # Resize frame to match writer dimensions if necessary (optional)
        # Ensure frame dimensions match what was passed to VideoWriter
        frame_resized = cv2.resize(frame, (frame_width, frame_height))

        # Write the flipped frame
        out.write(frame_resized)

        # Display the recording frame (optional)
        cv2.imshow('Recording...', frame_resized)

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

    cap.release()
    out.release()
    cv2.destroyAllWindows()
    print(f"Recording stopped and saved to '{output_filename}'.")

if __name__ == "__main__":
    record_webcam_video()

Playing an Existing Video File

OpenCV's VideoCapture object isn't just for live cameras; it can also open and play local video files.

import cv2

def play_video_file(video_path):
    """
    Plays an existing video file.
    Press 'q' to quit.
    """
    cap = cv2.VideoCapture(video_path)

    if not cap.isOpened():
        print(f"Error: Could not open video file '{video_path}'.")
        return

    print(f"Playing video '{video_path}'. Press 'q' to quit.")

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

        if not ret:
            # End of video or error
            print("End of video or read error.")
            break

        cv2.imshow('Video Player', frame)

        # Adjust the waitKey delay to control playback speed
        # For real-time playback, this might need tuning based on video FPS
        if cv2.waitKey(25) & 0xFF == ord('q'): # 25ms delay
            break

    cap.release()
    cv2.destroyAllWindows()
    print("Video playback stopped.")

if __name__ == "__main__":
    # Create a dummy video file or use an existing one
    # For example, run record_webcam_video() first to get 'output.avi'
    play_video_file("output.avi") # Replace with your video file path

Advanced Video Processing and Editing

For more complex scenarios like cutting, concatenating, adding effects, or generating videos from images, libraries like MoviePy are excellent choices.

  • Creating Video from Images: You can combine a sequence of images into a video.
  • Video Editing: Perform operations like trimming, cropping, adding text, or merging video clips.
from moviepy.editor import ImageSequenceClip
import numpy as np
import cv2 # For generating dummy images

def create_video_from_images(output_filename="images_to_video.mp4", num_frames=50, fps=10):
    """
    Generates a simple video from a sequence of dummy images.
    """
    frames = []
    for i in range(num_frames):
        # Create a simple image (e.g., a colored square that changes color)
        color = (i * 5) % 255
        img = np.zeros((200, 300, 3), dtype=np.uint8)
        img[:, :, 0] = color # Blue channel
        img[:, :, 1] = 255 - color # Green channel
        img[:, :, 2] = (color + 100) % 255 # Red channel
        frames.append(img)

    # Create a clip from the image sequence
    clip = ImageSequenceClip(frames, fps=fps)

    # Write the clip to a file
    clip.write_videofile(output_filename, codec='libx264')
    print(f"Video created from images and saved to '{output_filename}'.")

if __name__ == "__main__":
    create_video_from_images()

Conclusion

Whether you need to capture live footage, play existing files, or programmatically create and edit videos, Python, particularly with the OpenCV library, provides a robust and flexible platform. By understanding the core VideoCapture and VideoWriter objects, you can implement powerful video functionalities in your applications.