Image transformation, compression, and decompression codecs for scientific computing
—
High-level functions for reading and writing image files with automatic codec detection, format conversion, and memory-efficient processing. These functions provide a convenient interface for working with various image formats without needing to know the specific codec details.
Read image data from files or byte streams with automatic format detection and codec selection.
def imread(fileobj, /, codec=None, *, memmap=True, return_codec=False, **kwargs):
"""
Return image array from file.
Parameters:
- fileobj: str | os.PathLike[Any] | bytes | mmap.mmap - File path, file-like object, or bytes data
- codec: str | Callable[..., NDArray[Any]] | list[str | Callable[..., NDArray[Any]]] | None -
Codec name(s) or decoder function(s) to try. If None, auto-detect from file extension/content
- memmap: bool - Use memory mapping for large files (default True)
- return_codec: bool - If True, return (array, codec_function) tuple (default False)
- **kwargs: Additional codec-specific parameters passed to decoder
Returns:
NDArray[Any] | tuple[NDArray[Any], Callable[..., NDArray[Any]]]: Image array or (array, codec) tuple
Raises:
FileNotFoundError: If file path does not exist
DelayedImportError: If required codec is not available
Various codec-specific exceptions: For decoding errors
"""Usage Examples:
import imagecodecs
import numpy as np
# Basic image reading
image = imagecodecs.imread('photo.jpg')
print(f"Image shape: {image.shape}, dtype: {image.dtype}")
# Read with specific codec
image = imagecodecs.imread('data.tiff', codec='tiff')
# Try multiple codecs in order
image = imagecodecs.imread('unknown.bin', codec=['tiff', 'png', 'jpeg'])
# Memory-mapped reading for large files
large_image = imagecodecs.imread('huge_image.tiff', memmap=True)
# Get codec information
image, codec_func = imagecodecs.imread('photo.jpg', return_codec=True)
print(f"Used codec: {codec_func.__name__}")
# Codec-specific parameters
jpeg_image = imagecodecs.imread('photo.jpg', colorspace='rgb')
tiff_image = imagecodecs.imread('data.tiff', key=0) # Read specific TIFF pageWrite image arrays to files with automatic format selection based on file extension or explicit codec specification.
def imwrite(fileobj, data, /, codec=None, **kwargs):
"""
Write image array to file.
Parameters:
- fileobj: str | os.PathLike[Any] | IO[bytes] - Output file path
- data: ArrayLike - Image data to write (2D or 3D array)
- codec: str | Callable[..., bytes | bytearray] | None - Codec name or encoder function. If None, auto-detect from file extension
- **kwargs: Additional codec-specific parameters passed to encoder
Returns:
None
Raises:
ValueError: If data format is incompatible with chosen codec
DelayedImportError: If required codec is not available
Various codec-specific exceptions: For encoding errors
"""Usage Examples:
import imagecodecs
import numpy as np
# Create sample image data
image = np.random.randint(0, 256, (512, 512, 3), dtype=np.uint8)
# Basic image writing (codec auto-detected from extension)
imagecodecs.imwrite('output.png', image)
imagecodecs.imwrite('output.jpg', image)
imagecodecs.imwrite('output.tiff', image)
# Write with specific codec
imagecodecs.imwrite('output.bin', image, codec='png')
# Codec-specific parameters
imagecodecs.imwrite('high_quality.jpg', image, level=95, optimize=True)
imagecodecs.imwrite('compressed.png', image, level=9)
imagecodecs.imwrite('lossless.webp', image, lossless=True)
# Multi-page TIFF
pages = [np.random.randint(0, 256, (256, 256), dtype=np.uint8) for _ in range(5)]
for i, page in enumerate(pages):
imagecodecs.imwrite('multipage.tiff', page, append=i > 0)Get information about supported file formats and extensions.
def imagefileext():
"""
Return list of image file extensions handled by imread/imwrite.
Returns:
list[str]: List of supported file extensions (without leading dot)
"""Usage Examples:
import imagecodecs
# Get all supported extensions
extensions = imagecodecs.imagefileext()
print(f"Supported formats: {len(extensions)}")
print(f"Extensions: {extensions}")
# Check if specific format is supported
if 'webp' in extensions:
print("WebP format is supported")
# Filter files by supported extensions
import os
supported_files = []
for filename in os.listdir('.'):
ext = filename.split('.')[-1].lower()
if ext in extensions:
supported_files.append(filename)The imread/imwrite functions support numerous image formats through their respective codecs:
class DelayedImportError(ImportError):
"""Raised when a required codec library is not available."""
def __init__(self, name: str) -> None: ...
# Codec-specific exceptions inherit from their respective base classes
class JpegError(Exception): ...
class PngError(Exception): ...
class TiffError(Exception): ...
# ... additional codec exceptionsCommon error scenarios:
import imagecodecs
try:
image = imagecodecs.imread('corrupted.jpg')
except imagecodecs.JpegError as e:
print(f"JPEG decoding failed: {e}")
except imagecodecs.DelayedImportError as e:
print(f"Required library not available: {e}")
except FileNotFoundError:
print("File not found")
try:
imagecodecs.imwrite('output.webp', image)
except imagecodecs.DelayedImportError:
print("WebP codec not available, falling back to PNG")
imagecodecs.imwrite('output.png', image)memmap=True for large files to avoid loading entire image into memoryout parameter to reduce memory allocationsSome codecs support parallel processing:
# Multi-threaded JPEG decoding (when available)
image = imagecodecs.imread('large.jpg', numthreads=4)
# Multi-threaded encoding
imagecodecs.imwrite('output.avif', image, numthreads=8)Install with Tessl CLI
npx tessl i tessl/pypi-imagecodecs