### Install tifffile from Source Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/README.md Install tifffile from its source repository. This involves cloning the repository and performing a local installation. ```bash git clone https://github.com/cgohlke/tifffile.git cd tifffile pip install -e . ``` -------------------------------- ### Install tifffile Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/README.md Install the tifffile package using pip. Use the '[all]' option to include all optional dependencies. ```bash pip install tifffile ``` ```bash pip install tifffile[all] ``` -------------------------------- ### Install Tifffile with Dependencies Source: https://github.com/cgohlke/tifffile/blob/master/README.rst Install the tifffile package and all its dependencies from the Python Package Index. This command ensures all optional features are available. ```bash python -m pip install -U tifffile[all] ``` -------------------------------- ### FileHandle Read Example Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/file-classes.md Demonstrates reading the header and getting the size of a TIFF file using FileHandle. Ensure the file is opened in binary read mode ('rb'). ```python # Read from file with tifffile.FileHandle('image.tiff', mode='rb') as fh: header = fh.read(4) # TIFF magic number size = fh.size print(f'File size: {size} bytes') ``` -------------------------------- ### FileHandle Write Example Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/file-classes.md Illustrates writing binary data to a file using FileHandle. The file should be opened in binary write mode ('wb'). ```python # Stream operations with tifffile.FileHandle('output.bin', mode='wb') as fh: fh.write(b'Hello') ``` -------------------------------- ### TiffTag Representation Example Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tag-classes.md Demonstrates how to access a TiffTag by its code and print its string representation. ```python tag = page.tags[256] # ImageWidth tag print(tag) # TiffTag(ImageWidth=512) ``` -------------------------------- ### Measure Image Loading Time Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/file-classes.md Example of using the Timer context manager to measure the time taken to load a TIFF image. ```python import tifffile with tifffile.Timer() as timer: data = tifffile.imread('large_image.tiff') print(f'Loading took {timer.elapsed:.2f} seconds') ``` -------------------------------- ### TiffFile Page Access Example Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/page-classes.md Demonstrates opening a TIFF file, accessing its pages, and performing operations like counting, indexing, slicing, and iterating. ```python with tifffile.TiffFile('stack.tiff') as tif: pages = tif.pages # Get page count print(f'Total pages: {len(pages)}') # Access by index first = pages[0] fifth = pages[4] # Slice pages subset = pages[10:20] for page in subset: print(page.shape, page.compression) # Iterate all total_pixels = sum(p.size for p in pages) ``` -------------------------------- ### Getting Tag Value with Default Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tag-classes.md Illustrates how to use the get method to retrieve a tag's value, providing a default value if the tag is not found. ```python compression = tags.get(259, 'none') # Default 'none' if not found ``` -------------------------------- ### imread() Examples Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/main-functions.md Examples demonstrating how to use the imread function to read TIFF files in various ways, including reading single files, specific pages, page ranges, file sequences, and returning data as xarray or Zarr stores. ```APIDOC ## imread() Examples ### Description Examples demonstrating how to use the imread function to read TIFF files in various ways, including reading single files, specific pages, page ranges, file sequences, and returning data as xarray or Zarr stores. ### Code Examples ```python import tifffile import numpy as np # Read single file as NumPy array data = tifffile.imread('image.tiff') print(data.shape, data.dtype) # Read specific page page_5 = tifffile.imread('image.tiff', key=5) # Read page range pages = tifffile.imread('image.tiff', key=slice(10, 20)) # Read file sequence with glob pattern sequence = tifffile.imread('images_*.tiff') # Return as xarray with coordinates data_xr = tifffile.imread('image.tiff', return_as='xarray') # Return as Zarr store for memory-efficient access zarr_store = tifffile.imread('large_image.tiff', return_as='zarr') print(zarr_store.shape) zarr_store.close() # Selective reading with Zarr-style indexing subset = tifffile.imread('image.tiff', selection=np.s_[0:100, 100:200]) ``` ``` -------------------------------- ### Example: Parse XML Metadata Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/file-classes.md Demonstrates parsing an XML string into a dictionary using the xml2dict function. Ensure the tifffile library is imported. ```python import tifffile # Parse XML metadata xml_string = "value" data = tifffile.xml2dict(xml_string) print(data) # {'root': {'item': 'value'}} ``` -------------------------------- ### TiffPageSeries Usage Example Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/page-classes.md Demonstrates how to open a TIFF file, access its series, print series properties, and extract data as a NumPy array, xarray DataArray, or a Zarr store. ```python with tifffile.TiffFile('volume.ome.tiff') as tif: # Get series series = tif.series[0] print(f'Shape: {series.shape}') # e.g., (10, 100, 512, 512) print(f'Axes: {series.axes}') # e.g., 'TZYX' print(f'Dtype: {series.dtype}') print(f'Kind: {series.kind}') # Extract as array data = series.asarray() # Extract as xarray data_xr = series.asxarray() # Lazy access with Zarr zarr_store = series.aszarr() subset = zarr_store[0, 5:15, 100:200, 100:200] zarr_store.close() ``` -------------------------------- ### Load Multi-file TIFF Sequence Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/file-classes.md Example of creating a TiffSequence from multiple TIFF files and loading them as a NumPy array. ```python # Multi-file TIFF sequence sequence = tifffile.TiffSequence('stack_*.tiff') data = sequence.asarray() ``` -------------------------------- ### Get Help for Tifffile Console Script Source: https://github.com/cgohlke/tifffile/blob/master/README.rst Use the tifffile package as a console script to inspect and preview TIFF files. This command displays the available command-line options. ```bash python -m tifffile --help ``` -------------------------------- ### Open TIFF file with Zarr using Kerchunk Source: https://github.com/cgohlke/tifffile/blob/master/README.rst This snippet demonstrates how to open a TIFF file as a Zarr array using Kerchunk's `refs_as_store` utility. Ensure `kerchunk` and `tifffile` are installed. ```python from kerchunk.utils import refs_as_store import tifffile.zarr import zarr tifffile.zarr.register_codec() zarr.open(refs_as_store('temp.json'), mode='r') ``` -------------------------------- ### Write TIFF with LZW Compression Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/types.md Demonstrates writing a NumPy array to a TIFF file using LZW compression. Ensure the tifffile library is installed. ```python import tifffile import numpy as np # Write with specific compression data = np.random.rand(512, 512) tifffile.imwrite('lzw.tiff', data, compression=tifffile.COMPRESSION.lzw) ``` -------------------------------- ### Load Sequence as Zarr Store Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/file-classes.md Converts the image sequence into a Zarr store for efficient storage and access. Includes an example of accessing a subset of the data. ```python # Load with Zarr zarr_store = sequence.aszarr() subset = zarr_store[5:15, 100:200, 100:200] zarr_store.close() ``` -------------------------------- ### Read and Inspect TIFF File Properties Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/types.md Provides an example of reading a TIFF file and checking its compression, sample format (data type), and orientation. This is useful for verifying file integrity and understanding image characteristics. ```python # Read and check format with tifffile.TiffFile('image.tiff') as tif: page = tif.pages[0] # Check compression if page.compression == tifffile.COMPRESSION.lzw: print('LZW compressed') # Check dtype if page.sampleformat == tifffile.SAMPLEFORMAT.uint: print('Unsigned integer data') # Check orientation if page.orientation != tifffile.ORIENTATION.topleft: print(f'Rotated: {page.orientation}') ``` -------------------------------- ### Reading Common TIFF Tag Properties Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tag-classes.md Provides an example of reading several common TIFF tag properties like image dimensions, bits per sample, and compression from a TiffFile. ```python with tifffile.TiffFile('image.tiff') as tif: page = tif.pages[0] tags = page.tags # Read common properties print(f'Size: {tags[256].value} x {tags[257].value}') # Width x Height print(f'Bits per sample: {tags[258].value}') print(f'Samples per pixel: {tags[277].value}') print(f'Compression: {tags.get(259, 1)}') # Check for optional tags if 270 in tags: # ImageDescription print(f'Description: {tags[270].value}') if 306 in tags: # DateTime print(f'Created: {tags[306].value}') ``` -------------------------------- ### Initialize TiffWriter Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tiffwriter-class.md Illustrates the initialization of the TiffWriter with various parameters to control file creation and format. ```python def __init__( file: str | os.PathLike[Any] | FileHandle | IO[bytes], /, *, mode: Literal['w', 'x', 'r+'] | None = None, bigtiff: bool = False, byteorder: Literal['>', '<', '=', '|'] | None = None, append: bool | str = False, kind: Literal['generic', 'imagej', 'ome', 'shaped'] | None = None, imagej: bool = False, ome: bool | None = None, shaped: bool | None = None, ) -> None: pass ``` -------------------------------- ### Write Tiled Images Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/common-patterns.md Demonstrates writing images using tiled storage, which is efficient for large images. Compression can also be applied. ```python import tifffile import numpy as np data = np.random.rand(4096, 4096) # Tiled storage (efficient for large images) tifffile.imwrite( 'tiled.tiff', data, tile=(256, 256), compression='lzw' ) ``` -------------------------------- ### Write Images with Various Compression Methods Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/common-patterns.md Illustrates writing images using different compression algorithms like LZW, Deflate, PNG, Zstandard, and JPEG. ```python import tifffile import numpy as np data = np.random.rand(512, 512) # LZW compression (lossless, widely supported) tifffile.imwrite('lzw.tiff', data, compression='lzw') # Deflate/ZIP compression tifffile.imwrite('deflate.tiff', data, compression='deflate', compressionargs={'level': 9}) # PNG compression tifffile.imwrite('png.tiff', data, compression='png') # Zstandard (fast, modern) tifffile.imwrite('zstd.tiff', data, compression='zstd', compressionargs={'level': 5}) # JPEG (lossy, 8/12-bit only) data_8bit = (data * 255).astype(np.uint8) tifffile.imwrite('jpeg.tiff', data_8bit, compression='jpeg') ``` -------------------------------- ### Getting the Number of Pages Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/page-classes.md Shows how to retrieve the total number of pages in a TiffPages sequence using the len() function. ```python num_pages = len(pages) ``` -------------------------------- ### Getting the Number of TiffSeries Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/page-classes.md Shows how to retrieve the total count of TiffPageSeries within a TiffSeries object using the len() function. ```python num_series = len(tiff_series) ``` -------------------------------- ### Write OME-TIFF Files Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/common-patterns.md Shows how to write OME-TIFF files, either by using the '.ome.tiff' extension or by explicitly setting the 'kind' parameter. ```python import tifffile import numpy as np # Auto-detected by .ome.tiff extension volume = np.random.rand(10, 100, 512, 512) tifffile.imwrite( 'specimen.ome.tiff', volume, metadata={ 'axes': 'TZYX', 'TimeIncrement': 5.0, # seconds 'TimeIncrementUnit': 's', } ) # Or explicit format tifffile.imwrite('output.tiff', volume, kind='ome') ``` -------------------------------- ### Basic TIFF Operations Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/START_HERE.md Demonstrates reading a TIFF file into a NumPy array, writing a NumPy array to a TIFF file with LZW compression, and working with 3D volumes. Also shows lazy loading of large TIFF files using Zarr. ```python import tifffile import numpy as np # Read TIFF file image = tifffile.imread('photo.tiff') # Write TIFF file data = np.random.rand(512, 512) tifffile.imwrite('output.tiff', data, compression='lzw') # Work with 3D volume with tifffile.TiffFile('volume.tiff') as tif: volume = tif.asarray() print(f'Shape: {volume.shape}') # Lazy load large file zarr_store = tifffile.imread('huge.tiff', return_as='zarr') subset = zarr_store[100:200, 100:200] zarr_store.close() ``` -------------------------------- ### FileSequence aszarr() Method Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/file-classes.md Returns the image sequence as a Zarr store, enabling efficient storage and access of multi-dimensional array data. ```python def aszarr( **kwargs: Any ) -> ZarrFileSequenceStore ``` -------------------------------- ### Write Simple 2D Grayscale and 3D RGB Images Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/common-patterns.md Demonstrates writing a basic 2D grayscale image and a 3D RGB image to TIFF files. ```python import tifffile import numpy as np # 2D grayscale gray = np.random.randint(0, 256, (512, 512), dtype=np.uint8) tifffile.imwrite('gray.tiff', gray) # 3D RGB rgb = np.random.randint(0, 256, (512, 512, 3), dtype=np.uint8) tifffile.imwrite('rgb.tiff', rgb, photometric='rgb') ``` -------------------------------- ### Force Specific TIFF Format Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/configuration.md Explicitly set the TIFF variant using the `kind` option, for example, to 'shaped'. The format is usually auto-detected from the filename. ```python # Force specific format with tifffile.TiffWriter('output.tiff', kind='shaped') as tif: tif.write(data) ``` -------------------------------- ### Write Multi-page Image Stacks Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/common-patterns.md Shows how to write 3D volumes that are automatically split into pages and 4D data with axis metadata. ```python import tifffile import numpy as np # 3D volume (auto-split into pages) volume = np.random.rand(100, 512, 512) tifffile.imwrite('volume.tiff', volume) # 4D with metadata data_4d = np.random.rand(10, 50, 512, 512) tifffile.imwrite( 'timelapse.tiff', data_4d, metadata={'axes': 'TZYX'} ) ``` -------------------------------- ### FileSequence Constructor Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/file-classes.md Initializes a FileSequence object to discover and manage multiple image files. It supports various ways to specify files, including glob patterns and sequences of paths, and allows customization of reading, sorting, and axis ordering. ```APIDOC ## FileSequence Constructor ### Description Initializes a FileSequence object to discover and manage multiple image files. It supports various ways to specify files, including glob patterns and sequences of paths, and allows customization of reading, sorting, and axis ordering. ### Parameters #### Parameters - **files** (str | Sequence[str] | os.PathLike[Any] | None) - Optional - File path(s), glob pattern, or sequence of paths. - **pattern** (str | None) - Optional - Regex pattern for extracting dimensions from filenames. - **imread** (Callable[..., NDArray[Any]] | None) - Optional - Custom imread function (default: tifffile.imread). - **imreadargs** (dict[str, Any] | None) - Optional - Arguments passed to imread. - **sort** (Callable[..., Any] | bool | None) - Optional - Sorting function or enable natural sort. - **axesorder** (Sequence[int] | None) - Optional - Reorder axes. - **categories** (dict[str, dict[str, int]] | None) - Optional - Map axis values to indices. ``` -------------------------------- ### Accessing Tiff Tags from a Page Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tag-classes.md Shows how to access TIFF tags from a TiffFile page by both tag code and tag name. It also demonstrates using the get method with a default value. ```python with tifffile.TiffFile('image.tiff') as tif: page = tif.pages[0] tags = page.tags # Access by code width_tag = tags[256] # 256 = ImageWidth print(f'Width: {width_tag.value}') # Access by name length_tag = tags['ImageLength'] print(f'Height: {length_tag.value}') # Common tags print(f'Compression: {tags.get(259, "none")}') # 259 = Compression print(f'PhotometricInterpretation: {tags.get(262, "minisblack")}') # 262 ``` -------------------------------- ### FileHandle Constructor Signature Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/file-classes.md Shows the signature for the FileHandle constructor, detailing the parameters for initializing a file handle with various input types and modes. ```python def __init__( file: str | os.PathLike[Any] | FileHandle | IO[bytes], mode: Literal['r', 'w', 'r+', 'w+'] | None = None, name: str | None = None, offset: int | None = None, size: int | None = None, ) -> None ``` -------------------------------- ### Handle Invalid Append Mode Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/errors.md Illustrates how to catch a ValueError when attempting to use an invalid mode with TiffWriter in append mode. The example specifically shows an attempt to append with mode 'w', which is not permitted. ```python # Invalid append mode try: with tifffile.TiffWriter('file.tiff', append=True, mode='w') as tif: tif.write(data) except ValueError as e: print(f'Cannot append with mode w: {e}') ``` -------------------------------- ### Extracting Image Data as Zarr Store Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tifffile-class.md Shows how to use the aszarr() method to extract image data as a Zarr store for lazy or chunked access. Remember to call .close() when done. ```python with tifffile.TiffFile('image.tiff') as tif: zarr_store = tif.aszarr() # ... use zarr_store ... zarr_store.close() ``` -------------------------------- ### Create BigTIFF for Large Files Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tiffwriter-class.md Illustrates the creation of a BigTIFF file, which supports files larger than 4GB, by setting the `bigtiff=True` parameter. ```python # BigTIFF for large files with tifffile.TiffWriter('large.bigtiff', bigtiff=True) as tif: tif.write(large_volume) ``` -------------------------------- ### Read TIFF file and access data Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tifffile-class.md Demonstrates how to open a TIFF file using a context manager and extract image data as a NumPy array. Shows how to print the shape and data type of the extracted data. ```python import tifffile # Read TIFF file with tifffile.TiffFile('image.tiff') as tif: data = tif.asarray() print(f'Shape: {data.shape}, Dtype: {data.dtype}') ``` -------------------------------- ### Handle NotImplementedError with File Sequences Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/errors.md Demonstrates how to handle NotImplementedError when using return_as='xarray' with file sequences. A workaround is provided to read individual files. ```python import tifffile import glob # Unsupported combinations try: # This will raise NotImplementedError data = tifffile.imread('sequence_*.tiff', return_as='xarray') except NotImplementedError as e: print(f'Unsupported: {e}') # Use workaround: read individual files files = sorted(glob.glob('sequence_*.tiff')) arrays = [tifffile.imread(f, return_as='xarray') for f in files] ``` -------------------------------- ### Read TIFF as Zarr Store Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/zarr-and-xarray.md Demonstrates reading a single TIFF file as a Zarr store for lazy loading. Shows how to access shape, dtype, and chunks, perform lazy indexing, and save the Zarr store to disk. Requires the tifffile and zarr libraries. ```python import tifffile # Read TIFF as Zarr store zarr_store = tifffile.imread('image.tiff', return_as='zarr') print(f'Shape: {zarr_store.shape}') print(f'Dtype: {zarr_store.dtype}') print(f'Chunks: {zarr_store.chunks}') # Lazy indexing (only reads selected data) subset = zarr_store[100:200, 100:200] print(f'Read subset: {subset.shape}') # Save to disk for future use zarr_store.to_file('cached.zarr') zarr_store.close() ``` -------------------------------- ### Write OME-TIFF Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tiffwriter-class.md Shows how to write an OME-TIFF file, which is automatically detected by the '.ome.tiff' extension. This is suitable for multi-dimensional image data. ```python # Write OME-TIFF (auto-detected from .ome.tiff extension) with tifffile.TiffWriter('image.ome.tiff') as tif: volume = np.random.rand(100, 512, 512) tif.write(volume) ``` -------------------------------- ### Write Indexed Color Images with Colormap Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/common-patterns.md Demonstrates writing an indexed color image where pixel values map to specific colors defined in a colormap. ```python import tifffile import numpy as np # Indexed color image with palette gray_data = np.random.randint(0, 256, (512, 512), dtype=np.uint8) # Create color map (256 colors x 3 channels) colormap = np.arange(256 * 3, dtype=np.uint16).reshape(256, 3) tifffile.imwrite( 'palette.tiff', gray_data, photometric='palette', colormap=colormap ) ``` -------------------------------- ### Check TIFF File Format Before Opening Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/errors.md Shows how to read the initial bytes of a file to verify if it has the correct TIFF magic numbers ('II' or 'MM') before attempting to open it with tifffile. ```python import tifffile import struct with open('file.bin', 'rb') as f: magic = f.read(2) if magic not in {b'II', b'MM'}: print('Not a TIFF file') else: with tifffile.TiffFile('file.bin') as tif: # Process TIFF pass ``` -------------------------------- ### Write TIFF File Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/README.md Shows how to write TIFF files, including simple writes, compression options, multi-page volumes, and OME-TIFF with metadata. ```python import tifffile import numpy as np # Simple write data = np.random.rand(512, 512) tifffile.imwrite('output.tiff', data) # With compression tifffile.imwrite('compressed.tiff', data, compression='lzw') # Multi-page volume volume = np.random.rand(100, 512, 512) tifffile.imwrite('volume.tiff', volume) # OME-TIFF with metadata tifffile.imwrite('specimen.ome.tiff', volume, metadata={'axes': 'ZYX'}) ``` -------------------------------- ### Create and Write Tiled OME-TIFF via Zarr Source: https://github.com/cgohlke/tifffile/blob/master/README.rst Create an OME-TIFF file with an empty, tiled image series and write to it using the Zarr interface. Note: compression is not supported for this operation. ```python imwrite( 'temp2.ome.tif', shape=(8, 800, 600), dtype='uint16', photometric='minisblack', tile=(128, 128), metadata={'axes': 'CYX'}, ) store = imread('temp2.ome.tif', mode='r+', return_as='zarr') z = zarr.open(store, mode='r+') z z[3, 100:200, 200:300:2] = 1024 store.close() ``` -------------------------------- ### Write Images with Metadata Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/common-patterns.md Shows how to embed various metadata like resolution, datetime, software, description, and custom key-value pairs into a TIFF file. ```python import tifffile import numpy as np from datetime import datetime data = np.random.rand(512, 512) tifffile.imwrite( 'annotated.tiff', data, resolution=(72.0, 72.0), resolutionunit='inch', datetime=datetime.now(), software='MyApp 1.0', description='Specimen image from experiment XYZ', metadata={'acquisition': 'confocal', 'objective': '40x'} ) ``` -------------------------------- ### FileSequence Constructor Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/file-classes.md Initializes a FileSequence object. It can discover files using a glob pattern or a list of paths, and allows customization of the image reading function, sorting, and axis ordering. ```python def __init__( files: str | Sequence[str] | os.PathLike[Any] | None = None, *, pattern: str | None = None, imread: Callable[..., NDArray[Any]] | None = None, imreadargs: dict[str, Any] | None = None, sort: Callable[..., Any] | bool | None = None, axesorder: Sequence[int] | None = None, categories: dict[str, dict[str, int]] | None = None, ) -> None ``` -------------------------------- ### Read TIFF File Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/README.md Demonstrates basic reading of TIFF files, including using a context manager for explicit file handling and lazy loading for large files using Zarr. ```python import tifffile # Simple read image = tifffile.imread('image.tiff') # With context manager with tifffile.TiffFile('image.tiff') as tif: data = tif.asarray() print(f'Shape: {data.shape}, Type: {data.dtype}') # Lazy loading for large files zarr_store = tifffile.imread('large.tiff', return_as='zarr') subset = zarr_store[100:200, 100:200] zarr_store.close() ``` -------------------------------- ### FileSequence.aszarr() Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/file-classes.md Returns the image sequence as a Zarr store, allowing for efficient storage and access of multi-dimensional array data. ```APIDOC ## FileSequence.aszarr() ### Description Returns the image sequence as a Zarr store, allowing for efficient storage and access of multi-dimensional array data. ### Parameters #### Parameters - **kwargs** (Any) - Additional keyword arguments to pass to the Zarr store creation. ``` -------------------------------- ### Accessing OME Metadata from OME-TIFF File Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tag-classes.md Demonstrates how to open an OME-TIFF file, check for OME format, access OME metadata, and print series information. ```python with tifffile.TiffFile('specimen.ome.tiff') as tif: # Check if OME format if tif.is_ome: omexml = tif.omexml # Access OME metadata metadata_dict = omexml.asdict() # Series information for i, series in enumerate(omexml.images): print(f'Series {i}: {series}') ``` -------------------------------- ### Tiled Image Write with Compression Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/configuration.md Writes image data using tiling and LZW compression. Tiling can improve read performance for large images. ```python import tifffile import numpy as np # Tiled write with tifffile.TiffWriter('tiled.tiff') as tif: tif.write(data, tile=(128, 128), compression='lzw') ``` -------------------------------- ### Lazy Loading TIFF Files Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/common-patterns.md Demonstrates lazy loading of large TIFF files using Zarr for out-of-core access or memory mapping for direct access without loading the entire file into RAM. Also shows selective reading of specific slices. ```python import tifffile # Zarr for large files zarr_store = tifffile.imread('large.tiff', return_as='zarr') subset = zarr_store[100:200, 100:200] zarr_store.close() # Memory mapping data = tifffile.memmap('uncompressed.tiff') roi = data[50:100, 50:100] # Selective reading roi = tifffile.imread('large.tiff', selection=slice(100, 200), slice(100, 200)) ``` -------------------------------- ### Work with File Sequences Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/README.md Illustrates reading TIFF file sequences and extracting dimensions from filenames using patterns. ```python import tifffile # Read file sequence sequence = tifffile.FileSequence('images_*.tiff') data = sequence.asarray() # Extract dimensions from filenames sequence = tifffile.FileSequence( 'img_t{t:02d}_z{z:02d}.tiff', pattern=r'img_t(?P\d+)_z(?P\d+)' ) ``` -------------------------------- ### Inspect TIFF file from command line Source: https://github.com/cgohlke/tifffile/blob/master/README.rst Use the `tifffile` module as a command-line tool to inspect the contents of a TIFF file. This is useful for quick examination of file metadata and structure. ```bash python -m tifffile temp.ome.tif ``` -------------------------------- ### Saving TIFF as Zarr Store Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/zarr-and-xarray.md Shows how to read a TIFF image and save it as a Zarr store for efficient storage and retrieval. It also demonstrates how to open a previously saved Zarr store for cached access. ```python import tifffile # Read and save as Zarr zarr_store = tifffile.imread('image.tiff', return_as='zarr') zarr_store.to_file('image.zarr') zarr_store.close() # Later: open cached Zarr import zarr cached = zarr.open('image.zarr') data = cached[:] ``` -------------------------------- ### FileSequence asarray() Method Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/file-classes.md Loads the entire image sequence into a NumPy array. Supports parallel loading with maxworkers and specifying an output array or file. ```python def asarray( out: str | IO[bytes] | NDArray[Any] | None = None, maxworkers: int | None = None, buffersize: int | None = None, out_inplace: bool | None = None, ) -> NDArray[Any] ``` -------------------------------- ### Inspect TIFF File Structure Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/README.md Demonstrates how to inspect the structure of a TIFF file, including format detection, page information, and series details. ```python import tifffile with tifffile.TiffFile('image.tiff') as tif: # Format detection print(f'OME: {tif.is_ome}') print(f'BigTIFF: {tif.is_bigtiff}') # Page info for i, page in enumerate(tif.pages): print(f'Page {i}: {page.shape} {page.dtype}') print(f' Compression: {page.compression}') # Series info for i, series in enumerate(tif.series()): print(f'Series {i}: {series.shape} {series.axes}') ``` -------------------------------- ### Handle OSError with tifffile Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/errors.md Demonstrates how to catch OSError exceptions when opening or reading TIFF files. Also shows handling potential errors during file writing. ```python import tifffile # Handle file system errors try: with tifffile.TiffFile('protected.tiff') as tif: data = tif.asarray() except OSError as e: print(f'File error: {e}') # Safe file writing try: tifffile.imwrite('output.tiff', data) except OSError as e: print(f'Cannot write file: {e}') ``` -------------------------------- ### OmeXml asdict() Method Signature Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tag-classes.md Provides the method signature for converting OME metadata to a dictionary. ```python def asdict(self) -> dict[str, Any] **Returns:** Dictionary representation of OME metadata. ``` -------------------------------- ### Reading TIFF Files with tifffile.imread Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/main-functions.md Demonstrates various ways to read TIFF files using tifffile.imread, including reading single files, specific pages, page ranges, sequences, and returning data as xarray or Zarr stores. Also shows selective reading with Zarr-style indexing. ```python import tifffile import numpy as np # Read single file as NumPy array data = tifffile.imread('image.tiff') print(data.shape, data.dtype) # Read specific page page_5 = tifffile.imread('image.tiff', key=5) # Read page range pages = tifffile.imread('image.tiff', key=slice(10, 20)) # Read file sequence with glob pattern sequence = tifffile.imread('images_*.tiff') # Return as xarray with coordinates data_xr = tifffile.imread('image.tiff', return_as='xarray') # Return as Zarr store for memory-efficient access zarr_store = tifffile.imread('large_image.tiff', return_as='zarr') print(zarr_store.shape) zarr_store.close() # Selective reading with Zarr-style indexing subset = tifffile.imread('image.tiff', selection=np.s_[0:100, 100:200]) ``` -------------------------------- ### Memory-Mapped Access with tifffile Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/zarr-and-xarray.md Demonstrates direct memory mapping of TIFF files for lazy random access. This is useful for accessing subsets of large TIFF files without loading the entire image into memory. It also shows how to use memory-mappable series from TiffFile objects. ```python import tifffile # Direct memory mapping (if possible) data = tifffile.memmap('uncompressed.tiff') # Lazy random access subset = data[100:200, 100:200] # Works with memory-mappable series with tifffile.TiffFile('contiguous.tiff') as tif: series = tif.series[0] if series.is_memmappable: data = tif.asarray(out='memmap') ``` -------------------------------- ### Accessing TiffPages by Index Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/page-classes.md Demonstrates how to access individual pages or slices from a TiffPages sequence using indexing. ```python page = pages[0] # First page pages_slice = pages[0:10] # Pages 0-9 last = pages[-1] # Last page ``` -------------------------------- ### Generate OME-TIFF Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/configuration.md Create OME-TIFF files by using the '.ome.tiff' file extension. Metadata, such as axes, can be provided. ```python # OME-TIFF (auto-detected from .ome.tiff extension) with tifffile.TiffWriter('specimen.ome.tiff') as tif: tif.write(volume, metadata={'axes': 'TZYX'}) ``` -------------------------------- ### Accessing Compression Enum Members Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/types.md Demonstrates how to access members of the COMPRESSION enumeration by name or value, and how to check for membership. ```python # By name codec = tifffile.COMPRESSION.lzw # By value codec = tifffile.COMPRESSION(5) # Check membership if page.compression == tifffile.COMPRESSION.lzw: print('LZW compressed') ``` -------------------------------- ### Reading Multi-resolution TIFF as Zarr Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/zarr-and-xarray.md Demonstrates reading a multi-resolution (pyramidal) TIFF file and saving it as a Zarr store with multiscales metadata. This format is compatible with the OME-Zarr specification. ```python import tifffile # Read multi-resolution TIFF as Zarr with multiscales zarr_store = tifffile.imread( 'pyramid.ome.tiff', return_as='zarr', multiscales=True ) # Zarr structure includes multiscales metadata # Compatible with OME-Zarr spec ``` -------------------------------- ### Write Zarr Store to FSSpec Reference (TiffSequence) Source: https://github.com/cgohlke/tifffile/blob/master/README.rst Write a Zarr store obtained from a TiffSequence to a fsspec ReferenceFileSystem in JSON format. ```python store = image_sequence.aszarr() store.write_fsspec('temp.json', url='file://', zarr_format=3) ``` -------------------------------- ### Work with file sequences Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/index.md Load a sequence of TIFF files matching a pattern into a single array. Requires importing tifffile. ```python import tifffile sequence = tifffile.FileSequence('pattern_*.tiff') data = sequence.asarray() ``` -------------------------------- ### Create Memory-Mapped TIFF Source: https://github.com/cgohlke/tifffile/blob/master/README.rst Create a TIFF file with an empty image and write to a memory-mapped NumPy array. This method does not support compression or tiling. ```python >>> memmap_image = memmap( ... 'temp.tif', shape=(256, 256, 3), dtype='float32', photometric='rgb' ... ) >>> type(memmap_image) >>> memmap_image[255, 255, 1] = 1.0 >>> memmap_image.flush() >>> del memmap_image ``` -------------------------------- ### Custom File Sorting Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/configuration.md Illustrates how to provide a custom sorting function to FileSequence to order files based on specific criteria, such as a numeric part of the filename. ```python sequence = tifffile.FileSequence( 'images_*.tiff', sort=lambda x: int(x.split('_')[1]) ) ``` -------------------------------- ### Read File Sequence as Zarr Store Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/zarr-and-xarray.md Demonstrates reading a sequence of TIFF files as a Zarr store, enabling access via array indexing. This is useful for handling multi-page or time-series TIFF data lazily. Requires the tifffile and zarr libraries. ```python import tifffile # Read file sequence as Zarr zarr_store = tifffile.imread('img_*.tiff', return_as='zarr') # Access via array indexing frame_0 = zarr_store[0] subset = zarr_store[10:20, 100:200, 100:200] zarr_store.close() ``` -------------------------------- ### TiffWriter Constructor Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tiffwriter-class.md Initializes a TiffWriter instance to save image data to a TIFF file. It supports various modes, TIFF variants, and options for handling large files and byte order. ```APIDOC ## TiffWriter Constructor ### Description Initializes a TiffWriter instance to save image data to a TIFF file. It supports various modes, TIFF variants, and options for handling large files and byte order. ### Parameters #### File Path or Stream - **file** (str | os.PathLike[Any] | FileHandle | IO[bytes]) - Required - Output file path or binary stream. #### Options - **mode** (Literal['w', 'x', 'r+'] | None) - Optional, Default: 'w' - File mode: 'w' (write, truncate), 'x' (exclusive), 'r+' (append). - **bigtiff** (bool) - Optional, Default: False - Write 64-bit BigTIFF format (enables files >4GB). - **byteorder** (Literal['>', '<', '=', '|'] | None) - Optional, Default: System - Byte order: '<' little-endian, '>' big-endian. - **append** (bool | str) - Optional, Default: False - Append to existing TIFF file. Use 'force' to append with metadata. - **kind** (Literal['generic', 'imagej', 'ome', 'shaped'] | None) - Optional, Default: None - TIFF variant. None auto-detects from filename. - **imagej** (bool) - Optional, Default: False - Alias for kind='imagej'. - **ome** (bool | None) - Optional, Default: None - Alias for kind='ome'. - **shaped** (bool | None) - Optional, Default: None - Alias for kind='shaped'. ### Raises - **ValueError**: Cannot append without 'r+' mode; append='force' with metadata file; invalid byteorder; invalid kind. - **UserWarning**: BigTIFF with ImageJ format (nonconformant). ### Examples ```python import tifffile import numpy as np # Create new TIFF file with tifffile.TiffWriter('output.tiff') as tif: data = np.random.rand(512, 512) tif.write(data) # Write OME-TIFF (auto-detected from .ome.tiff extension) with tifffile.TiffWriter('image.ome.tiff') as tif: volume = np.random.rand(100, 512, 512) tif.write(volume) # BigTIFF for large files with tifffile.TiffWriter('large.bigtiff', bigtiff=True) as tif: tif.write(large_volume) # Append to existing file with tifffile.TiffWriter('stack.tiff', append=True) as tif: tif.write(new_frame) ``` ``` -------------------------------- ### Iterate and Access TiffPages Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/page-classes.md Shows how to open a TIFF file and iterate over its pages, accessing properties like shape and compression. Also demonstrates accessing the first and last pages. ```python import tifffile with tifffile.TiffFile('multipage.tiff') as tif: # Iterate over pages for i, page in enumerate(tif.pages): print(f'Page {i}: shape={page.shape}, dtype={page.dtype}') print(f' Compression: {page.compression}') print(f' Is tiled: {page.is_tiled}') # Access first page first = tif.pages[0] data = first.asarray() # Access last page last = tif.pages[-1] print(f'Last page: {last.shape}') ``` -------------------------------- ### Accessing TIFF File Properties Source: https://github.com/cgohlke/tifffile/blob/master/_autodocs/api-reference/tifffile-class.md Demonstrates how to access basic properties of a TiffFile object, such as byte order, filename, and file handle. ```python with tifffile.TiffFile('image.tiff') as tif: print(f'Byte order: {tif.byteorder}') print(f'Filename: {tif.filename}') print(f'File handle: {tif.filehandle}') ```