0
# Image Sequences
1
2
Animation and multi-frame image support for iterating through frames in animated GIFs, multi-page TIFFs, and other sequence-based image formats.
3
4
## Capabilities
5
6
### Frame Iterator
7
8
Iterate through frames in multi-frame images with support for both sequential iteration and random access.
9
10
```python { .api }
11
class Iterator:
12
def __init__(self, im: Image.Image) -> None:
13
"""
14
Create an iterator for an image sequence.
15
16
Parameters:
17
- im: Image object with seek capability (animated GIF, multi-page TIFF, etc.)
18
19
Raises:
20
AttributeError: If the image doesn't support seeking (no seek method)
21
"""
22
23
def __getitem__(self, ix: int) -> Image.Image:
24
"""
25
Access a specific frame by index.
26
27
Parameters:
28
- ix: Frame index (0-based)
29
30
Returns:
31
Image.Image: The image positioned at the specified frame
32
33
Raises:
34
IndexError: If the frame index is out of range
35
"""
36
37
def __iter__(self) -> Iterator:
38
"""
39
Return the iterator object itself.
40
41
Returns:
42
Iterator: Self for iteration protocol
43
"""
44
45
def __next__(self) -> Image.Image:
46
"""
47
Get the next frame in the sequence.
48
49
Returns:
50
Image.Image: The next frame in the sequence
51
52
Raises:
53
StopIteration: When the end of the sequence is reached
54
"""
55
```
56
57
### Bulk Frame Processing
58
59
Process all frames in an image sequence with optional transformation functions.
60
61
```python { .api }
62
def all_frames(
63
im: Image.Image | list[Image.Image],
64
func: Callable[[Image.Image], Image.Image] | None = None,
65
) -> list[Image.Image]:
66
"""
67
Extract all frames from an image sequence, optionally applying a function to each.
68
69
Parameters:
70
- im: Single image object or list of image objects
71
- func: Optional function to apply to each frame
72
73
Returns:
74
list[Image.Image]: List of all frames (copied) with optional transformation applied
75
76
Note:
77
- Original image position is restored after processing
78
- All returned frames are copies, safe to modify independently
79
- Function is applied to each frame if provided
80
"""
81
```
82
83
### Usage Examples
84
85
```python
86
from PIL import Image, ImageSequence
87
88
# Open an animated GIF
89
gif = Image.open("animated.gif")
90
91
# Iterate through all frames
92
for frame in ImageSequence.Iterator(gif):
93
# Process each frame
94
print(f"Frame size: {frame.size}")
95
# frame is the same Image object, positioned at different frames
96
97
# Access specific frames by index
98
iterator = ImageSequence.Iterator(gif)
99
first_frame = iterator[0] # First frame
100
third_frame = iterator[2] # Third frame
101
102
# Get all frames as separate Image objects
103
all_frame_copies = ImageSequence.all_frames(gif)
104
print(f"Total frames: {len(all_frame_copies)}")
105
106
# Apply transformation to all frames
107
def resize_frame(frame):
108
return frame.resize((100, 100))
109
110
resized_frames = ImageSequence.all_frames(gif, resize_frame)
111
112
# Process multiple images at once
113
images = [gif1, gif2, gif3]
114
all_frames_from_multiple = ImageSequence.all_frames(images)
115
116
# Practical example: Extract frames for analysis
117
gif = Image.open("animation.gif")
118
frames = ImageSequence.all_frames(gif)
119
120
# Analyze each frame individually
121
for i, frame in enumerate(frames):
122
# Save individual frames
123
frame.save(f"frame_{i:03d}.png")
124
125
# Get frame statistics
126
mean_color = frame.convert("RGB").resize((1, 1)).getpixel((0, 0))
127
print(f"Frame {i} average color: {mean_color}")
128
129
# Working with multi-page TIFF
130
tiff = Image.open("multipage.tiff")
131
for page_num, page in enumerate(ImageSequence.Iterator(tiff)):
132
print(f"Page {page_num}: {page.size}, {page.mode}")
133
page.save(f"page_{page_num}.png")
134
```
135
136
### Supported Formats
137
138
The ImageSequence module works with any image format that supports multiple frames or pages:
139
140
- **Animated GIF**: Multiple animation frames
141
- **Multi-page TIFF**: Multiple pages/layers
142
- **ICO files**: Multiple icon sizes
143
- **ICNS files**: Multiple icon representations
144
- **Some PNG files**: With animation extensions
145
146
### Iterator Behavior
147
148
- **Position Management**: Iterator tracks current position automatically
149
- **Reusable**: Can be used multiple times, resets to beginning each iteration
150
- **Index Access**: Supports `iterator[index]` syntax for random access
151
- **Memory Efficient**: Reuses the same Image object, just changing its frame position
152
153
### Frame Extraction Notes
154
155
- `all_frames()` creates **copies** of each frame, safe for independent modification
156
- Original image's frame position is restored after `all_frames()` completes
157
- Frames are extracted in sequence order (0, 1, 2, ...)
158
- Optional transformation function is applied after frame extraction but before copying