Library for reading and writing a wide range of image, video, scientific, and volumetric data formats.
—
Handle sequences of images like GIF animations, TIFF stacks, multi-page PDFs, or video frames with built-in memory management and batch processing capabilities.
Read all images from a multi-image file, with automatic memory protection to prevent system overload.
def mimread(uri, format=None, memtest="256MB", **kwargs):
"""
Read multiple images from the specified file.
Parameters:
- uri (ImageResource): File path, URL, bytes, or file object
- format (str, optional): Format to use for reading
- memtest (bool|int|float|str): Memory limit protection
- bool: True uses default limit, False disables
- int/float: Byte threshold
- str: Human-readable size ('256MB', '1GB', '500MiB')
- **kwargs: Format-specific parameters
Returns:
- List[Array]: List of numpy arrays, each with 'meta' attribute
Raises:
- RuntimeError: If memory limit exceeded
Note: Default memory limit is 256MB to prevent system swapping
"""Usage Examples:
import imageio.v2 as imageio
# Read GIF animation frames
frames = imageio.mimread('animation.gif')
print(f"Number of frames: {len(frames)}")
for i, frame in enumerate(frames):
print(f"Frame {i}: {frame.shape}")
# Read TIFF stack with memory limit
stack = imageio.mimread('microscopy_stack.tiff', memtest='512MB')
# Read without memory protection (use carefully!)
large_stack = imageio.mimread('huge_dataset.tiff', memtest=False)
# Read with custom memory limit
frames = imageio.mimread('video.mp4', memtest=1000000000) # 1GB limitWrite a sequence of images as an animation, stack, or multi-page document.
def mimwrite(uri, ims, format=None, **kwargs):
"""
Write multiple images to the specified file.
Parameters:
- uri (ImageResource): Output path or '<bytes>' for byte return
- ims (Sequence[ArrayLike]): Sequence of image arrays
- format (str, optional): Format to use for writing
- **kwargs: Format-specific parameters
Returns:
- None: When writing to file
- bytes: When uri is '<bytes>'
Raises:
- ValueError: If ims is not a sequence of arrays
Note: Each array must be NxM, NxMx3, or NxMx4
"""Usage Examples:
import imageio.v2 as imageio
import numpy as np
# Create sample frames
frames = []
for i in range(10):
# Create animated pattern
frame = np.zeros((100, 100, 3), dtype=np.uint8)
frame[i*10:(i+1)*10, :] = [255, 0, 0] # Moving red bar
frames.append(frame)
# Write as GIF animation
imageio.mimwrite('animation.gif', frames, duration=0.5)
# Write as MP4 video
imageio.mimwrite('animation.mp4', frames, fps=20)
# Write as multi-page TIFF
imageio.mimwrite('stack.tiff', frames)
# Get as bytes
gif_bytes = imageio.mimwrite('<bytes>', frames, format='GIF', duration=0.2)Create and customize GIF animations with frame timing and optimization:
# Basic GIF with uniform timing
imageio.mimwrite('basic.gif', frames, duration=0.5)
# Variable frame timing
durations = [0.1, 0.2, 0.1, 0.3, 0.1] # Per-frame durations
imageio.mimwrite('variable.gif', frames[:5], duration=durations)
# Optimized GIF with color quantization
imageio.mimwrite('optimized.gif', frames,
duration=0.1, quantizer='nq', palettesize=256)
# Infinite loop GIF
imageio.mimwrite('loop.gif', frames, duration=0.2, loop=0)Create video files using FFmpeg backend:
# Basic MP4 video
imageio.mimwrite('video.mp4', frames, fps=30)
# High-quality video with custom codec
imageio.mimwrite('hq_video.mp4', frames,
fps=60, codec='libx264', quality=8)
# AVI with specific codec
imageio.mimwrite('video.avi', frames,
fps=25, codec='mjpeg')
# Control bitrate and other parameters
imageio.mimwrite('custom.mp4', frames,
fps=30, bitrate='2M', preset='slow')Handle multi-page TIFF files common in microscopy and scientific imaging:
# Basic TIFF stack
imageio.mimwrite('stack.tiff', frames)
# Compressed TIFF stack
imageio.mimwrite('compressed.tiff', frames, compression='lzw')
# 16-bit TIFF stack
frames_16bit = [frame.astype(np.uint16) * 256 for frame in frames]
imageio.mimwrite('16bit_stack.tiff', frames_16bit)
# TIFF with metadata
imageio.mimwrite('meta_stack.tiff', frames,
resolution=(300, 300), software='ImageIO')The memtest parameter prevents excessive memory usage:
# Size unit examples
imageio.mimread('file.tiff', memtest='100MB') # 100 megabytes
imageio.mimread('file.tiff', memtest='2GB') # 2 gigabytes
imageio.mimread('file.tiff', memtest='512MiB') # 512 mebibytes (binary)
imageio.mimread('file.tiff', memtest='1.5GB') # 1.5 gigabytes
# Numeric limits (in bytes)
imageio.mimread('file.tiff', memtest=1000000) # 1 million bytes
imageio.mimread('file.tiff', memtest=2**30) # 1 GiB in bytesFor large multi-image files, consider using readers for sequential access:
# Instead of loading all frames at once
try:
frames = imageio.mimread('huge_video.mp4') # May fail with memory error
except RuntimeError as e:
print(f"Memory limit exceeded: {e}")
# Use reader for sequential processing
reader = imageio.get_reader('huge_video.mp4')
processed_frames = []
for i, frame in enumerate(reader):
# Process frame individually
processed = process_frame(frame) # Your processing function
processed_frames.append(processed)
# Optional: limit number of frames processed
if i >= 100:
break
reader.close()Process multiple multi-image files efficiently:
import os
from pathlib import Path
def process_image_sequence(input_path, output_path):
"""Process a multi-image file and save result."""
try:
frames = imageio.mimread(input_path, memtest='1GB')
# Apply processing to each frame
processed = []
for frame in frames:
# Example: convert to grayscale
if len(frame.shape) == 3:
gray = np.mean(frame, axis=2).astype(frame.dtype)
processed.append(gray)
else:
processed.append(frame)
# Save processed sequence
imageio.mimwrite(output_path, processed)
return True
except Exception as e:
print(f"Error processing {input_path}: {e}")
return False
# Process multiple files
input_dir = Path('input_sequences')
output_dir = Path('processed_sequences')
output_dir.mkdir(exist_ok=True)
for file_path in input_dir.glob('*.gif'):
output_path = output_dir / f"processed_{file_path.name}"
success = process_image_sequence(file_path, output_path)
print(f"{'✓' if success else '✗'} {file_path.name}")Convert between different multi-image formats:
def convert_multi_format(input_file, output_file, **kwargs):
"""Convert multi-image file between formats."""
# Read with automatic format detection
frames = imageio.mimread(input_file)
# Write with format determined by output extension
imageio.mimwrite(output_file, frames, **kwargs)
# Convert GIF to MP4
convert_multi_format('animation.gif', 'animation.mp4', fps=30)
# Convert video to GIF with custom settings
convert_multi_format('video.mp4', 'animation.gif',
duration=0.1, quantizer='wu')
# Convert TIFF stack to individual images
frames = imageio.mimread('stack.tiff')
for i, frame in enumerate(frames):
imageio.imwrite(f'frame_{i:03d}.png', frame)Install with Tessl CLI
npx tessl i tessl/pypi-imageio