# Python video processing libraries

Python video processing libraries decode, edit, and encode video files frame by frame. Most rely on FFmpeg, either through bindings to its libraries or by building commands for its executable. These libraries let media pipelines, computer vision models, and editing tools read and write video in code.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [opencv-python-headless](#opencv-python-headless) | 64.1M | 5.5K | Nov 2026 | Apache-2.0 |
| [av](#av) | 52.3M | 3.3K | Oct 2026 | BSD-3-Clause |
| [imageio](#imageio) | 47.4M | 1.7K | Nov 2026 | BSD-2-Clause |
| [imageio-ffmpeg](#imageio-ffmpeg) | 27.1M | 306 | Nov 2026 | BSD-2-Clause |
| [torchvision](#torchvision) | 18.0M | 18.0K | Oct 2026 | BSD-3-Clause |
| [ffmpeg-python](#ffmpeg-python) | 11.1M | 11.0K | Jul 2019 | Apache-2.0 |
| [moviepy](#moviepy) | 5.5M | 15.2K | May 2025 | MIT |
| [torchcodec](#torchcodec) | 4.5M | 1.2K | Sep 2026 | BSD-3-Clause |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[opencv-python-headless](#opencv-python-headless) has the most monthly downloads in this comparison, at 64.1M, a count that covers all its computer vision work.

## Capabilities

| Library | Video encoding | Audio/video muxing | NumPy frame output |
| --- | --- | --- | --- |
| [opencv-python-headless](#opencv-python-headless) | Yes | No | Yes |
| [av](#av) | Yes | Yes | Yes |
| [imageio](#imageio) | Yes | Yes | Yes |
| [imageio-ffmpeg](#imageio-ffmpeg) | Yes | Yes | No |
| [torchvision](#torchvision) | No | No | No |
| [ffmpeg-python](#ffmpeg-python) | Yes | Yes | No |
| [moviepy](#moviepy) | Yes | Yes | Yes |
| [torchcodec](#torchcodec) | Yes | Yes | No |

## Libraries

### opencv-python-headless

[GitHub](https://github.com/opencv/opencv-python) · [PyPI](https://pypi.org/project/opencv-python-headless) · [Docs](https://github.com/opencv/opencv-python/blob/4.x/README.md)

Wraps the OpenCV Python bindings.

- Downloads / mo: 64.1M
- Stars: 5.5K
- Last release: 5.1.0.95
- License: Apache-2.0
- Capabilities: [From the opencv-python-headless docs](https://github.com/opencv/opencv-python/blob/4.x/README.md)

```sh
pip install opencv-python-headless
```

**Breakthrough/PySceneDetect** (5.5K stars)

[Breakthrough/PySceneDetect](https://github.com/Breakthrough/PySceneDetect) 

```python
def _open_capture(self, frame_rate: FrameRate | None = None):
    """Opens capture referenced by this object and resets internal state."""
    if self._is_device:
        assert isinstance(self._path_or_device, int)
        if self._path_or_device < 0:
            raise ValueError("Invalid/negative device ID specified.")
        input_is_video_file = False
        capture_api = cv2.CAP_ANY
    else:
        assert isinstance(self._path_or_device, str)
        capture_api = _get_capture_api(self._path_or_device)
        input_is_video_file = not any(
            identifier in self._path_or_device
            for identifier in NON_VIDEO_FILE_INPUT_IDENTIFIERS
        )
        # We don't have a way of querying why opening a video fails (errors are logged at
        # least), so provide a better error message if we try to open a missing file.
        if input_is_video_file and not os.path.exists(self._path_or_device):
            raise OSError("Video file not found.")

    cap = cv2.VideoCapture(self._path_or_device, capture_api)
    if not cap.isOpened():
        raise VideoOpenFailure(
            "Ensure file is valid video and system dependencies are up to date.\n"
        )

    # Display an error if the video codec type seems unsupported (#86) as this indicates
    # potential video corruption, or may explain missing frames. We only perform this check
    # for video files on-disk (skipped for devices, image sequences, streams, etc...).
    codec_unsupported: bool = int(abs(cap.get(cv2.CAP_PROP_FOURCC))) == 0
    if codec_unsupported and input_is_video_file:
        logger.error(
            "Video codec detection failed. If output is incorrect:\n"
            "  - Re-encode the input video with ffmpeg\n"
            "  - Update OpenCV (pip install --upgrade opencv-python)\n"
            "  - Use the PyAV backend (--backend pyav)\n"
            "For details, see https://github.com/Breakthrough/PySceneDetect/issues/86"
        )

    # Ensure the framerate is correct to avoid potential divide by zero errors. This can be
    # addressed in the PyAV backend if required since it supports integer timebases.
    assert frame_rate is None or frame_rate > MAX_FPS_DELTA, (
        "Frame rate must be validated if set!"
    )
    if frame_rate is None:
        frame_rate = cap.get(cv2.CAP_PROP_FPS)
        if frame_rate < MAX_FPS_DELTA:
            raise FrameRateUnavailable()

    self._cap: cv2.VideoCapture = cap
    self._frame_rate: Fraction = framerate_to_fraction(frame_rate)
    self._has_grabbed = False
    self._eof_timecode: Timecode | None = None
    cap.set(cv2.CAP_PROP_ORIENTATION_AUTO, 1.0)  # https://github.com/opencv/opencv/issues/26795

```

[scenedetect/backends/opencv.py](https://github.com/Breakthrough/PySceneDetect/blob/47f95bd4e2b36164db28d05afa68fdbbfac48153/scenedetect/backends/opencv.py#L373-L426) · [More projects using opencv-python-headless →](https://dashboard.exa.ai/playground/search?q=opencv-python-headless%20GitHub%20projects)

**Quickstart**

```python
import cv2

capture = cv2.VideoCapture('input.mp4')
ok, frame = capture.read()
capture.release()

```

From [videoio.hpp](https://github.com/opencv/opencv/blob/5.x/modules/videoio/include/opencv2/videoio.hpp)

### av

[GitHub](https://github.com/PyAV-Org/PyAV) · [PyPI](https://pypi.org/project/av) · [Docs](https://github.com/PyAV-Org/PyAV/blob/master/README.md)

Provides Pythonic bindings for FFmpeg's libraries.

- Downloads / mo: 52.3M
- Stars: 3.3K
- Last release: 19.0.2
- License: BSD-3-Clause
- Capabilities: [From the av docs](https://github.com/PyAV-Org/PyAV/blob/master/README.md)

```sh
pip install av
```

**ManimCommunity/manim** (42.6K stars)

[ManimCommunity/manim](https://github.com/ManimCommunity/manim) 

```python
def encode_and_write_frame(self, frame: PixelArray, num_frames: int) -> None:
    """
    For internal use only: takes a given frame in ``np.ndarray`` format and
    write it to the stream
    """
    for _ in range(num_frames):
        # Notes: precomputing reusing packets does not work!
        # I.e., you cannot do `packets = encode(...)`
        # and reuse it, as it seems that `mux(...)`
        # consumes the packet.
        # The same issue applies for `av_frame`,
        # reusing it renders weird-looking frames.
        av_frame = av.VideoFrame.from_ndarray(frame, format="rgba")
        for packet in self.video_stream.encode(av_frame):
            self.video_container.mux(packet)

```

[manim/scene/scene_file_writer.py](https://github.com/ManimCommunity/manim/blob/c2dfb597ff470f0cdb01ce9074edb426f45000bc/manim/scene/scene_file_writer.py#L424-L438) · [More projects using av →](https://dashboard.exa.ai/playground/search?q=av%20GitHub%20projects)

**Quickstart**

```python
import av

with av.open('input.mp4') as container:
    frame = next(container.decode(video=0))

```

From [core.py](https://pyav.basswood-io.com/docs/stable/api/_globals.html)

### imageio

[GitHub](https://github.com/imageio/imageio) · [PyPI](https://pypi.org/project/imageio) · [Docs](https://github.com/imageio/imageio/blob/master/README.md)

Provides image and video reading and writing through selectable backend plugins.

- Downloads / mo: 47.4M
- Stars: 1.7K
- Last release: 2.38.2
- License: BSD-2-Clause
- Capabilities: [From the imageio docs](https://github.com/imageio/imageio/blob/master/README.md)

**Strengths**

- **Iterates frames without bulk loading.** Use imiter for videos too large to load together.
- **Applies filters through PyAV.** Run FFmpeg filter sequences or graphs during video processing.

**Watch out for**

- **Video support needs extra packages.** Install the selected PyAV or FFmpeg backend.
- **Audio can outlast shortened video.** Trim audio separately when using the FFmpeg backend’s audio_path option.

```sh
pip install imageio imageio-ffmpeg
```

**huggingface/diffusers** (34.9K stars)

[huggingface/diffusers](https://github.com/huggingface/diffusers) 

```python
def export_to_video(
    video_frames: list[np.ndarray] | list[PIL.Image.Image],
    output_video_path: str = None,
    fps: int = 10,
    quality: float = 5.0,
    bitrate: int | None = None,
    macro_block_size: int | None = 16,
) -> str:
    """
    quality:
        Video output quality. Default is 5. Uses variable bit rate. Highest quality is 10, lowest is 0. Set to None to
        prevent variable bitrate flags to FFMPEG so you can manually specify them using output_params instead.
        Specifying a fixed bitrate using `bitrate` disables this parameter.

    bitrate:
        Set a constant bitrate for the video encoding. Default is None causing `quality` parameter to be used instead.
        Better quality videos with smaller file sizes will result from using the `quality` variable bitrate parameter
        rather than specifying a fixed bitrate with this parameter.

    macro_block_size:
        Size constraint for video. Width and height, must be divisible by this number. If not divisible by this number
        imageio will tell ffmpeg to scale the image up to the next closest size divisible by this number. Most codecs
        are compatible with a macroblock size of 16 (default), some can go smaller (4, 8). To disable this automatic
        feature set it to None or 1, however be warned many players can't decode videos that are odd in size and some
        codecs will produce poor results or fail. See https://en.wikipedia.org/wiki/Macroblock.
    """
    # TODO: Dhruv. Remove by Diffusers release 0.33.0
    # Added to prevent breaking existing code
    if not is_imageio_available():
        logger.warning(
            (
                "It is recommended to use `export_to_video` with `imageio` and `imageio-ffmpeg` as a backend. \n"
                "These libraries are not present in your environment. Attempting to use legacy OpenCV backend to export video. \n"
                "Support for the OpenCV backend will be deprecated in a future Diffusers version"
            )
        )
        return _legacy_export_to_video(video_frames, output_video_path, fps)

    if is_imageio_available():
        import imageio
    else:
        raise ImportError(BACKENDS_MAPPING["imageio"][1].format("export_to_video"))

    try:
        imageio.plugins.ffmpeg.get_exe()
    except AttributeError:
        raise AttributeError(
            (
                "Found an existing imageio backend in your environment. Attempting to export video with imageio. \n"
                "Unable to find a compatible ffmpeg installation in your environment to use with imageio. Please install via `pip install imageio-ffmpeg"
            )
        )

    if output_video_path is None:
        output_video_path = tempfile.NamedTemporaryFile(suffix=".mp4").name

    if isinstance(video_frames[0], np.ndarray):
        video_frames = [(frame * 255).astype(np.uint8) for frame in video_frames]

    elif isinstance(video_frames[0], PIL.Image.Image):
        video_frames = [np.array(frame) for frame in video_frames]

    with imageio.get_writer(
        output_video_path, fps=fps, quality=quality, bitrate=bitrate, macro_block_size=macro_block_size
    ) as writer:
        for frame in video_frames:
            writer.append_data(frame)

    return output_video_path

```

[src/diffusers/utils/export_utils.py](https://github.com/huggingface/diffusers/blob/d5df05ed2a2d310c2e515f5de55bd9e7eb63235d/src/diffusers/utils/export_utils.py#L150-L218) · [More projects using imageio →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20imageio%20for%20video%20capture%2C%20processing%20and%20encoding&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import imageio

with imageio.get_reader('input.mp4', format='FFMPEG') as reader:
    frame = reader.get_data(0)

```

From [examples.html](https://github.com/imageio/imageio/blob/master/imageio/v2.py)

### imageio-ffmpeg

[GitHub](https://github.com/imageio/imageio-ffmpeg) · [PyPI](https://pypi.org/project/imageio-ffmpeg) · [Docs](https://github.com/imageio/imageio-ffmpeg/blob/main/README.md)

Wraps FFmpeg for Python.

- Downloads / mo: 27.1M
- Stars: 306
- Last release: 0.8.1
- License: BSD-2-Clause
- Capabilities: [From the imageio-ffmpeg docs](https://github.com/imageio/imageio-ffmpeg/blob/main/README.md)

```sh
pip install imageio-ffmpeg
```

**nvidia-cosmos/cosmos-reason1** (964 stars)

[nvidia-cosmos/cosmos-reason1](https://github.com/nvidia-cosmos/cosmos-reason1) 

```python
def _write_video(video_tensor, output_path, **ffmpeg_kwargs):
    # Expected channel order is HWC (input is TCHW).
    video_tensor = video_tensor.permute(0, 2, 3, 1).contiguous()
    # This takes the height added for the timestamps into account.
    height, width = video_tensor.shape[1], video_tensor.shape[2]
    generator = imageio_ffmpeg.write_frames(
        output_path,
        size=(width, height),
        **ffmpeg_kwargs,
    )
    try:
        # Seed the generator.
        generator.send(None)
        generator.send(video_tensor.cpu().numpy())
    finally:
        generator.close()

```

[scripts/add_timestamps.py](https://github.com/nvidia-cosmos/cosmos-reason1/blob/b84a3fae3284c375bb0cefab7b53aeb1d5059ab6/scripts/add_timestamps.py#L146-L161) · [More projects using imageio-ffmpeg →](https://dashboard.exa.ai/playground/search?q=imageio-ffmpeg%20GitHub%20projects)

**Quickstart**

```python
from imageio_ffmpeg import read_frames

reader = read_frames('input.mp4')
metadata = next(reader)
frame = next(reader)
reader.close()

```

From [README.md](https://github.com/imageio/imageio-ffmpeg/blob/main/README.md)

### torchvision

[GitHub](https://github.com/pytorch/vision) · [PyPI](https://pypi.org/project/torchvision) · [Docs](https://github.com/pytorch/vision/blob/main/README.md)

Provides image and video datasets and models for PyTorch deep learning.

- Downloads / mo: 18.0M
- Stars: 18.0K
- Last release: 0.29.2
- License: BSD-3-Clause
- Capabilities: [From the torchvision docs](https://github.com/pytorch/vision/blob/main/README.md)

```sh
pip install torch torchvision
```

**open-edge-platform/anomalib** (6.4K stars)

[open-edge-platform/anomalib](https://github.com/open-edge-platform/anomalib) 

```python
def pre_process(self, first_frame: torch.Tensor, last_frame: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """Resize inputs to dimensions required by backbone.

    Args:
        first_frame (torch.Tensor): Starting frame of optical flow computation.
        last_frame (torch.Tensor): Last frame of optical flow computation.

    Returns:
        tuple[torch.Tensor, torch.Tensor]: Preprocessed first and last frame.
    """
    first_frame = F.resize(first_frame, size=[520, 960], antialias=False)
    last_frame = F.resize(last_frame, size=[520, 960], antialias=False)
    return self.transforms(first_frame, last_frame)

```

[src/anomalib/models/video/ai_vad/flow.py](https://github.com/open-edge-platform/anomalib/blob/c3fa8b5b4326a20b2c6b73d91deec624ddd2c434/src/anomalib/models/video/ai_vad/flow.py#L44-L56) · [More projects using torchvision →](https://dashboard.exa.ai/playground/search?q=torchvision%20GitHub%20projects)

**Quickstart**

```python
import torch
from torchvision.transforms.v2 import UniformTemporalSubsample

video = torch.zeros(4, 3, 8, 8)
sampled = UniformTemporalSubsample(num_samples=2)(video)

```

From [_temporal.py](https://github.com/pytorch/vision/blob/main/torchvision/transforms/v2/_temporal.py)

### ffmpeg-python

[GitHub](https://github.com/kkroening/ffmpeg-python) · [PyPI](https://pypi.org/project/ffmpeg-python) · [Docs](https://github.com/kkroening/ffmpeg-python/blob/master/README.md)

Builds FFmpeg input, output, and filter graphs through a Python interface.

- Downloads / mo: 11.1M
- Stars: 11.0K
- Last release: 0.2.0
- License: Apache-2.0
- Capabilities: [From the ffmpeg-python docs](https://github.com/kkroening/ffmpeg-python/blob/master/README.md)

**Strengths**

- **Builds complex filter graphs.** Connect trimming, overlays, and other filters in a Python pipeline.
- **Exposes the generated command.** Inspect get_args or compile before running the pipeline.

**Watch out for**

- **Requires a separate FFmpeg install.** Install FFmpeg and make its executable accessible before running pipelines.
- **Filters can drop audio.** Select and recombine audio explicitly when the filter pipeline drops it.

```sh
pip install ffmpeg-python
```

**xinntao/Real-ESRGAN** (37.5K stars)

[xinntao/Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN) 

```python
def __init__(self, args, audio, height, width, video_save_path, fps):
    out_width, out_height = int(width * args.outscale), int(height * args.outscale)
    if out_height > 2160:
        print('You are generating video that is larger than 4K, which will be very slow due to IO speed.',
              'We highly recommend to decrease the outscale(aka, -s).')

    if audio is not None:
        self.stream_writer = (
            ffmpeg.input('pipe:', format='rawvideo', pix_fmt='bgr24', s=f'{out_width}x{out_height}',
                         framerate=fps).output(
                             audio,
                             video_save_path,
                             pix_fmt='yuv420p',
                             vcodec='libx264',
                             loglevel='error',
                             acodec='copy').overwrite_output().run_async(
                                 pipe_stdin=True, pipe_stdout=True, cmd=args.ffmpeg_bin))
    else:
        self.stream_writer = (
            ffmpeg.input('pipe:', format='rawvideo', pix_fmt='bgr24', s=f'{out_width}x{out_height}',
                         framerate=fps).output(
                             video_save_path, pix_fmt='yuv420p', vcodec='libx264',
                             loglevel='error').overwrite_output().run_async(
                                 pipe_stdin=True, pipe_stdout=True, cmd=args.ffmpeg_bin))

```

[inference_realesrgan_video.py](https://github.com/xinntao/Real-ESRGAN/blob/a4abfb2979a7bbff3f69f58f58ae324608821e27/inference_realesrgan_video.py#L139-L162) · [More projects using ffmpeg-python →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20ffmpeg-python%20for%20video%20capture%2C%20processing%20and%20encoding&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import ffmpeg

stream = ffmpeg.input('input.mp4')
stream = ffmpeg.output(stream, 'output.mp4')
ffmpeg.run(stream)

```

From [README.md](https://github.com/kkroening/ffmpeg-python/blob/master/README.md)

### moviepy

[GitHub](https://github.com/Zulko/moviepy) · [PyPI](https://pypi.org/project/moviepy) · [Docs](https://github.com/Zulko/moviepy/blob/master/README.md)

Edits and combines video clips, audio, titles, and custom effects.

- Downloads / mo: 5.5M
- Stars: 15.2K
- Last release: 2.2.1
- License: MIT
- Capabilities: [From the moviepy docs](https://github.com/Zulko/moviepy/blob/master/README.md)

**Strengths**

- **Combines clips, titles, and audio.** Build an edited video from separate media clips.
- **Supports custom frame effects.** Control video frames and audio when creating effects.

**Watch out for**

- **Cannot stream live video.** Use another tool for webcam capture or live remote rendering.
- **Pure conversion adds overhead.** Call FFmpeg directly when the task only converts video formats.

```sh
pip install moviepy
```

**harry0703/MoneyPrinterTurbo** (144.6K stars)

[harry0703/MoneyPrinterTurbo](https://github.com/harry0703/MoneyPrinterTurbo) 

```python
def _fit_clip_to_canvas(
    clip,
    *,
    target_width: int,
    target_height: int,
    fit_mode: VideoFitMode | str = VideoFitMode.cover,
):
    """Resize a clip to an exact canvas using cover/crop or contain/letterbox."""
    source_width, source_height = (int(value) for value in clip.size)
    target_width = int(target_width)
    target_height = int(target_height)
    if min(source_width, source_height, target_width, target_height) <= 0:
        raise ValueError(
            "video dimensions must be positive: "
            f"source={source_width}x{source_height}, "
            f"target={target_width}x{target_height}"
        )

    mode = VideoFitMode(fit_mode)
    if (source_width, source_height) == (target_width, target_height):
        return clip

    # Exact aspect-ratio matches do not need either a crop or a background.
    if source_width * target_height == source_height * target_width:
        return clip.resized(new_size=(target_width, target_height))

    width_scale = target_width / source_width
    height_scale = target_height / source_height

    if mode == VideoFitMode.cover:
        # ceil guarantees the resized clip covers the complete canvas despite
        # floating-point rounding. Any excess is removed symmetrically.
        scale_factor = max(width_scale, height_scale)
        resized_width = max(target_width, math.ceil(source_width * scale_factor))
        resized_height = max(target_height, math.ceil(source_height * scale_factor))
        resized_clip = clip.resized(new_size=(resized_width, resized_height))
        crop_x = max(0, (resized_width - target_width) // 2)
        crop_y = max(0, (resized_height - target_height) // 2)
        return resized_clip.cropped(
            x1=crop_x,
            y1=crop_y,
            width=target_width,
            height=target_height,
        )

    # contain preserves the legacy behavior: show the complete source frame,
    # centered over a black canvas when the aspect ratios differ.
    scale_factor = min(width_scale, height_scale)
    resized_width = max(1, min(target_width, int(source_width * scale_factor)))
    resized_height = max(1, min(target_height, int(source_height * scale_factor)))
    background = ColorClip(
        size=(target_width, target_height), color=(0, 0, 0)
    ).with_duration(clip.duration)
    resized_clip = clip.resized(
        new_size=(resized_width, resized_height)
    ).with_position("center")
    # bg_color keeps the composite opaque, so MoviePy does not build and encode
    # a full-frame transparency mask for every frame.
    return CompositeVideoClip(
        [background, resized_clip],
        size=(target_width, target_height),
        bg_color=(0, 0, 0),
    ).with_duration(clip.duration)

```

[app/services/video.py](https://github.com/harry0703/MoneyPrinterTurbo/blob/bdd8d328cc366fe70d9fa67ffd0443ba34b4a3e1/app/services/video.py#L916-L978) · [More projects using moviepy →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20moviepy%20for%20video%20capture%2C%20processing%20and%20encoding&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from moviepy import VideoFileClip

with VideoFileClip('input.mp4') as clip:
    frame = clip.get_frame(0)

```

From [quick_presentation.html](https://github.com/Zulko/moviepy/blob/master/README.md)

### torchcodec

[GitHub](https://github.com/meta-pytorch/torchcodec) · [PyPI](https://pypi.org/project/torchcodec) · [Docs](https://github.com/meta-pytorch/torchcodec/blob/main/README.md)

Decodes video for PyTorch.

- Downloads / mo: 4.5M
- Stars: 1.2K
- Last release: 0.17.0
- License: BSD-3-Clause
- Capabilities: [From the torchcodec docs](https://github.com/meta-pytorch/torchcodec/blob/main/README.md)

```sh
pip install torch torchcodec
```

**nvidia-cosmos/cosmos-reason1** (964 stars)

[nvidia-cosmos/cosmos-reason1](https://github.com/nvidia-cosmos/cosmos-reason1) 

```python
def _read_video(video_path):
    decoder = torchcodec.decoders.VideoDecoder(video_path)

    # Pre-allocate output tensor using metadata.
    metadata = decoder.metadata
    num_frames = metadata.num_frames
    height, width = metadata.height, metadata.width
    channels = 3

    # Preallocate tensor: [T, C, H, W].
    video_tensor = torch.empty((num_frames, channels, height, width), dtype=torch.uint8)

    for idx, frame in enumerate(decoder):
        assert frame.shape == (3, height, width)
        video_tensor[idx, ...] = frame

    return video_tensor

```

[scripts/add_timestamps.py](https://github.com/nvidia-cosmos/cosmos-reason1/blob/b84a3fae3284c375bb0cefab7b53aeb1d5059ab6/scripts/add_timestamps.py#L112-L128) · [More projects using torchcodec →](https://dashboard.exa.ai/playground/search?q=torchcodec%20GitHub%20projects)

**Quickstart**

```python
from torchcodec.decoders import VideoDecoder

decoder = VideoDecoder('input.mp4', device='cpu')
frame = decoder[0]

```

From [README.md](https://github.com/meta-pytorch/torchcodec/blob/main/README.md)

## FAQ

### Which Python video processing library should I use?

[av](#av) suits code that works with FFmpeg's libraries directly from Python. [ffmpeg-python](#ffmpeg-python) suits complex filter graphs built as a Python pipeline. [moviepy](#moviepy) suits edits that combine clips, titles, and audio.

### How do I use FFmpeg in Python?

[ffmpeg-python](#ffmpeg-python) builds FFmpeg input, output, and filter graphs through a Python interface. It requires a separate FFmpeg install on the machine.

### What is MoviePy?

[moviepy](#moviepy) edits and combines video clips, audio, titles, and custom effects. It cannot stream live video such as webcam capture.

### What is imageio?

[imageio](#imageio) reads and writes images and video through selectable backend plugins. Video support needs the PyAV or FFmpeg backend installed.

### What is PyAV?

[av](#av) provides Pythonic bindings for FFmpeg's libraries.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python video processing libraries MoviePy OpenCV ffmpeg-python ImageIO code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
