### Build and Install Bitshuffle Source: https://github.com/cgohlke/imagecodecs/blob/master/3rdparty/bitshuffle/README.rst Build and install bitshuffle using setup.py. Options for HDF5 plugin and ZSTD support can be included. ```bash python setup.py install [--h5plugin [--h5plugin-dir=spam] --zstd] ``` -------------------------------- ### Codec Availability Check Example Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/codec-patterns.md Example demonstrating how to check for codec availability using the `.available` attribute before attempting to use it. ```python from imagecodecs import JPEG2K if JPEG2K.available: print("JPEG2K is available") ``` -------------------------------- ### Install Bitshuffle from Source Source: https://github.com/cgohlke/imagecodecs/blob/master/3rdparty/bitshuffle/README.rst Install bitshuffle from source using pip, forcing it to build from source code. This is useful for targeting specific instructions or unsupported processors. ```bash pip install --no-binary=bitshuffle ``` -------------------------------- ### Install Bitshuffle using pip Source: https://github.com/cgohlke/imagecodecs/blob/master/3rdparty/bitshuffle/README.rst Install the bitshuffle package using pip. Binary wheels are available for Linux and macOS x86_64 platforms with AVX2 support. A source build will be performed on other platforms. ```bash pip install bitshuffle ``` -------------------------------- ### Basic Zarr v3 Array Setup Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/zarr.md Initializes Zarr v3 codecs and imports necessary libraries for creating a Zarr array. ```python import zarr import numpy as np from imagecodecs.zarr import register_codecs, Zstd register_codecs() ``` -------------------------------- ### Initialize ZSTD Submodule Source: https://github.com/cgohlke/imagecodecs/blob/master/3rdparty/bitshuffle/README.rst Before installing bitshuffle with ZSTD support, ensure the ZSTD repository is initialized as a submodule. ```bash git submodule update --init ``` -------------------------------- ### Lazy Loading Example Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/architecture.md Demonstrates how codec extensions are loaded on demand. The extension is not imported until the codec function is first used. ```python # No loading on import from imagecodecs import jpeg2k_encode # Not imported yet # Loading on first use result = jpeg2k_encode(data) # _jpeg2k extension is now imported ``` -------------------------------- ### Codec Options Dictionary Example Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/types.md Illustrates how to use a dictionary to pass codec-specific options, such as compression level or thread count, to encoding functions. ```python options: dict[str, Any] = { 'level': 90, # Compression/quality level 'bitspersample': 8, # Bits per sample (images) 'colorspace': 'RGB', # Color space 'numthreads': 4, # Thread count # ... codec-specific options } encoded = jpeg2k_encode(data, **options) ``` -------------------------------- ### JPEG Encode/Decode Example Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/core.md Demonstrates basic usage of jpeg_encode and jpeg_decode functions, including lossless encoding. Requires numpy. ```python import numpy as np from imagecodecs import jpeg_decode, jpeg_encode # Create image data = np.random.randint(0, 256, (256, 256, 3), dtype=np.uint8) # Encode to JPEG encoded = jpeg_encode(data, level=90) # Decode from JPEG decoded = jpeg_decode(encoded) # Lossless encoding (routes to LJPEG) lossless = jpeg_encode(data, lossless=True) ``` -------------------------------- ### Configure Build with Specific Codecs Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/README.md Shows how to customize the build process to enable specific codecs like JPEG2K and AVIF. This is done by defining a `customize_build` function in a setup script. ```python # imagecodecs_distributor_setup.py def customize_build(BUILD): BUILD['JPEG2K'].enabled = True BUILD['AVIF'].enabled = True # ... configure which codecs to build ``` -------------------------------- ### Count Documentation Size via Command Line Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/INDEX.md Use 'du -sh' to get a human-readable summary of the disk usage for the documentation directory. ```bash du -sh /workspace/home/output/ ``` -------------------------------- ### Write Zarr store to ReferenceFileSystem and open with Kerchunk Source: https://github.com/cgohlke/imagecodecs/blob/master/README.rst This example shows how to write a Zarr store to a fsspec ReferenceFileSystem in JSON format and then open it as a Zarr array using the kerchunk library. It's useful for creating efficient, shareable references to array data. ```python >>> store.write_fsspec( ... 'temp.json', url='file://', codec_id='imagecodecs_jpeg2k' ... ) >>> from kerchunk.utils import refs_as_store >>> zarr.open(refs_as_store('temp.json'), mode='r') shape=(1, 256, 256, 3)... ``` -------------------------------- ### version Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/core.md Get version information about imagecodecs and all available codecs. ```APIDOC ## version ### Description Get version information about imagecodecs and all available codecs. ### Method version ### Parameters #### Path Parameters - **astype** (type | None) - Optional - Return type: None for string, dict for dict, tuple for tuple. Defaults to None. ### Returns - `str` if `astype=None` or `astype=str`: Comma-separated version strings - `dict[str, str]` if `astype=dict`: Dictionary of component names to versions - `tuple[str, ...]` if `astype=tuple`: Tuple of version strings ### Example ```python from imagecodecs import version # Get all versions as string (default) versions = version() print(versions) # Output: imagecodecs-2026.5.10, cython-3.2.4, ... # Get versions as dictionary version_dict = version(astype=dict) print(version_dict['imagecodecs']) # Output: 2026.5.10 # Get versions as tuple version_tuple = version(astype=tuple) for v in version_tuple: print(v) ``` ``` -------------------------------- ### File Extension to Codec Mapping Example Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/architecture.md Illustrates the mapping from file extensions to codec names as generated by the `imagefileext()` function. This mapping is cached for performance. ```python # imagecodecs.py:1197-1255 _imcodecs() -> tuple[dict[str, str], list[str]] # Returns: # - dict: extension → codec name # - list: available codec names # Examples: # 'jpg' → 'jpeg8' # 'jp2' → 'jpeg2k' # 'png' → 'png' # 'webp' → 'webp' ``` -------------------------------- ### Cython Codec Extension Example (JPEG2K) Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/architecture.md Shows the typical structure of a Cython codec extension module, including encode, decode, check, and version functions, along with a custom error class. ```cython # _jpeg2k.pyx def jpeg2k_encode( data, /, level=None, *, codecformat=None, colorspace=None, out=None, ) -> bytes | bytearray: """Return JPEG2000 encoded image.""" # Cython implementation def jpeg2k_decode( data, /, *, colorspace=None, outcolorspace=None, out=None, ) -> NDArray: """Return decoded JPEG2000 image.""" # Cython implementation def jpeg2k_check(data: bytes | bytearray, /) -> bool: """Return whether data is JPEG2000 encoded.""" # Check for JP2/J2K magic bytes def jpeg2k_version() -> str: """Return OpenJPEG library version string.""" # Return version of underlying library class Jpeg2kError(RuntimeError): """JPEG2000 codec error.""" ``` -------------------------------- ### DelayedImportError Usage Example Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/core.md Shows how to catch a DelayedImportError when attempting to use an unavailable codec. ```python from imagecodecs import DelayedImportError try: from imagecodecs import some_unavailable_codec_decode some_unavailable_codec_decode(data) except DelayedImportError as e: print(f"Codec not available: {e}") ``` -------------------------------- ### Create Delta-LZW Compressed Zarr Array Source: https://github.com/cgohlke/imagecodecs/blob/master/README.rst Shows how to create a Zarr array using a combination of Delta and LZW compression codecs. This example requires registering codecs and defining a list of codecs for the Zarr array. ```python >>> from imagecodecs.zarr import register_codecs, Delta, Lzw >>> register_codecs() >>> zarr.zeros( ... (4, 5, 512, 512, 3), ... chunks=(1, 1, 256, 256, 3), ... dtype='u1', ... codecs=[Delta(), zarr.codecs.BytesCodec(), Lzw()], ... ) ``` -------------------------------- ### Codec to Extension Mapping Example Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/types.md Shows the implicit mapping from codec names to a list of their associated file extensions. This mapping is used internally by `imread` and `imwrite` for auto-detection. ```text # jpeg2k -> ['j2k', 'jp2', 'j2c', 'jpc', 'jpx', 'jpf', 'jpg2'] # jpeg8 -> ['jpg', 'jpeg', 'jpe', 'jfif', 'jfi', 'jif'] # png -> ['png'] # tiff -> ['tif', 'tiff', 'ptif', 'ptiff', 'tf8', 'tf2', 'btf'] # webp -> ['webp', 'webm'] # ... and many more ``` -------------------------------- ### Codec Error Handling Example Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/codec-patterns.md Illustrates how to handle potential errors during codec operations, specifically decoding, by using a try-except block to catch codec-specific exceptions. ```python from imagecodecs import jpeg2k_decode, Jpeg2kError try: decoded = jpeg2k_decode(invalid_data) except Jpeg2kError as e: print(f"JPEG2K decoding failed: {e}") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Numcodecs Codec Configuration Serialization Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/types.md Illustrates how to get the configuration dictionary for a Numcodecs codec, like Jpeg2k, and serialize it to a JSON string. ```python from imagecodecs.numcodecs import Jpeg2k import json codec = Jpeg2k(level=90) config = codec.get_config() # { # 'id': 'imagecodecs_jpeg2k', # 'level': 90, # } json_str = json.dumps(config) ``` -------------------------------- ### Create HDF5 Dataset with Bitshuffle Compression (Python) Source: https://github.com/cgohlke/imagecodecs/blob/master/3rdparty/bitshuffle/README.rst Example of creating an HDF5 dataset using the bitshuffle filter with LZ4 compression via h5py in Python. Requires h5py version 2.5.0 or later. ```python import h5py import numpy import bitshuffle.h5 print(h5py.__version__) # >= '2.5.0' f = h5py.File(filename, "w") # block_size = 0 let Bitshuffle choose its value block_size = 0 dataset = f.create_dataset( "data", (100, 100, 100), compression=bitshuffle.h5.H5FILTER, compression_opts=(block_size, bitshuffle.h5.H5_COMPRESS_LZ4), dtype='float32', ) # create some random data array = numpy.random.rand(100, 100, 100) array = array.astype('float32') dataset[:] = array f.close() ``` -------------------------------- ### Handle NotImplementedError for DICOMRLE Source: https://github.com/cgohlke/imagecodecs/blob/master/README.rst Demonstrates that not all codecs are fully implemented and may raise NotImplementedError at runtime. This example specifically shows the behavior when trying to use dicomrle_encode. ```python >>> from imagecodecs import dicomrle_encode >>> dicomrle_encode(array) Traceback ( ... NotImplementedError: dicomrle_encode ``` -------------------------------- ### Check Codec Availability Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/zarr.md Demonstrates how to check if a specific codec, like Jpeg2k, is available in the current imagecodecs build before attempting to use it. Codecs are only available if their underlying libraries are installed. ```python from imagecodecs.zarr import register_codecs import imagecodecs register_codecs() # Check if codec is available if imagecodecs.JPEG2K.available: from imagecodecs.zarr import Jpeg2k codec = Jpeg2k(level=90) else: print("JPEG2K is not available in this build") ``` -------------------------------- ### Handling Codec Errors with Try-Except Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/errors.md Use try-except blocks to gracefully handle potential errors during codec operations, such as missing dependencies (DelayedImportError) or decoding failures (Jpeg2kError). This example shows how to check the codec version and catch specific exceptions. ```python from imagecodecs import ( jpeg2k_decode, Jpeg2kError, jpeg2k_version, DelayedImportError ) try: version = jpeg2k_version() print(f"Using {version}") decoded = jpeg2k_decode(data) except DelayedImportError: print("JPEG2K not available") except Jpeg2kError as e: print(f"Decode failed with {version}: {e}") ``` -------------------------------- ### Zarr v3 Integration with Compression Pipeline Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/README.md Integrate imagecodecs with Zarr v3 by registering codecs and defining a compression pipeline using codecs like `Delta` and `Zstd`. This example shows creating a Zarr v3 array with a multi-stage compression. ```python from imagecodecs.zarr import register_codecs, Zstd, Delta import zarr # Register codecs with Zarr v3 register_codecs() # Create Zarr v3 array with compression pipeline arr = zarr.zeros( (1000, 1000), chunks=(100, 100), dtype='i4', codecs=[ Delta(axis=0), Zstd(level=5), ], ) ``` -------------------------------- ### Check Codec Availability (JPEG2K, AVIF) Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/README.md Checks if specific codecs like JPEG2K and AVIF are available in the current build. This is useful for conditional logic based on installed codec support. ```python from imagecodecs import JPEG2K, AVIF if JPEG2K.available: print("JPEG2K is available") else: print("JPEG2K is not available in this build") if AVIF.available: print("AVIF is available") ``` -------------------------------- ### Conditional Codec Building in Setup.py Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/architecture.md Shows how the setup.py script conditionally builds codec extensions based on the operating system platform. ```python # setup.py defines customize_build functions for different platforms if PLATFORM == 'linux': # All codecs built elif PLATFORM == 'win32': # Platform-specific restrictions apply ``` -------------------------------- ### Get Available Codecs Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/errors.md A function to retrieve a list of available codecs. Set include_unavailable to True to get all codecs, regardless of availability. ```python from imagecodecs import _codecs def get_available_codecs(include_unavailable=False): if include_unavailable: return _codecs(available=None) # All codecs else: return _codecs(available=True) # Only available ``` -------------------------------- ### Handling ZstdError Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/errors.md Example of catching ZstdError during Zstandard decoding. This is relevant for handling frame corruption or version mismatches. ```python from imagecodecs import zstd_decode, ZstdError try: decoded = zstd_decode(data) except ZstdError as e: print(f"ZSTD decode failed: {e}") ``` -------------------------------- ### Handling WebpError Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/errors.md Example of catching WebpError during WebP decoding. This is relevant for invalid streams or memory allocation issues. ```python from imagecodecs import webp_decode, WebpError try: decoded = webp_decode(data) except WebpError as e: print(f"WebP decode failed: {e}") ``` -------------------------------- ### Using Default Compression Level Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/configuration.md Illustrates how to utilize the default compression level for codecs like deflate_encode by passing 'level=None' or omitting the 'level' argument. ```python # Uses default compression level encoded = deflate_encode(data, level=None) # Explicit level encoded = deflate_encode(data, level=9) # Via keyword encoded = deflate_encode(data) ``` -------------------------------- ### Codec Alias Definition Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/architecture.md Shows how some codecs are aliased for convenience within the imagecodecs library. This example defines an alias for JPEG. ```python _ALIASES: dict[str, str] = { 'JPEG': 'JPEG8', 'JpegError': 'Jpeg8Error', 'jpeg_check': 'jpeg8_check', 'jpeg_version': 'jpeg8_version', } ``` -------------------------------- ### View Specific Document via Command Line Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/INDEX.md Use the 'cat' command to display the content of a specific documentation file. ```bash cat /workspace/home/output/README.md ``` -------------------------------- ### Stub Function for Unavailable Codecs Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/architecture.md Provides an example of a stub function created when a codec extension fails to load, raising a DelayedImportError. ```python # Stub for encode function def stub_encode(*args, **kwargs) -> None: raise DelayedImportError(name) ``` -------------------------------- ### Import and Lazy Loading Pattern Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/codec-patterns.md Demonstrates the import pattern for codecs, showing how direct imports trigger lazy loading of underlying extensions. Also shows how to check codec availability. ```python from imagecodecs import jpeg2k_encode, jpeg2k_decode, JPEG2K # First access triggers import of _jpeg2k extension encoded = jpeg2k_encode(image_array) # Codec availability can be checked if JPEG2K.available: print("JPEG2K is available") ``` -------------------------------- ### Get Version Information for All Codecs Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/INDEX.md Retrieves version information for all available codecs in the imagecodecs library. This function is part of the core API. ```python imagecodecs.version() ``` -------------------------------- ### Using AVIF Pixel Format Enum Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/types.md Shows how to instantiate an Avif codec using either a string or an enum member for the pixel format. ```python from imagecodecs import AVIF, Avif if AVIF.available: codec = Avif(pixelformat='YUV420') # or codec = Avif(pixelformat=AVIF.PIXEL_FORMAT.YUV420) ``` -------------------------------- ### Create Zarr Array with Avif Image Compression Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/zarr.md Shows how to create a Zarr array for high-quality image compression using the Avif codec. Requires the Avif codec to be available. ```python import zarr from imagecodecs.zarr import register_codecs, Avif register_codecs() # High-quality image compression with AVIF arr = zarr.zeros( (720, 1280, 3), chunks=(360, 640, 3), dtype='u1', codecs=[ Avif( level=55, speed=8, numthreads=4, ) ], store=zarr.MemoryStore(), ) ``` -------------------------------- ### Get Supported Image File Extensions Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/core.md The imagefileext function returns a sorted list of all file extensions that the imread and imwrite functions can recognize. ```python from imagecodecs import imagefileext extensions = imagefileext() print(extensions) # Output: ['apng', 'avif', 'bmp', 'dds', 'exr', 'gif', 'heif', # 'heic', 'jpg', 'jpeg', 'jp2', 'j2k', 'jxl', ...] if 'webp' in extensions: print('WebP is supported') ``` -------------------------------- ### Get imagecodecs Version Information Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/core.md The version function retrieves version information for imagecodecs and its components. It can return this information as a string, a dictionary, or a tuple. ```python from imagecodecs import version # Get all versions as string (default) versions = version() print(versions) # Output: imagecodecs-2026.5.10, cython-3.2.4, ... # Get versions as dictionary version_dict = version(astype=dict) print(version_dict['imagecodecs']) # Output: 2026.5.10 # Get versions as tuple version_tuple = version(astype=tuple) for v in version_tuple: print(v) ``` -------------------------------- ### Brotli Codec Initialization Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Initializes the Brotli compression codec with optional compression level and window size parameters. ```python class Brotli(Codec): codec_id = 'imagecodecs_brotli' def __init__( self, *, level: int | None = None, lgwin: int | None = None, ) -> None: ... ``` -------------------------------- ### Zlib Codec Initialization Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Initializes the Zlib compression codec with an optional compression level parameter. ```python class Zlib(Codec): codec_id = 'imagecodecs_zlib' def __init__(self, *, level: int | None = None) -> None: ... ``` -------------------------------- ### Get JPEG2K Codec Version Source: https://github.com/cgohlke/imagecodecs/blob/master/README.rst Retrieves the version string of the underlying OpenJPEG library used by the JPEG2K codec. This can be helpful for debugging or compatibility checks. ```python >>> jpeg2k_version() 'openjpeg 2.5.4' ``` -------------------------------- ### Search Across All Documentation via Command Line Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/INDEX.md Use 'grep -r' to perform a recursive search for a pattern across all documentation files. ```bash grep -r "jpeg2k" /workspace/home/output/ ``` -------------------------------- ### Register Bitshuffle HDF5 Plugin in Rust Source: https://github.com/cgohlke/imagecodecs/blob/master/3rdparty/bitshuffle/README.rst Example of how to register the bitshuffle HDF5 plugin in a Rust program to enable reading HDF5 files compressed with bitshuffle. ```rust use hdf5_bitshuffle::register_bitshuffle_plugin; fn main() { register_bitshuffle_plugin(); } ``` -------------------------------- ### Gzip Codec Initialization Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Initializes the GZIP compression codec with an optional compression level parameter. ```python class Gzip(Codec): codec_id = 'imagecodecs_gzip' def __init__(self, *, level: int | None = None) -> None: ... ``` -------------------------------- ### Create Zarr Array with Zstd Compression Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/zarr.md Demonstrates creating a Zarr array with Zstd compression using a MemoryStore. Ensure Zstd is available. ```python import zarr import numpy as np from imagecodecs.zarr import Zstd # Create array with compression codec store = zarr.MemoryStore() arr = zarr.zeros( (1000, 1000), chunks=(100, 100), dtype='f4', codecs=[Zstd(level=5)], store=store, ) # Write data arr[:] = np.random.randn(1000, 1000) ``` -------------------------------- ### Zarr v3 Array with Codecs Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/types.md Shows how to create a Zarr v3 array using a list of codec specifications, such as Delta and Zstd. ```python import zarr from imagecodecs.zarr import Zstd, Delta arr = zarr.zeros( shape=(1000, 1000), chunks=(100, 100), dtype='i4', codecs=[ Delta(axis=0), Zstd(level=5), ], ) ``` -------------------------------- ### Get Codec Version Information Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/README.md Retrieves the version information for specific codecs like JPEG2K, PNG, and Zstd. This helps in identifying the underlying library versions used by imagecodecs. ```python from imagecodecs import jpeg2k_version, png_version, zstd_version print(jpeg2k_version()) # 'openjpeg 2.5.4' print(png_version()) # 'libpng 1.6.58' print(zstd_version()) # 'zstd 1.5.7' ``` -------------------------------- ### Bz2 Codec Initialization Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Initializes the BZ2 compression codec with an optional compression level parameter. ```python class Bz2(Codec): codec_id = 'imagecodecs_bz2' def __init__(self, *, compresslevel: int | None = None) -> None: ... ``` -------------------------------- ### Zstd Codec Initialization Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Initializes the ZStandard compression codec with an optional compression level parameter. ```python class Zstd(Codec): codec_id = 'imagecodecs_zstd' def __init__(self, *, level: int | None = None) -> None: ... ``` -------------------------------- ### Bitshuffle Shuffling and Unshuffling in Java Source: https://github.com/cgohlke/imagecodecs/blob/master/3rdparty/bitshuffle/README.rst Demonstrates how to use the BitShuffle class from the snappy-java library to shuffle and unshuffle integer arrays in Java. ```java import org.xerial.snappy.BitShuffle; int[] data = new int[] {1, 3, 34, 43, 34}; byte[] shuffledData = BitShuffle.bitShuffle(data); int[] result = BitShuffle.bitUnShuffleIntArray(shuffledData); ``` -------------------------------- ### Zarr v2 Integration with JPEG2000 Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/README.md Integrate imagecodecs with Zarr v2 by registering codecs and using a specific compressor like `Jpeg2k`. This example demonstrates creating a Zarr array with JPEG2000 compression. ```python from imagecodecs.numcodecs import register_codecs, Jpeg2k import zarr import numpy as np # Register codecs with Zarr v2 register_codecs() # Create Zarr array with JPEG2000 compression arr = zarr.zeros( (512, 512, 3), chunks=(256, 256, 3), dtype='u1', compressor=Jpeg2k(level=90), zarr_format=2, ) arr[:] = np.random.randint(0, 256, arr.shape, dtype='u1') ``` -------------------------------- ### Apng Codec Initialization Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Initializes the Animated PNG (Apng) codec with various parameters for compression level, strategy, filter, photometric mode, delay, and squeeze. ```python class Apng(Codec): codec_id = 'imagecodecs_apng' def __init__( self, *, level: int | None = None, strategy: int | str | None = None, filter: int | str | None = None, photometric: int | str | None = None, delay: int | None = None, squeeze: Sequence[int] | False | None = None, ) -> None: ... ``` -------------------------------- ### Decode JP2 Bytes to NumPy Array Source: https://github.com/cgohlke/imagecodecs/blob/master/README.rst Decodes JPEG 2000 (JP2) encoded bytes back into a NumPy array. This example shows a direct decoding process and verifies the result against the original array. ```python >>> decoded = jpeg2k_decode(encoded) >>> numpy.array_equal(decoded, array) True ``` -------------------------------- ### Handle ValueError: no codec specified Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/errors.md Raised by imwrite when the codec cannot be determined from the file extension. Specify the codec explicitly. ```python from imagecodecs import imwrite try: imwrite(file_object, data) # No codec specified except ValueError as e: print(f"Cannot determine codec: {e}") # Specify codec explicitly imwrite(file_object, data, codec='jpeg2k') ``` -------------------------------- ### Lzma Codec Initialization Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Initializes the LZMA compression codec with an optional compression level parameter. ```python class Lzma(Codec): codec_id = 'imagecodecs_lzma' def __init__(self, *, level: int | None = None) -> None: ... ``` -------------------------------- ### Encode NumPy Array to Lossless JP2 Source: https://github.com/cgohlke/imagecodecs/blob/master/README.rst Encodes a NumPy array into a lossless JPEG 2000 (JP2) format. The example demonstrates creating a random array and then encoding it, showing the first few bytes of the encoded data. ```python >>> import numpy >>> array = numpy.random.randint(100, 200, (256, 256, 3), numpy.uint8) >>> encoded = jpeg2k_encode(array, level=0) >>> bytes(encoded[:12]) b'\x00\x00\x00\x0cjP \r\n\x87\n' ``` -------------------------------- ### Check Codec Availability and Usage Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/configuration.md Demonstrates how to check if a specific codec like WIC is available and then use its encoding function. This is useful for conditionally enabling platform-specific features. ```python from imagecodecs import WIC, EXR, JETRAW if WIC.available: from imagecodecs import wic_encode encoded = wic_encode(data) ``` -------------------------------- ### Build Conda Package Source: https://github.com/cgohlke/imagecodecs/blob/master/3rdparty/bitshuffle/README.rst Command to build a conda package for bitshuffle using the provided conda recipe. ```bash conda build conda-recipe ``` -------------------------------- ### Using Pre-allocated Output Buffers Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/configuration.md Shows how to improve performance by pre-allocating an output NumPy array and passing it to decoding functions like jpeg2k_decode. The output buffer is modified in-place. ```python import numpy as np from imagecodecs import jpeg2k_decode # Allocate output once output = np.zeros((512, 512, 3), dtype='uint8') # Decode multiple times for encoded_data in dataset: jpeg2k_decode(encoded_data, out=output) # output is modified in-place process(output) ``` -------------------------------- ### Lz4 Codec Initialization Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Initializes the LZ4 compression codec with an optional acceleration parameter. ```python class Lz4(Codec): codec_id = 'imagecodecs_lz4' def __init__(self, *, acceleration: int | None = None) -> None: ... ``` -------------------------------- ### Create Zarr Array with Codec Pipeline (Delta + Zstd) Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/zarr.md Demonstrates combining multiple codecs in a pipeline, such as Delta encoding followed by Zstd compression. Ensure both codecs are available. ```python import zarr import numpy as np from imagecodecs.zarr import register_codecs, Delta, Zstd register_codecs() # Combine delta filter with compression arr = zarr.zeros( (1000, 1000), chunks=(100, 100), dtype='i4', codecs=[ Delta(axis=0), # Delta encoding Zstd(level=5), # Compress with Zstd ], store=zarr.MemoryStore(), ) arr[:] = np.arange(1000000, dtype='i4').reshape((1000, 1000)) ``` -------------------------------- ### Deflate Codec Initialization Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Initializes the Deflate compression codec with an optional compression level parameter. ```python class Deflate(Codec): codec_id = 'imagecodecs_deflate' def __init__(self, *, level: int | None = None) -> None: ... ``` -------------------------------- ### Using String Enum Names for Parameters Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/configuration.md Demonstrates how to use string names for enum parameters, such as 'filter' in png_encode. It also shows how to convert enum names to their integer values. ```python from imagecodecs import png_encode # Using enum string name encoded = png_encode(data, filter='paeth') # Using integer enum value encoded = png_encode(data, filter=4) # Convert enum names to uppercase for codec access from imagecodecs import PNG filter_enum = PNG.FILTER.PAETH ``` -------------------------------- ### Zarr Codec Configuration Serialization Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/types.md Demonstrates how to serialize a Zarr codec configuration, like Jpeg2k, into a dictionary and then a JSON string. ```python from imagecodecs.zarr import Jpeg2k import json codec = Jpeg2k(level=90) config = codec.to_dict() # { # 'name': 'imagecodecs_jpeg2k', # 'configuration': {'level': 90} # } json_str = json.dumps(config) ``` -------------------------------- ### Importing Codec Functions Directly Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/architecture.md Illustrates the direct import of specific codec encoding functions from the imagecodecs library using attribute lookup. ```python from imagecodecs import jpeg2k_encode # Attribute lookup ``` -------------------------------- ### JSON Serialization and Deserialization of Zarr Codecs Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/zarr.md Demonstrates how to serialize a Zarr codec to a dictionary and then deserialize it back from JSON. This is useful for saving and loading codec configurations. ```python import json from imagecodecs.zarr import Jpeg2k # Create codec with options codec = Jpeg2k(level=90) # Serialize to JSON codec_dict = codec.to_dict() print(json.dumps(codec_dict)) # Output: {"name": "imagecodecs_jpeg2k", "configuration": {"level": 90}} # Deserialize from JSON codec2 = Jpeg2k.from_dict(codec_dict) assert codec == codec2 ``` -------------------------------- ### Zarr v3 Integration with Jpeg2k Codec Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/architecture.md Explains the native Zarr v3 integration using the Jpeg2k codec, highlighting the initialization and encoding process within Zarr's framework. ```text zarr.array(codecs=[Jpeg2k(level=90)]) ↓ Jpeg2k.__init__(level=90) [zarr.py] ↓ Jpeg2k._encode_sync(chunk, spec) ↓ [zarr.py] ↓ jpeg2k_encode(array, level=90) [imagecodecs] ↓ [Return bytes in Buffer] ↓ Zarr stores compressed chunk ``` -------------------------------- ### Compress and Decompress Data with Zstandard Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/README.md Utilize `zstd_encode` and `zstd_decode` for compressing and decompressing binary data using the Zstandard algorithm. The compression level can be specified. ```python from imagecodecs import zstd_encode, zstd_decode data = b'some binary data to compress' # Compress encoded = zstd_encode(data, level=10) # Decompress decoded = zstd_decode(encoded) ``` -------------------------------- ### Module Import and Dynamic Access Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/codec-patterns.md Shows an alternative import method using the main 'imagecodecs' module and dynamically accessing codec functions via getattr. Useful for iterating over available codecs. ```python import imagecodecs # Dynamic loading via __getattr__ codec_list = imagecodecs._codecs(available=True) for codec_name in codec_list: version_func = getattr(imagecodecs, f'{codec_name}_version') print(version_func()) ``` -------------------------------- ### Accessing Codec IDs and Retrieving Codecs Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Demonstrates how to access the `codec_id` attribute for registered codecs like Jpeg2k and Zlib, and how to retrieve a codec instance using `numcodecs.get_codec`. ```python from imagecodecs.numcodecs import Jpeg2k, Zlib print(Jpeg2k.codec_id) # 'imagecodecs_jpeg2k' print(Zlib.codec_id) # 'imagecodecs_zlib' # Codecs are registered and can be retrieved import numcodecs jpeg2k_codec = numcodecs.get_codec(Jpeg2k.codec_id) ``` -------------------------------- ### Quantize Encode and Decode Functions Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/configuration.md Offers quantization encoding and decoding for data compression. Various modes like 'scale', 'bitgroom', and 'bitround' are supported, along with specific parameters for each mode. ```python def quantize_encode(data, /, level=None, *, out=None, **kwargs) -> NDArray def quantize_decode(data, /, *, out=None, **kwargs) -> NDArray ``` -------------------------------- ### Register Codecs and Create Zstd Compressed Zarr Array Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Demonstrates registering imagecodecs codecs and creating a Zarr array with Zstd compression. This is useful for general-purpose data compression. ```python from imagecodecs.numcodecs import register_codecs, Zstd import zarr import numpy as np register_codecs() # Create Zarr array with Zstd compression arr = zarr.zeros( (1000, 1000), chunks=(100, 100), dtype='f8', compressor=Zstd(level=10), zarr_format=2, ) # Write data data = np.random.randn(1000, 1000) arr[:] = data ``` -------------------------------- ### Pre-allocated Output Buffer for Decoding Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/architecture.md Shows how to provide a pre-allocated NumPy array as an output buffer for decoding functions. This avoids unnecessary memory allocation by modifying the buffer in-place. ```python # User can provide output buffer import numpy as np output = np.zeros((512, 512, 3), dtype='uint8') jpeg2k_decode(data, out=output) # output is modified in-place, avoiding allocation ``` -------------------------------- ### Import All Numcodecs Codecs Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Imports all available imagecodecs codecs for use with numcodecs. ```python from imagecodecs.numcodecs import ( register_codecs, Aec, Apng, Avif, Bfloat16, Bitorder, Bitshuffle, Blosc, Blosc2, Bmp, Brotli, Byteshuffle, Bz2, Ccittfax3, Ccittfax4, Ccittrle, Checksum, Cms, Dds, Deflate, Delta, Dicomrle, Eer, Exr, Float24, Floatpred, Gif, Hcomp, Heif, Htj2k, Jpeg, Jpeg2k, Jpegls, Jpegxl, Jpegxr, Jpegxs, Lerc, Ljpeg, Lz4, Lz4f, Lz4h5, Lzf, Lzfse, Lzham, Lzma, Lzo, Lzw, Meshopt, Packbits, Packints, Pcodec, Pglz, Pixarlog, Png, Qoi, Quantize, Rcomp, Rgbe, Snappy, Sperr, Spng, Sz3, Szip, Tiff, Ultrahdr, Wavpack, Webp, Wic, Xor, Zfp, Zlib, Zlibng, Zopfli, Zstd ) ``` -------------------------------- ### Configure HDF5 Plugin Path Source: https://github.com/cgohlke/imagecodecs/blob/master/3rdparty/bitshuffle/README.rst Set the HDF5_PLUGIN_PATH environment variable to enable the dynamically loaded HDF5 filter plugins for Bitshuffle and LZF. ```bash export HDF5_PLUGIN_PATH=/path/to/hdf5/plugin ``` -------------------------------- ### List Extension Modules Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/core.md Retrieves a tuple of all C extension module names. These are typically the underlying implementations for the codecs. ```python from imagecodecs import _extensions extensions = _extensions() print(extensions) # Output: ('aec', 'apng', 'avif', 'bcn', 'bfloat16', ...) ``` -------------------------------- ### Quantize Codec Configuration Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/zarr.md Configuration for the Quantize codec, used for quantization and scaling. This codec is fixed-size. ```python @dataclass(frozen=True) class Quantize(ArrayArrayCodec): is_fixed_size: bool = True mode: str | None = None scale: float | None = None bitgroom: int | None = None bitround: int | None = None ``` -------------------------------- ### List All Codecs Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/core.md Retrieves a tuple of all registered codec names. Use the 'available' parameter to filter by availability. ```python from imagecodecs import _codecs # All codecs all_codecs = _codecs() print(all_codecs) # Output: ('aec', 'apng', 'avif', 'bcn', 'bfloat16', 'bitorder', ...) ``` ```python from imagecodecs import _codecs # Only available codecs (loads all extensions) available = _codecs(available=True) ``` ```python from imagecodecs import _codecs # Only unavailable codecs unavailable = _codecs(available=False) ``` -------------------------------- ### Zarr v2 Integration with Jpeg2k Compressor Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/architecture.md Shows how imagecodecs' Jpeg2k compressor is used within the Zarr v2 library, detailing the initialization and encoding steps. ```text zarr.array(compressor=Jpeg2k(level=90)) ↓ Jpeg2k.__init__(level=90) [numcodecs.py] ↓ Jpeg2k.encode(chunk_array) ↓ [numcodecs.py] ↓ jpeg2k_encode(array, level=90) [imagecodecs] ↓ [Return bytes] ↓ Zarr stores compressed chunk ``` -------------------------------- ### Create Zarr Array with Jpeg2k Image Compression Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/zarr.md Shows how to create a Zarr array for image compression using the Jpeg2k codec. The imagecodecs.zarr codecs must be registered first. Data is stored in a DirectoryStore. ```python import zarr import numpy as np from imagecodecs.zarr import register_codecs, Jpeg2k register_codecs() # Create array for image compression store = zarr.DirectoryStore('image.zarr') arr = zarr.zeros( (512, 512, 3), chunks=(256, 256, 3), dtype='u1', codecs=[Jpeg2k(level=90)], store=store, ) # Store image image = np.random.randint(0, 256, (512, 512, 3), dtype='u1') arr[:] = image ``` -------------------------------- ### Create Zarr v3 Array with Zstd Codec Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/zarr.md Demonstrates creating a Zarr v3 array using the Zstd compression codec from imagecodecs. Ensure imagecodecs is registered with Zarr v3 before creating the array. ```python import zarr from imagecodecs.zarr import register_codecs, Zstd # Register imagecodecs with Zarr v3 register_codecs() # Create Zarr v3 array with imagecodecs codec store = zarr.DirectoryStore('data.zarr') arr = zarr.zeros( (1000, 1000), chunks=(100, 100), dtype='f4', codecs=[Zstd(level=5)], store=store, ) ``` -------------------------------- ### Bmp Codec Configuration Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Configure the BMP image codec with bit depth and photometric interpretation. ```python class Bmp(Codec): codec_id = 'imagecodecs_bmp' def __init__( self, *, bitspersample: int | None = None, photometric: int | str | None = None, ) -> None: ... ``` -------------------------------- ### imagefileext Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/core.md Return list of image file extensions recognized by imread and imwrite. ```APIDOC ## imagefileext ### Description Return list of image file extensions recognized by imread and imwrite. ### Method imagefileext ### Returns - `list[str]`: Sorted list of file extensions (without leading dot) supported by imread/imwrite ### Example ```python from imagecodecs import imagefileext extensions = imagefileext() print(extensions) # Output: ['apng', 'avif', 'bmp', 'dds', 'exr', 'gif', 'heif', # 'heic', 'jpg', 'jpeg', 'jp2', 'j2k', 'jxl', ...] if 'webp' in extensions: print('WebP is supported') ``` ``` -------------------------------- ### Snappy Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Snappy compression codec. Implements the numcodecs Codec interface. ```APIDOC ## Snappy ### Description Snappy compression codec. ``` -------------------------------- ### Register Codecs and Create Jpeg2k Compressed Zarr Array for Images Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/numcodecs.md Shows how to register codecs and create a Zarr array for image data using JPEG2000 compression. Suitable for lossy image compression. ```python from imagecodecs.numcodecs import register_codecs, Jpeg2k import zarr import numpy as np register_codecs() # Create Zarr array with JPEG2000 compression image_store = zarr.DirectoryStore('image.zarr') root = zarr.group(store=image_store, overwrite=True, zarr_format=2) arr = root.zeros( 'image', shape=(512, 512, 3), chunks=(256, 256, 3), dtype='u1', compressor=Jpeg2k(level=90), ) # Write image data image_data = np.random.randint(0, 256, (512, 512, 3), dtype='u1') arr[:] = image_data ``` -------------------------------- ### Webp Codec Configuration Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/zarr.md Configuration options for the Webp codec, used for WebP image format. ```python @dataclass(frozen=True) class Webp(ArrayBytesCodec): is_fixed_size: bool = False level: int | None = None lossless: bool | None = None method: int | None = None ``` -------------------------------- ### NONE Codec Usage Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/api-reference/core.md Demonstrates the usage of the NONE codec, which acts as an identity transform for decoding and encoding. It is always available. ```python from imagecodecs import none_decode, none_encode, NONE # Check availability assert NONE.available # Pass data through unchanged data = b'some binary data' result = none_decode(data) assert result == data # Encoding is also identity encoded = none_encode(data) assert encoded == data ``` -------------------------------- ### Codec Configuration Reference Source: https://github.com/cgohlke/imagecodecs/blob/master/_autodocs/INDEX.md Provides a comprehensive reference for configuring various compression, image format, and transform codecs. ```APIDOC ## Codec Configuration Reference ### Description Provides a comprehensive reference for configuring various compression, image format, and transform codecs. ### Compression Codecs (15+ documented) - AEC, Blosc, Blosc2, Brotli, BZ2, Deflate, Gzip, LZ4, Lz4f, Lz4h5, Lzma, Snappy, Zlib, ZlibNG, Zstd ### Image Format Codecs (30+ documented) - **JPEG Family**: JPEG8, Lossless JPEG, JPEG2000, HTJ2K, JPEGLS, JPEGXL, JPEGXR, JPEGXS - **Other**: PNG, APNG, AVIF, HEIF, WebP, TIFF, BMP, GIF, and 15+ more ### Transform Codecs (10+ documented) - Delta, Bitshuffle, Byteshuffle, Float24, Bfloat16, Floatpred, Quantize, XOR, Bitorder ### Codec-Specific Parameters - Per-codec parameter tables: type, default, description. - Compression level ranges and defaults. - Color space and format options. - Platform-specific limitations. - Environment variables. ```