0
# Imagecodecs
1
2
Imagecodecs is a comprehensive Python library for block-oriented, in-memory buffer transformation, compression, and decompression functions specifically designed for scientific image input/output packages. It implements decode and/or encode functions for over 80 different codecs including popular formats like JPEG, PNG, TIFF, WebP, JPEG 2000, JPEG XL, AVIF, HEIF, and numerous compression algorithms including Zlib, LZMA, ZStandard, Blosc, and Brotli.
3
4
## Package Information
5
6
- **Package Name**: imagecodecs
7
- **Language**: Python
8
- **Installation**: `pip install imagecodecs`
9
- **Dependencies**: NumPy (required), various optional C libraries for specific codecs
10
11
## Core Imports
12
13
```python
14
import imagecodecs
15
```
16
17
Common usage patterns:
18
19
```python
20
# Direct codec access
21
import imagecodecs
22
data_compressed = imagecodecs.zlib_encode(data)
23
data_decompressed = imagecodecs.zlib_decode(data_compressed)
24
25
# High-level image I/O
26
import imagecodecs
27
image_array = imagecodecs.imread('image.jpg')
28
imagecodecs.imwrite('output.png', image_array)
29
```
30
31
## Basic Usage
32
33
```python
34
import imagecodecs
35
import numpy as np
36
37
# High-level image reading and writing
38
image = imagecodecs.imread('input.jpg')
39
imagecodecs.imwrite('output.png', image)
40
41
# Direct compression/decompression
42
data = np.random.randint(0, 256, (100, 100), dtype=np.uint8)
43
compressed = imagecodecs.zlib_encode(data)
44
decompressed = imagecodecs.zlib_decode(compressed)
45
46
# Check codec availability
47
if imagecodecs.JPEG.available:
48
encoded = imagecodecs.jpeg_encode(image, level=95)
49
decoded = imagecodecs.jpeg_decode(encoded)
50
51
# Get version information
52
print(imagecodecs.version())
53
```
54
55
## Architecture
56
57
Imagecodecs uses a modular architecture with consistent patterns across all codecs:
58
59
- **Lazy Loading**: Codec modules are loaded on-demand to minimize import time and memory usage
60
- **Consistent API**: All codecs follow the same pattern: `{codec}_encode()`, `{codec}_decode()`, `{codec}_check()`, `{codec}_version()`
61
- **Constants Classes**: Each codec has a constants class with availability checks and configuration enums
62
- **Exception Hierarchy**: Structured exception handling with codec-specific error classes
63
- **NumPy Integration**: Seamless integration with NumPy arrays for efficient data processing
64
- **Numcodecs Compatibility**: Full compatibility with Zarr arrays and numcodecs ecosystem
65
66
## Capabilities
67
68
### Image I/O Functions
69
70
High-level functions for reading and writing image files with automatic codec detection and format conversion.
71
72
```python { .api }
73
def imread(fileobj, /, codec=None, *, memmap=True, return_codec=False, **kwargs):
74
"""
75
Return image array from file.
76
77
Parameters:
78
- fileobj: str | os.PathLike[Any] | bytes | mmap.mmap - File path or data
79
- codec: str | Callable[..., NDArray[Any]] | list[str | Callable[..., NDArray[Any]]] | None - Codec(s) to try for decoding
80
- memmap: bool - Use memory mapping for large files (default True)
81
- return_codec: bool - Return (array, codec) tuple if True (default False)
82
- **kwargs: Additional codec-specific parameters
83
84
Returns:
85
NDArray[Any] | tuple[NDArray[Any], Callable[..., NDArray[Any]]]: Image array or (array, codec) tuple
86
"""
87
88
def imwrite(fileobj, data, /, codec=None, **kwargs):
89
"""
90
Write image array to file.
91
92
Parameters:
93
- fileobj: str | os.PathLike[Any] | IO[bytes] - Output file path
94
- data: ArrayLike - Image data to write
95
- codec: str | Callable[..., bytes | bytearray] | None - Codec for encoding
96
- **kwargs: Additional codec-specific parameters
97
98
Returns:
99
None
100
"""
101
102
def imagefileext():
103
"""
104
Return list of image file extensions handled by imread/imwrite.
105
106
Returns:
107
list[str]: List of supported file extensions
108
"""
109
```
110
111
[Image I/O Functions](./image-io.md)
112
113
### Lossless Compression
114
115
General-purpose lossless compression algorithms optimized for different data types and use cases, including scientific data compression and high-performance columnar storage.
116
117
```python { .api }
118
def zlib_encode(data, level=None, *, out=None):
119
"""
120
Return ZLIB encoded data.
121
122
Parameters:
123
- data: bytes-like - Input data to compress
124
- level: int | None - Compression level (0-9, default 6)
125
- out: bytes | bytearray | None - Output buffer
126
127
Returns:
128
bytes | bytearray: Compressed data
129
"""
130
131
def blosc_encode(data, level=None, *, compressor=None, shuffle=None, typesize=None, blocksize=None, numthreads=None, out=None):
132
"""
133
Return BLOSC encoded data.
134
135
Parameters:
136
- data: bytes-like - Input data to compress
137
- level: int | None - Compression level (0-9)
138
- compressor: str | None - Compression algorithm ('blosclz', 'lz4', 'lz4hc', 'snappy', 'zlib', 'zstd')
139
- shuffle: int | None - Shuffle filter (0=none, 1=byte, 2=bit)
140
- typesize: int | None - Element size for shuffle
141
- blocksize: int | None - Block size in bytes
142
- numthreads: int | None - Number of threads
143
- out: bytes | bytearray | None - Output buffer
144
145
Returns:
146
bytes | bytearray: Compressed data
147
"""
148
149
def zstd_encode(data, level=None, *, out=None):
150
"""
151
Return ZSTD encoded data.
152
153
Parameters:
154
- data: bytes-like - Input data to compress
155
- level: int | None - Compression level (1-22, default 3)
156
- out: bytes | bytearray | None - Output buffer
157
158
Returns:
159
bytes | bytearray: Compressed data
160
"""
161
```
162
163
[Lossless Compression](./lossless-compression.md)
164
165
### Image Formats
166
167
Image-specific codecs for common formats including JPEG, PNG, TIFF, WebP, and next-generation formats like AVIF, HEIF, and JPEG XL.
168
169
```python { .api }
170
def jpeg_encode(data, level=None, *, colorspace=None, outcolorspace=None, subsampling=None, optimize=None, smoothing=None, out=None):
171
"""
172
Return JPEG encoded image.
173
174
Parameters:
175
- data: NDArray - Image data to encode
176
- level: int | None - Quality level (0-100, default 75)
177
- colorspace: str | None - Input color space
178
- outcolorspace: str | None - Output color space
179
- subsampling: str | None - Chroma subsampling ('444', '422', '420', '411')
180
- optimize: bool | None - Optimize Huffman tables
181
- smoothing: int | None - Smoothing factor (0-100)
182
- out: bytes | bytearray | None - Output buffer
183
184
Returns:
185
bytes | bytearray: JPEG encoded image
186
"""
187
188
def png_encode(data, level=None, *, strategy=None, filter=None, out=None):
189
"""
190
Return PNG encoded image.
191
192
Parameters:
193
- data: NDArray - Image data to encode
194
- level: int | None - Compression level (0-9, default 6)
195
- strategy: str | None - Compression strategy
196
- filter: str | None - Row filter type
197
- out: bytes | bytearray | None - Output buffer
198
199
Returns:
200
bytes | bytearray: PNG encoded image
201
"""
202
203
def jpegxl_encode(data, level=None, *, effort=None, distance=None, lossless=None, out=None):
204
"""
205
Return JPEG XL encoded image.
206
207
Parameters:
208
- data: NDArray - Image data to encode
209
- level: int | None - Quality level (0-100) for lossy mode
210
- effort: int | None - Encoding effort (1-9, default 7)
211
- distance: float | None - Psychovisual distance (0.0-25.0)
212
- lossless: bool | None - Use lossless compression
213
- out: bytes | bytearray | None - Output buffer
214
215
Returns:
216
bytes | bytearray: JPEG XL encoded image
217
"""
218
```
219
220
[Image Formats](./image-formats.md)
221
222
### Scientific Data Compression
223
224
Specialized codecs optimized for scientific computing, including floating-point data compression, error-bounded compression, and array processing utilities.
225
226
```python { .api }
227
def zfp_encode(data, *, rate=None, precision=None, tolerance=None, out=None):
228
"""
229
Return ZFP encoded floating-point array.
230
231
Parameters:
232
- data: NDArray - Floating-point array to compress
233
- rate: float | None - Target compression rate in bits per value
234
- precision: int | None - Number of bit planes to encode
235
- tolerance: float | None - Absolute error tolerance
236
- out: bytes | bytearray | None - Output buffer
237
238
Returns:
239
bytes | bytearray: ZFP compressed data
240
"""
241
242
def sperr_encode(data, *, mode=None, quality=None, tolerance=None, out=None):
243
"""
244
Return SPERR encoded floating-point data.
245
246
Parameters:
247
- data: NDArray - Floating-point data to compress
248
- mode: str | None - Compression mode ('rate', 'psnr', 'pwe')
249
- quality: float | None - Quality parameter for chosen mode
250
- tolerance: float | None - Error tolerance
251
- out: bytes | bytearray | None - Output buffer
252
253
Returns:
254
bytes | bytearray: SPERR compressed data
255
"""
256
257
def floatpred_encode(data, *, axis=-1, dist=1, out=None):
258
"""
259
Return floating-point predictor encoded data.
260
261
Parameters:
262
- data: NDArray - Floating-point data to encode
263
- axis: int - Axis along which to apply predictor
264
- dist: int - Predictor distance
265
- out: NDArray | None - Output buffer
266
267
Returns:
268
NDArray: Predictor encoded data
269
"""
270
```
271
272
[Scientific Data Compression](./scientific-compression.md)
273
274
### Array Processing
275
276
Utilities for array transformation, bit manipulation, byte shuffling, and data preparation for compression algorithms.
277
278
```python { .api }
279
def delta_encode(data, *, axis=-1, dist=1, out=None):
280
"""
281
Return delta encoded data.
282
283
Parameters:
284
- data: NDArray - Input array to encode
285
- axis: int - Axis along which to compute differences
286
- dist: int - Distance for delta computation
287
- out: NDArray | None - Output buffer
288
289
Returns:
290
NDArray: Delta encoded data
291
"""
292
293
def bitshuffle_encode(data, *, itemsize=1, blocksize=0, out=None):
294
"""
295
Return bitshuffle encoded data.
296
297
Parameters:
298
- data: bytes-like | NDArray - Input data
299
- itemsize: int - Size of data items in bytes
300
- blocksize: int - Block size for shuffling (default auto)
301
- out: bytes | bytearray | NDArray | None - Output buffer
302
303
Returns:
304
bytes | bytearray | NDArray: Bit-shuffled data
305
"""
306
307
def packints_encode(data, *, out=None):
308
"""
309
Return packed integer array.
310
311
Parameters:
312
- data: NDArray - Integer array to pack
313
- out: NDArray | None - Output buffer
314
315
Returns:
316
NDArray: Packed integer data
317
"""
318
```
319
320
[Array Processing](./array-processing.md)
321
322
### Color Management
323
324
Color space transformations and ICC profile handling using Little-CMS for accurate color reproduction and conversion between different color spaces.
325
326
```python { .api }
327
def cms_transform(data, profile, outprofile, *, colorspace=None, outcolorspace=None, intent=None, out=None):
328
"""
329
Return color-transformed array.
330
331
Parameters:
332
- data: NDArray - Image data to transform
333
- profile: bytes | str - Input ICC profile or color space name
334
- outprofile: bytes | str - Output ICC profile or color space name
335
- colorspace: str | None - Input color space interpretation
336
- outcolorspace: str | None - Output color space interpretation
337
- intent: str | None - Rendering intent ('perceptual', 'relative', 'saturation', 'absolute')
338
- out: NDArray | None - Output buffer
339
340
Returns:
341
NDArray: Color-transformed image data
342
"""
343
344
def cms_profile(profile, *, whitepoint=None, primaries=None, transferfunction=None, gamma=None):
345
"""
346
Return ICC profile.
347
348
Parameters:
349
- profile: str - Profile type ('srgb', 'adobe_rgb', 'prophoto_rgb', etc.)
350
- whitepoint: tuple | None - White point coordinates
351
- primaries: tuple | None - Color primaries
352
- transferfunction: str | None - Transfer function type
353
- gamma: float | None - Gamma value
354
355
Returns:
356
bytes: ICC profile data
357
"""
358
```
359
360
[Color Management](./color-management.md)
361
362
### Utilities and Metadata
363
364
Package information, version checking, codec availability testing, and checksum functions for data integrity verification.
365
366
```python { .api }
367
def version(astype=None, /):
368
"""
369
Return version information about all codecs and dependencies.
370
371
All extension modules are imported into the process during this call.
372
373
Parameters:
374
- astype: type | None - Return type (str, tuple, dict)
375
376
Returns:
377
str | tuple[str, ...] | dict[str, str]: Version information
378
"""
379
380
def h5checksum_fletcher32(data, value=None):
381
"""
382
Return Fletcher-32 checksum.
383
384
Parameters:
385
- data: bytes-like - Data to checksum
386
- value: int | None - Initial checksum value
387
388
Returns:
389
int: Fletcher-32 checksum
390
"""
391
392
class DelayedImportError(ImportError):
393
"""Delayed ImportError for optional codec dependencies."""
394
395
def __init__(self, name: str) -> None: ...
396
```
397
398
[Utilities and Metadata](./utilities.md)
399
400
## Types
401
402
```python { .api }
403
from typing import Any, Callable, IO, Literal, overload
404
from numpy.typing import ArrayLike, DTypeLike, NDArray
405
import os
406
import mmap
407
408
BytesLike = bytes | bytearray | mmap.mmap
409
410
# Codec constants classes
411
class JPEG:
412
available: bool # True if JPEG codec is available
413
414
class PNG:
415
available: bool # True if PNG codec is available
416
417
class ZLIB:
418
available: bool # True if ZLIB codec is available
419
420
class WEBP:
421
available: bool # True if WebP codec is available
422
423
class AVIF:
424
available: bool # True if AVIF codec is available
425
426
class BLOSC:
427
available: bool # True if BLOSC codec is available
428
429
class ZSTD:
430
available: bool # True if ZSTD codec is available
431
432
# Generic codec constants base class pattern
433
class CodecConstants:
434
available: bool # True if codec is available
435
436
# Exception hierarchy
437
class ImcdError(Exception):
438
"""Base IMCD codec exception."""
439
440
class DelayedImportError(ImportError):
441
"""Delayed ImportError for lazy loading."""
442
443
def __init__(self, name: str) -> None: ...
444
445
# Codec-specific exception classes
446
class JpegError(ImcdError):
447
"""JPEG codec exception."""
448
449
class PngError(ImcdError):
450
"""PNG codec exception."""
451
452
class ZlibError(ImcdError):
453
"""ZLIB codec exception."""
454
455
class WebpError(ImcdError):
456
"""WebP codec exception."""
457
458
class AvifError(ImcdError):
459
"""AVIF codec exception."""
460
461
class BloscError(ImcdError):
462
"""BLOSC codec exception."""
463
464
class ZstdError(ImcdError):
465
"""ZSTD codec exception."""
466
```