0
# Multi-Image Operations
1
2
Handle sequences of images like GIF animations, TIFF stacks, multi-page PDFs, or video frames with built-in memory management and batch processing capabilities.
3
4
## Capabilities
5
6
### Multiple Image Reading
7
8
Read all images from a multi-image file, with automatic memory protection to prevent system overload.
9
10
```python { .api }
11
def mimread(uri, format=None, memtest="256MB", **kwargs):
12
"""
13
Read multiple images from the specified file.
14
15
Parameters:
16
- uri (ImageResource): File path, URL, bytes, or file object
17
- format (str, optional): Format to use for reading
18
- memtest (bool|int|float|str): Memory limit protection
19
- bool: True uses default limit, False disables
20
- int/float: Byte threshold
21
- str: Human-readable size ('256MB', '1GB', '500MiB')
22
- **kwargs: Format-specific parameters
23
24
Returns:
25
- List[Array]: List of numpy arrays, each with 'meta' attribute
26
27
Raises:
28
- RuntimeError: If memory limit exceeded
29
30
Note: Default memory limit is 256MB to prevent system swapping
31
"""
32
```
33
34
**Usage Examples:**
35
36
```python
37
import imageio.v2 as imageio
38
39
# Read GIF animation frames
40
frames = imageio.mimread('animation.gif')
41
print(f"Number of frames: {len(frames)}")
42
for i, frame in enumerate(frames):
43
print(f"Frame {i}: {frame.shape}")
44
45
# Read TIFF stack with memory limit
46
stack = imageio.mimread('microscopy_stack.tiff', memtest='512MB')
47
48
# Read without memory protection (use carefully!)
49
large_stack = imageio.mimread('huge_dataset.tiff', memtest=False)
50
51
# Read with custom memory limit
52
frames = imageio.mimread('video.mp4', memtest=1000000000) # 1GB limit
53
```
54
55
### Multiple Image Writing
56
57
Write a sequence of images as an animation, stack, or multi-page document.
58
59
```python { .api }
60
def mimwrite(uri, ims, format=None, **kwargs):
61
"""
62
Write multiple images to the specified file.
63
64
Parameters:
65
- uri (ImageResource): Output path or '<bytes>' for byte return
66
- ims (Sequence[ArrayLike]): Sequence of image arrays
67
- format (str, optional): Format to use for writing
68
- **kwargs: Format-specific parameters
69
70
Returns:
71
- None: When writing to file
72
- bytes: When uri is '<bytes>'
73
74
Raises:
75
- ValueError: If ims is not a sequence of arrays
76
77
Note: Each array must be NxM, NxMx3, or NxMx4
78
"""
79
```
80
81
**Usage Examples:**
82
83
```python
84
import imageio.v2 as imageio
85
import numpy as np
86
87
# Create sample frames
88
frames = []
89
for i in range(10):
90
# Create animated pattern
91
frame = np.zeros((100, 100, 3), dtype=np.uint8)
92
frame[i*10:(i+1)*10, :] = [255, 0, 0] # Moving red bar
93
frames.append(frame)
94
95
# Write as GIF animation
96
imageio.mimwrite('animation.gif', frames, duration=0.5)
97
98
# Write as MP4 video
99
imageio.mimwrite('animation.mp4', frames, fps=20)
100
101
# Write as multi-page TIFF
102
imageio.mimwrite('stack.tiff', frames)
103
104
# Get as bytes
105
gif_bytes = imageio.mimwrite('<bytes>', frames, format='GIF', duration=0.2)
106
```
107
108
## Format-Specific Features
109
110
### GIF Animations
111
112
Create and customize GIF animations with frame timing and optimization:
113
114
```python
115
# Basic GIF with uniform timing
116
imageio.mimwrite('basic.gif', frames, duration=0.5)
117
118
# Variable frame timing
119
durations = [0.1, 0.2, 0.1, 0.3, 0.1] # Per-frame durations
120
imageio.mimwrite('variable.gif', frames[:5], duration=durations)
121
122
# Optimized GIF with color quantization
123
imageio.mimwrite('optimized.gif', frames,
124
duration=0.1, quantizer='nq', palettesize=256)
125
126
# Infinite loop GIF
127
imageio.mimwrite('loop.gif', frames, duration=0.2, loop=0)
128
```
129
130
### Video Files (MP4, AVI, etc.)
131
132
Create video files using FFmpeg backend:
133
134
```python
135
# Basic MP4 video
136
imageio.mimwrite('video.mp4', frames, fps=30)
137
138
# High-quality video with custom codec
139
imageio.mimwrite('hq_video.mp4', frames,
140
fps=60, codec='libx264', quality=8)
141
142
# AVI with specific codec
143
imageio.mimwrite('video.avi', frames,
144
fps=25, codec='mjpeg')
145
146
# Control bitrate and other parameters
147
imageio.mimwrite('custom.mp4', frames,
148
fps=30, bitrate='2M', preset='slow')
149
```
150
151
### TIFF Stacks
152
153
Handle multi-page TIFF files common in microscopy and scientific imaging:
154
155
```python
156
# Basic TIFF stack
157
imageio.mimwrite('stack.tiff', frames)
158
159
# Compressed TIFF stack
160
imageio.mimwrite('compressed.tiff', frames, compression='lzw')
161
162
# 16-bit TIFF stack
163
frames_16bit = [frame.astype(np.uint16) * 256 for frame in frames]
164
imageio.mimwrite('16bit_stack.tiff', frames_16bit)
165
166
# TIFF with metadata
167
imageio.mimwrite('meta_stack.tiff', frames,
168
resolution=(300, 300), software='ImageIO')
169
```
170
171
## Memory Management
172
173
### Understanding Memory Limits
174
175
The `memtest` parameter prevents excessive memory usage:
176
177
```python
178
# Size unit examples
179
imageio.mimread('file.tiff', memtest='100MB') # 100 megabytes
180
imageio.mimread('file.tiff', memtest='2GB') # 2 gigabytes
181
imageio.mimread('file.tiff', memtest='512MiB') # 512 mebibytes (binary)
182
imageio.mimread('file.tiff', memtest='1.5GB') # 1.5 gigabytes
183
184
# Numeric limits (in bytes)
185
imageio.mimread('file.tiff', memtest=1000000) # 1 million bytes
186
imageio.mimread('file.tiff', memtest=2**30) # 1 GiB in bytes
187
```
188
189
### Handling Large Datasets
190
191
For large multi-image files, consider using readers for sequential access:
192
193
```python
194
# Instead of loading all frames at once
195
try:
196
frames = imageio.mimread('huge_video.mp4') # May fail with memory error
197
except RuntimeError as e:
198
print(f"Memory limit exceeded: {e}")
199
200
# Use reader for sequential processing
201
reader = imageio.get_reader('huge_video.mp4')
202
processed_frames = []
203
204
for i, frame in enumerate(reader):
205
# Process frame individually
206
processed = process_frame(frame) # Your processing function
207
processed_frames.append(processed)
208
209
# Optional: limit number of frames processed
210
if i >= 100:
211
break
212
213
reader.close()
214
```
215
216
## Advanced Usage
217
218
### Batch Processing
219
220
Process multiple multi-image files efficiently:
221
222
```python
223
import os
224
from pathlib import Path
225
226
def process_image_sequence(input_path, output_path):
227
"""Process a multi-image file and save result."""
228
try:
229
frames = imageio.mimread(input_path, memtest='1GB')
230
231
# Apply processing to each frame
232
processed = []
233
for frame in frames:
234
# Example: convert to grayscale
235
if len(frame.shape) == 3:
236
gray = np.mean(frame, axis=2).astype(frame.dtype)
237
processed.append(gray)
238
else:
239
processed.append(frame)
240
241
# Save processed sequence
242
imageio.mimwrite(output_path, processed)
243
return True
244
245
except Exception as e:
246
print(f"Error processing {input_path}: {e}")
247
return False
248
249
# Process multiple files
250
input_dir = Path('input_sequences')
251
output_dir = Path('processed_sequences')
252
output_dir.mkdir(exist_ok=True)
253
254
for file_path in input_dir.glob('*.gif'):
255
output_path = output_dir / f"processed_{file_path.name}"
256
success = process_image_sequence(file_path, output_path)
257
print(f"{'✓' if success else '✗'} {file_path.name}")
258
```
259
260
### Format Detection and Conversion
261
262
Convert between different multi-image formats:
263
264
```python
265
def convert_multi_format(input_file, output_file, **kwargs):
266
"""Convert multi-image file between formats."""
267
# Read with automatic format detection
268
frames = imageio.mimread(input_file)
269
270
# Write with format determined by output extension
271
imageio.mimwrite(output_file, frames, **kwargs)
272
273
# Convert GIF to MP4
274
convert_multi_format('animation.gif', 'animation.mp4', fps=30)
275
276
# Convert video to GIF with custom settings
277
convert_multi_format('video.mp4', 'animation.gif',
278
duration=0.1, quantizer='wu')
279
280
# Convert TIFF stack to individual images
281
frames = imageio.mimread('stack.tiff')
282
for i, frame in enumerate(frames):
283
imageio.imwrite(f'frame_{i:03d}.png', frame)
284
```