Decord2

3.3.0 · active · verified Mon Apr 13

Decord2 is a high-performance, efficient video decoding and loading library for deep learning research, featuring smart shuffling, random frame access, GPU acceleration, and seamless integration with popular frameworks. It is currently at version 3.3.0 and has a frequent release cadence, with multiple releases in the past year.

Warnings

Install

Imports

Quickstart

Initialize a `VideoReader` to load frames from a video file. This example demonstrates accessing individual frames, slicing a batch of frames, and retrieving frames by specific indices. It defaults to CPU context but can be switched to GPU if the library is installed with CUDA support.

import os
import numpy as np
from decord import VideoReader, cpu

# Create a dummy video file for demonstration
# In a real scenario, you would have an actual video file
dummy_video_path = 'dummy_video.mp4'
# For a real application, ensure ffmpeg is installed and generate a simple video:
# import subprocess
# try:
#     subprocess.run(['ffmpeg', '-f', 'lavfi', '-i', 'testsrc=s=1280x720:r=30', '-vframes', '30', dummy_video_path], check=True)
# except FileNotFoundError:
#     print('FFmpeg not found. Cannot create dummy video.')
#     print('Please replace "dummy_video.mp4" with a path to an actual video file.')
#     exit()

# Placeholder for a real video file
# Assume 'your_video.mp4' exists or create one as above
video_file = 'your_video.mp4' # Replace with your video file path

# Initialize VideoReader with CPU context
# Use 'cpu(0)' for the first CPU context
# For GPU, use 'gpu(0)' if installed with GPU support
try:
    vr = VideoReader(video_file, ctx=cpu(0))
    print(f"Successfully opened video: {video_file}")
    print(f"Number of frames: {len(vr)}")

    # Access a single frame by index
    frame_0 = vr[0].asnumpy()
    print(f"Shape of first frame: {frame_0.shape}") # (H, W, C)

    # Access a batch of frames (e.g., frames 10 to 20)
    frames_batch = vr[10:20].asnumpy()
    print(f"Shape of frames batch: {frames_batch.shape}") # (N, H, W, C)

    # Access frames at specific indices
    random_frames = vr.get_batch([5, 15, 25]).asnumpy()
    print(f"Shape of random frames batch: {random_frames.shape}") # (N, H, W, C)

except Exception as e:
    print(f"Error processing video: {e}")
    print("Please ensure 'your_video.mp4' exists and is a valid video file.")
    print("You may also need to install FFmpeg on your system if installing from source.")

view raw JSON →