CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-imagecodecs

Image transformation, compression, and decompression codecs for scientific computing

Pending
Overview
Eval results
Files

image-io.mddocs/

Image I/O Functions

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.

Capabilities

Reading Images

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 page

Writing Images

Write 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)

File Extension Support

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)

Supported Image Formats

The imread/imwrite functions support numerous image formats through their respective codecs:

Common Formats

  • JPEG (.jpg, .jpeg) - Lossy compression for photographs
  • PNG (.png) - Lossless compression with transparency support
  • TIFF (.tiff, .tif) - Flexible format supporting multiple pages and data types
  • BMP (.bmp) - Uncompressed bitmap format
  • GIF (.gif) - Palette-based format with animation support

Next-Generation Formats

  • WebP (.webp) - Modern format with superior compression
  • AVIF (.avif) - AV1-based format with excellent compression
  • HEIF (.heif, .heic) - High efficiency format used by Apple devices
  • JPEG XL (.jxl) - Next-generation JPEG replacement

Scientific Formats

  • JPEG 2000 (.jp2, .j2k) - Wavelet-based compression for medical imaging
  • JPEG XS (.jxs) - Low-latency format for professional video
  • JPEG-LS (.jls) - Lossless/near-lossless compression

Specialized Formats

  • QOI (.qoi) - Simple lossless format
  • RGBE (.hdr) - High dynamic range format
  • EER (.eer) - Electron microscopy format

Data Type Support

Input Data Types

  • uint8: Standard 8-bit images (0-255)
  • uint16: 16-bit images (0-65535)
  • float32/float64: Floating-point images (typically 0.0-1.0)
  • int8/int16/int32: Signed integer formats

Array Shapes

  • 2D arrays: Grayscale images (height, width)
  • 3D arrays: Color images (height, width, channels)
    • RGB: 3 channels
    • RGBA: 4 channels (with alpha)
    • CMYK: 4 channels (for printing)

Memory Layout

  • C-contiguous: Default NumPy layout (row-major)
  • Fortran-contiguous: Column-major layout (supported by most codecs)
  • Memory-mapped: For processing large files without loading into RAM

Error Handling

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 exceptions

Common 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)

Performance Considerations

Memory Usage

  • Use memmap=True for large files to avoid loading entire image into memory
  • Specify output buffer with out parameter to reduce memory allocations
  • Choose appropriate data types (uint8 vs float32) based on precision needs

Codec Selection

  • JPEG: Best for photographs and natural images
  • PNG: Best for screenshots, graphics, and images requiring lossless compression
  • WebP/AVIF: Modern formats with superior compression ratios
  • TIFF: Best for scientific data and multi-page documents

Multi-threading

Some 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

docs

array-processing.md

color-management.md

image-formats.md

image-io.md

index.md

lossless-compression.md

scientific-compression.md

utilities.md

tile.json