0
# Image I/O Operations
1
2
Core functionality for reading and writing single images with support for all major image formats, automatic format detection, and metadata preservation.
3
4
## Capabilities
5
6
### Single Image Reading
7
8
Read a single image from various sources including files, URLs, bytes, and file objects. Returns a numpy array with metadata attached.
9
10
```python { .api }
11
def imread(uri, format=None, **kwargs):
12
"""
13
Read an image 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
- **kwargs: Format-specific parameters
19
20
Returns:
21
- Array: NumPy array with 'meta' attribute containing metadata
22
23
Note: Main imageio.imread shows deprecation warning, use imageio.v2.imread
24
"""
25
```
26
27
**Usage Examples:**
28
29
```python
30
import imageio.v2 as imageio
31
32
# Read from file path
33
image = imageio.imread('photo.jpg')
34
print(f"Shape: {image.shape}, dtype: {image.dtype}")
35
print(f"Metadata: {image.meta}")
36
37
# Read from URL
38
image = imageio.imread('https://example.com/image.png')
39
40
# Read with specific format
41
image = imageio.imread('data.raw', format='RAW-FI')
42
43
# Read from bytes
44
with open('image.jpg', 'rb') as f:
45
data = f.read()
46
image = imageio.imread(data)
47
```
48
49
### Single Image Writing
50
51
Write a single image to file or return as bytes. Supports automatic format detection based on file extension.
52
53
```python { .api }
54
def imwrite(uri, im, format=None, **kwargs):
55
"""
56
Write an image to the specified file.
57
58
Parameters:
59
- uri (ImageResource): Output path or '<bytes>' for byte return
60
- im (ArrayLike): Image data as numpy array (NxM, NxMx3, or NxMx4)
61
- format (str, optional): Format to use for writing
62
- **kwargs: Format-specific parameters (quality, compression, etc.)
63
64
Returns:
65
- None: When writing to file
66
- bytes: When uri is '<bytes>'
67
68
Raises:
69
- ValueError: If image dimensions are invalid
70
"""
71
```
72
73
**Usage Examples:**
74
75
```python
76
import imageio.v2 as imageio
77
import numpy as np
78
79
# Create sample image
80
image = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)
81
82
# Write to file (format auto-detected from extension)
83
imageio.imwrite('output.png', image)
84
85
# Write with specific format and quality
86
imageio.imwrite('output.jpg', image, format='JPEG', quality=95)
87
88
# Get image as bytes
89
png_bytes = imageio.imwrite('<bytes>', image, format='PNG')
90
91
# Write grayscale image
92
gray_image = np.random.randint(0, 255, (100, 100), dtype=np.uint8)
93
imageio.imwrite('gray.png', gray_image)
94
95
# Write with transparency (RGBA)
96
rgba_image = np.random.randint(0, 255, (100, 100, 4), dtype=np.uint8)
97
imageio.imwrite('transparent.png', rgba_image)
98
```
99
100
### Format-Specific Parameters
101
102
Different formats support various parameters for fine-tuning the I/O operations:
103
104
**JPEG Parameters:**
105
- `quality` (int): JPEG quality (0-100, default varies)
106
- `optimize` (bool): Optimize Huffman tables
107
- `progressive` (bool): Save as progressive JPEG
108
109
**PNG Parameters:**
110
- `compress_level` (int): Compression level (0-9)
111
- `optimize` (bool): Optimize palette
112
113
**TIFF Parameters:**
114
- `compression` (str): Compression type ('lzw', 'jpeg', 'packbits', etc.)
115
- `photometric` (str): Photometric interpretation
116
117
**Example with format parameters:**
118
119
```python
120
# High-quality JPEG with optimization
121
imageio.imwrite('high_quality.jpg', image,
122
quality=98, optimize=True, progressive=True)
123
124
# Compressed PNG
125
imageio.imwrite('compressed.png', image,
126
compress_level=9, optimize=True)
127
128
# TIFF with LZW compression
129
imageio.imwrite('compressed.tiff', image,
130
compression='lzw')
131
```
132
133
## Advanced Features
134
135
### Metadata Preservation
136
137
Images read with ImageIO retain metadata in the `meta` attribute:
138
139
```python
140
image = imageio.imread('photo_with_exif.jpg')
141
print("EXIF data:", image.meta.get('exif', {}))
142
print("Image description:", image.meta.get('description', ''))
143
144
# Metadata varies by format:
145
# JPEG: exif, jfif, adobe, comment
146
# PNG: gamma, transparency, text chunks
147
# TIFF: extensive tag information
148
```
149
150
### Data Type Handling
151
152
ImageIO preserves original data types and bit depths:
153
154
```python
155
# 16-bit TIFF
156
image_16bit = imageio.imread('16bit_image.tiff')
157
print(f"Data type: {image_16bit.dtype}") # e.g., uint16
158
159
# 32-bit float TIFF
160
float_image = imageio.imread('float_data.tiff')
161
print(f"Data type: {float_image.dtype}") # e.g., float32
162
163
# Note: Unlike PIL, ImageIO preserves original bit depth
164
```
165
166
### Error Handling
167
168
Common error scenarios and handling:
169
170
```python
171
try:
172
image = imageio.imread('nonexistent.jpg')
173
except FileNotFoundError:
174
print("File not found")
175
176
try:
177
image = imageio.imread('corrupted.jpg')
178
except Exception as e:
179
print(f"Read error: {e}")
180
181
try:
182
# Invalid image dimensions
183
invalid_image = np.random.rand(100) # 1D array
184
imageio.imwrite('output.jpg', invalid_image)
185
except ValueError as e:
186
print(f"Invalid image dimensions: {e}")
187
```