mediapy
mediapy is a Python library designed to simplify reading, writing, and displaying images and videos, especially within IPython/Jupyter notebooks. Developed by Google LLC, it is currently on version 1.2.6 and receives updates periodically.
Warnings
- gotcha Video input/output operations (e.g., `read_video`, `write_video`, `show_video`) are dependent on the external `ffmpeg` command-line tool. It must be installed on your system and accessible in the system's PATH, otherwise a `RuntimeError` will be raised.
- gotcha When displaying videos with `media.show_video` after reading them with `media.read_video`, the framerate might not always be automatically detected or correctly applied. For accurate playback speed, it's recommended to explicitly pass the `fps` argument to `show_video` using `video.metadata.fps`.
- breaking Version 1.2.1 introduced an incompatibility with Python 3.8 due to the use of `os.PathLike[str]`, which was not subscriptable in Python 3.8 at the time. This caused `TypeError: 'ABCMeta' object is not subscriptable`.
Install
-
pip install mediapy
Imports
- mediapy
import mediapy as media
Quickstart
import mediapy as media
import numpy as np
import shutil
import os
# --- Image Example ---
image_url = 'https://github.com/hhoppe/data/raw/main/image.png'
print(f"Reading image from: {image_url}")
image = media.read_image(image_url)
print(f"Image shape: {image.shape}, dtype: {image.dtype}")
media.show_image(image, title='Remote Image')
# Example of creating and saving an image
checkerboard = np.kron([[0, 1] * 16, [1, 0] * 16] * 16, np.ones((4, 4)))
output_image_path = '/tmp/checkerboard.png'
media.write_image(output_image_path, checkerboard)
print(f"\nCheckerboard image written to {output_image_path}")
# --- Video Example (requires ffmpeg) ---
if shutil.which('ffmpeg'):
video_url = 'https://github.com/hhoppe/data/raw/main/video.mp4'
print(f"\nReading video from: {video_url}")
video = media.read_video(video_url)
print(f"Video shape: {video.shape}, dtype: {video.dtype}")
if hasattr(video, 'metadata') and hasattr(video.metadata, 'fps'):
print(f"Video framerate: {video.metadata.fps} fps")
media.show_video(video, title='Remote Video', fps=video.metadata.fps)
else:
media.show_video(video, title='Remote Video - FPS unknown')
else:
print("\nFFmpeg is not installed or not in PATH. Skipping video example.")
print("Please install ffmpeg (e.g., 'brew install ffmpeg' on macOS, 'apt install ffmpeg' on Debian/Ubuntu) for video functionality.")