tifffile

Read and write TIFF files.

Tifffile is a comprehensive Python library to

  1. store NumPy arrays in TIFF (Tagged Image File Format) files, and

  2. read image and metadata from TIFF-like files used in bioimaging.

Image and metadata can be read from TIFF, BigTIFF, OME-TIFF, GeoTIFF, Adobe DNG, ZIF (Zoomable Image File Format), MetaMorph STK, Zeiss LSM, ImageJ hyperstack, Micro-Manager MMStack and NDTiff, SGI, NIHImage, Olympus FluoView and SIS, ScanImage, Molecular Dynamics GEL, Aperio SVS, Leica SCN, Roche BIF, PerkinElmer QPTIFF (QPI, PKI), Hamamatsu NDPI, Argos AVS, Philips DP, and ThermoFisher EER formatted files.

Image data can be read as NumPy arrays or Zarr arrays/groups from strips, tiles, pages (IFDs), SubIFDs, higher-order series, and pyramidal levels.

Image data can be written to TIFF, BigTIFF, OME-TIFF, and ImageJ hyperstack compatible files in multi-page, volumetric, pyramidal, memory-mappable, tiled, predicted, or compressed form.

Many compression schemes, predictors, and data types are supported via the imagecodecs library, including LZW, PackBits, Deflate, CCITT, PIXTIFF, LZMA, LERC, Zstd, JPEG (8 and 12-bit, lossless), JPEG 2000, JPEG XR, JPEG XL, WebP, PNG, EER, Jetraw, 24-bit floating-point, packed integers, and horizontal differencing.

Tifffile can also be used to inspect TIFF structures, read image data from multi-dimensional file sequences, write fsspec ReferenceFileSystem for TIFF files and image file sequences, patch TIFF tag values, and parse many proprietary metadata formats.

Author:

Christoph Gohlke

License:

BSD-3-Clause

Version:

2026.5.15

DOI:

10.5281/zenodo.6795860

Quickstart

Install the tifffile package and all dependencies from the Python Package Index:

python -m pip install -U tifffile[all]

Tifffile is also available in other package repositories such as Anaconda, Debian, and MSYS2.

The tifffile library is type annotated and documented via docstrings:

python -c "import tifffile; help(tifffile)"

Tifffile can be used as a console script to inspect and preview TIFF files:

python -m tifffile --help

See Examples for using the programming interface.

Source code and support are available on GitHub.

Support is also provided on the image.sc forum.

Requirements

This revision was tested with the following requirements and dependencies (other versions may work):

  • CPython 3.12.10, 3.13.13, 3.14.5, 3.15.0b1 64-bit

  • NumPy 2.4.4

  • Imagecodecs 2026.5.10 (required for encoding or decoding LZW, JPEG, etc. compressed segments)

  • Xarray 2026.4.0 (required only for reading xarray DataArrays)

  • Matplotlib 3.10.9 (required for plotting)

  • Lxml 6.1.0 (required only for validating and printing XML)

  • Zarr 3.2.1 (required only for using Zarr stores)

  • Kerchunk 0.2.10 (required only for opening ReferenceFileSystem files)

Revisions

2026.5.15

  • Update ZarrFileSequenceStore to zarr format 3 (breaking).

  • Derive ZarrFileSequenceStore dimension names from FileSequence.dims.

  • Add option to override dimension names in zarr stores.

  • Add support for Python 3.15.

2026.5.2

  • Change TiffFile.series from list to callable TiffSeries sequence (breaking).

  • Remove TiffPageSeries squeeze dual-state (breaking).

  • Remove TiffPageSeries.get_shape, get_axes, and get_coords (breaking).

  • Remove ZarrTiffStore squeeze parameter (breaking).

  • Update ZarrTiffStore to zarr format 3 and multiscales to NGFF 0.5 (breaking).

  • Update multiscales zarr format 2 fsspec files to NGFF 0.4 (breaking).

  • Remove generic TiffPage coords (breaking).

  • Change dims and sizes to use single-char axis codes (breaking).

  • Add zarr format 3 compatible Tiff codec.

  • Add asxarray methods to TiffFile, TiffPage, TiffPageSeries (requires xarray).

  • Add geotiff kind of TiffPageSeries.

  • Add mpp and coord_offsets/scales/units properties to TiffPageSeries.

  • Add attrs property to TiffPage and TiffPageSeries.

  • Add kind and squeeze parameters to memmap.

  • Add kind parameter to imwrite and TiffFile; deprecate ome, imagej, shaped.

  • Add return_as parameter to imread; deprecate aszarr.

  • Fix writing TIFF trees (#326).

  • Fix wrong TiffTagRegistry entries (#323).

  • Implement TiffPageSeries.coords property.

  • Deprecate kwargs to FileSequence.asarray; use imreadargs.

  • Require zarr>=3.2.0 for zarr support.

  • Drop support for numpy 2.0 (SPEC0, #324).

2026.4.11

  • Add option to write zarr format 3 fsspec reference file system.

  • Support reading TIFF with embedded C2PA manifest.

  • Sync API of imagecodecs fallback implementations (#320).

  • Do not use defusedxml.

  • Drop support for Python 3.11.

2026.3.3

  • Do not convert TVIPS pixel sizes to m (#319).

  • Support writing packed integers with imagecodecs > 2026.1.14.

  • Support reading ccitt compressed images with imagecodecs > 2026.1.14.

2026.2.24

  • Remove deprecated TiffPages.pages and FileSequence.files (breaking).

  • Remove stripnull, stripascii, and bytestr functions (breaking).

  • Rewrite command line interfaces (breaking).

  • Support Experimenter and Project elements in OmeXml.

  • Refactor TiffPages.

  • Fix code review issues.

2026.2.20

  • Fix rounding of high resolutions (#318).

  • Fix code review issues.

2026.2.16

  • Optimize reading multi-file pyramidal OME TIFF files.

2026.2.15

  • Support reading multi-file pyramidal OME TIFF files (image.sc/t/119259).

2026.1.28

  • Deprecate colormaped parameter in imagej_description (use colormapped).

  • Fix code review issues.

2026.1.14

Refer to the CHANGES file for older revisions.

Notes

TIFF, the Tagged Image File Format, was created by the Aldus Corporation and Adobe Systems Incorporated.

Tifffile supports a large subset of the TIFF6 specification, mainly 1-32, and 64-bit integer, 16, 32, and 64-bit float, grayscale and multi-sample images. Specifically, OJPEG compression, chroma subsampling without JPEG compression, color space transformations, samples with differing types, or IPTC, ICC, and XMP metadata are not implemented.

Besides classic TIFF, tifffile supports several TIFF-like formats that do not strictly adhere to the TIFF6 specification. Some formats extend TIFF capabilities in various ways, including exceeding the 4 GB limit, handling multi-dimensional data, or working around format constraints:

  • BigTIFF is identified by version number 43 and uses different file header, IFD, and tag structures with 64-bit offsets. The format also adds 64-bit data types. Tifffile can read and write BigTIFF files.

  • ImageJ hyperstacks store all image data, which may exceed 4 GB, contiguously after the first IFD. Files > 4 GB contain one IFD only. The size and shape of the up to 6-dimensional image data can be determined from the ImageDescription tag of the first IFD, which is Latin-1 encoded. Tifffile can read and write ImageJ hyperstacks.

  • OME-TIFF files store up to 8-dimensional image data in one or multiple TIFF or BigTIFF files. The UTF-8 encoded OME-XML metadata found in the ImageDescription tag of the first IFD defines the position of TIFF IFDs in the high-dimensional image data. Tifffile can read OME-TIFF files and write NumPy arrays to single-file OME-TIFF.

  • Micro-Manager NDTiff stores multi-dimensional image data in one or more classic TIFF files. Metadata contained in a separate NDTiff.index binary file defines the position of the TIFF IFDs in the image array. Each TIFF file also contains metadata in a non-TIFF binary structure at offset 8. Downsampled image data of pyramidal datasets are stored in separate folders. Tifffile can read NDTiff files. Version 0 and 1 series, tiling, stitching, and multi-resolution pyramids are not supported.

  • Micro-Manager MMStack stores 6-dimensional image data in one or more classic TIFF files. Metadata contained in non-TIFF binary structures and JSON strings define the image stack dimensions and the position of the image frame data in the file and the image stack. The TIFF structures and metadata are often corrupted or wrong. Tifffile can read MMStack files.

  • Carl Zeiss LSM files store all IFDs below 4 GB and wrap around 32-bit StripOffsets pointing to image data above 4 GB. The StripOffsets of each series and position require separate unwrapping. The StripByteCounts tag contains the number of bytes for the uncompressed data. Tifffile can read LSM files of any size.

  • MetaMorph STK files contain additional image planes stored contiguously after the image data of the first page. The total number of planes is equal to the count of the UIC2 tag. Tifffile can read STK files.

  • ZIF, the Zoomable Image File format, is a subspecification of BigTIFF with SGI’s ImageDepth extension and additional compression schemes. Only little-endian, tiled, interleaved, 8-bit per sample images with JPEG, PNG, JPEG XR, and JPEG 2000 compression are allowed. Tifffile can read and write ZIF files.

  • Hamamatsu NDPI files use some 64-bit offsets in the file header, IFD, and tag structures. Single, LONG typed tag values can exceed 32-bit. The high bytes of 64-bit tag values and offsets are stored after IFD structures. Tifffile can read NDPI files > 4 GB. JPEG compressed segments with dimensions >65530 or missing restart markers cannot be decoded with common JPEG libraries. Tifffile works around this limitation by separately decoding the MCUs between restart markers, which performs poorly. BitsPerSample, SamplesPerPixel, and PhotometricInterpretation tags may contain wrong values, which can be corrected using the value of tag 65441.

  • Philips TIFF slides store padded ImageWidth and ImageLength tag values for tiled pages. The values can be corrected using the DICOM_PIXEL_SPACING attributes of the XML formatted description of the first page. Tile offsets and byte counts may be 0. Tifffile can read Philips slides.

  • Ventana/Roche BIF slides store tiles and metadata in a BigTIFF container. Tiles may overlap and require stitching based on the TileJointInfo elements in the XMP tag. Volumetric scans are stored using the ImageDepth extension. Tifffile can read BIF and decode individual tiles but does not perform stitching.

  • ScanImage optionally allows corrupted non-BigTIFF files > 2 GB. The values of StripOffsets and StripByteCounts can be recovered using the constant differences of the offsets of IFD and tag values throughout the file. Tifffile can read such files if the image data are stored contiguously in each page.

  • GeoTIFF sparse files allow strip or tile offsets and byte counts to be 0. Such segments are implicitly set to 0 or the NODATA value on reading. Tifffile can read GeoTIFF sparse files.

  • Tifffile shaped files store the array shape and user-provided metadata of multi-dimensional image series in JSON format in the ImageDescription tag of the first page of the series. The format allows multiple series, SubIFDs, sparse segments with zero offset and byte count, and truncated series, where only the first page of a series is present, and the image data are stored contiguously. No other software besides Tifffile supports the truncated format.

Other libraries for reading, writing, inspecting, or manipulating scientific TIFF files from Python are bioio, aicsimageio, apeer-ometiff-library, bigtiff, fabio.TiffIO, GDAL, imread, large_image, openslide-python, opentile, pylibtiff, pylsm, pymimage, python-bioformats, pytiff, scanimagetiffreader-python, SimpleITK, slideio, tiffslide, tifftools, tyf, xtiff, and ndtiff.

References

Examples

Write a NumPy array to a single-page RGB TIFF file:

>>> import numpy
>>> data = numpy.random.randint(0, 255, (256, 256, 3), 'uint8')
>>> imwrite('temp.tif', data, photometric='rgb')

Read the image from the TIFF file as NumPy array:

>>> image = imread('temp.tif')
>>> image.shape
(256, 256, 3)

Use the photometric and planarconfig arguments to write a 3x3x3 NumPy array to an interleaved RGB, a planar RGB, or a 3-page grayscale TIFF:

>>> data = numpy.random.randint(0, 255, (3, 3, 3), 'uint8')
>>> imwrite('temp.tif', data, photometric='rgb')
>>> imwrite('temp.tif', data, photometric='rgb', planarconfig='separate')
>>> imwrite('temp.tif', data, photometric='minisblack')

Use the extrasamples argument to specify how extra components are interpreted, for example, for an RGBA image with unassociated alpha channel:

>>> data = numpy.random.randint(0, 255, (256, 256, 4), 'uint8')
>>> imwrite('temp.tif', data, photometric='rgb', extrasamples=['unassalpha'])

Write a 3-dimensional NumPy array to a multi-page, 16-bit grayscale TIFF file:

>>> data = numpy.random.randint(0, 2**12, (64, 301, 219), 'uint16')
>>> imwrite('temp.tif', data, photometric='minisblack')

Read the whole image stack from the multi-page TIFF file as NumPy array:

>>> image_stack = imread('temp.tif')
>>> image_stack.shape
(64, 301, 219)
>>> image_stack.dtype
dtype('uint16')

Read the image from the first page in the TIFF file as NumPy array:

>>> image = imread('temp.tif', key=0)
>>> image.shape
(301, 219)

Read images from a selected range of pages:

>>> images = imread('temp.tif', key=range(4, 40, 2))
>>> images.shape
(18, 301, 219)

Iterate over all pages in the TIFF file and successively read images:

>>> with TiffFile('temp.tif') as tif:
...     for page in tif.pages:
...         image = page.asarray()
...

Get information about the image stack in the TIFF file without reading any image data:

>>> tif = TiffFile('temp.tif')
>>> len(tif.pages)  # number of pages in the file
64
>>> page = tif.pages[0]  # get shape and dtype of image in first page
>>> page.shape
(301, 219)
>>> page.dtype
dtype('uint16')
>>> page.axes
'YX'
>>> series = tif.series[0]  # get shape and dtype of first image series
>>> series.shape
(64, 301, 219)
>>> series.dtype
dtype('uint16')
>>> series.axes
'QYX'
>>> tif.close()

Inspect the “XResolution” tag from the first page in the TIFF file:

>>> with TiffFile('temp.tif') as tif:
...     tag = tif.pages[0].tags['XResolution']
...
>>> tag.value
(1, 1)
>>> tag.name
'XResolution'
>>> tag.code
282
>>> tag.count
1
>>> tag.dtype
<DATATYPE.RATIONAL: 5>

Iterate over all tags in the TIFF file:

>>> with TiffFile('temp.tif') as tif:
...     for page in tif.pages:
...         for tag in page.tags:
...             tag_name, tag_value = tag.name, tag.value
...

Overwrite the value of an existing tag, for example, XResolution:

>>> with TiffFile('temp.tif', mode='r+') as tif:
...     _ = tif.pages[0].tags['XResolution'].overwrite((96000, 1000))
...

Write a 5-dimensional floating-point array using BigTIFF format, separate color components, tiling, Zlib compression level 8, horizontal differencing predictor, and additional metadata:

>>> data = numpy.random.rand(2, 5, 3, 301, 219).astype('float32')
>>> imwrite(
...     'temp.tif',
...     data,
...     bigtiff=True,
...     photometric='rgb',
...     planarconfig='separate',
...     tile=(32, 32),
...     compression='zlib',
...     compressionargs={'level': 8},
...     predictor=True,
...     metadata={'axes': 'TZCYX'},
... )

Write a 10 fps time series of volumes with xyz voxel size 2.6755x2.6755x3.9474 micron^3 to an ImageJ hyperstack formatted TIFF file:

>>> volume = numpy.random.randn(6, 57, 256, 256).astype('float32')
>>> image_labels = [f'{i}' for i in range(volume.shape[0] * volume.shape[1])]
>>> imwrite(
...     'temp.tif',
...     volume,
...     kind='imagej',
...     resolution=(1.0 / 2.6755, 1.0 / 2.6755),
...     metadata={
...         'spacing': 3.947368,
...         'unit': 'um',
...         'finterval': 1 / 10,
...         'fps': 10.0,
...         'axes': 'TZYX',
...         'Labels': image_labels,
...     },
... )

Read the volume and metadata from the ImageJ hyperstack file as xarray DataArray:

>>> with TiffFile('temp.tif') as tif:
...     volume = tif.asxarray()
...     imagej_metadata = tif.imagej_metadata
...
>>> volume
<xarray.DataArray '' (T: 6, Z: 57, Y: 256, X: 256)> Size: 90MB
array([[[[...]]]],
        shape=(6, 57, 256, 256), dtype=float32)
Coordinates:
    * T        (T) float64 48B 0.0 0.1 0.2 0.3 0.4 0.5
    * Z        (Z) float64 456B 0.0 3.947 ... 221.1
    * Y        (Y) float32 1kB 0.0 2.675 ... 682.3
    * X        (X) float32 1kB 0.0 2.675 ... 682.3
Attributes:
    photometric:    minisblack
    mode:           grayscale
...
>>> imagej_metadata['slices']
57
>>> imagej_metadata['frames']
6

Memory-map the contiguous image data in the ImageJ hyperstack file:

>>> memmap_volume = memmap('temp.tif')
>>> memmap_volume.shape
(6, 57, 256, 256)
>>> del memmap_volume

Create a TIFF file containing an empty image and write to the memory-mapped NumPy array (note: this does not work with compression or tiling):

>>> memmap_image = memmap(
...     'temp.tif', shape=(256, 256, 3), dtype='float32', photometric='rgb'
... )
>>> type(memmap_image)
<class 'numpy.memmap'>
>>> memmap_image[255, 255, 1] = 1.0
>>> memmap_image.flush()
>>> del memmap_image

Write two NumPy arrays to a multi-series TIFF file (note: other TIFF readers will not recognize the two series; use the OME-TIFF format for better interoperability):

>>> series0 = numpy.random.randint(0, 255, (32, 32, 3), 'uint8')
>>> series1 = numpy.random.randint(0, 255, (4, 256, 256), 'uint16')
>>> with TiffWriter('temp.tif') as tif:
...     tif.write(series0, photometric='rgb')
...     tif.write(series1, photometric='minisblack')
...

Read the second image series from the TIFF file:

>>> series1 = imread('temp.tif', series=1)
>>> series1.shape
(4, 256, 256)

Successively write the frames of one contiguous series to a TIFF file:

>>> data = numpy.random.randint(0, 255, (30, 301, 219), 'uint8')
>>> with TiffWriter('temp.tif') as tif:
...     for frame in data:
...         tif.write(frame, contiguous=True)
...

Append an image series to the existing TIFF file (note: this does not work with ImageJ hyperstack or OME-TIFF files):

>>> data = numpy.random.randint(0, 255, (301, 219, 3), 'uint8')
>>> imwrite('temp.tif', data, photometric='rgb', append=True)

Create a TIFF file from a generator of tiles:

>>> data = numpy.random.randint(0, 2**12, (31, 33, 3), 'uint16')
>>> def tiles(data, tileshape):
...     for y in range(0, data.shape[0], tileshape[0]):
...         for x in range(0, data.shape[1], tileshape[1]):
...             yield data[y : y + tileshape[0], x : x + tileshape[1]]
...
>>> imwrite(
...     'temp.tif',
...     tiles(data, (16, 16)),
...     tile=(16, 16),
...     shape=data.shape,
...     dtype=data.dtype,
...     photometric='rgb',
... )

Write a multi-dimensional, multi-resolution (pyramidal), multi-series OME-TIFF file with optional metadata. Sub-resolution images are written to SubIFDs. Limit parallel encoding to 2 threads. Write a thumbnail image as a separate image series:

>>> data = numpy.random.randint(0, 255, (8, 2, 512, 512, 3), 'uint8')
>>> subresolutions = 2
>>> pixelsize = 0.29  # micrometer
>>> with TiffWriter('temp.ome.tif', bigtiff=True) as tif:
...     metadata = {
...         'axes': 'TCYXS',
...         'SignificantBits': 8,
...         'TimeIncrement': 0.1,
...         'TimeIncrementUnit': 's',
...         'PhysicalSizeX': pixelsize,
...         'PhysicalSizeXUnit': 'µm',
...         'PhysicalSizeY': pixelsize,
...         'PhysicalSizeYUnit': 'µm',
...         'Channel': {'Name': ['Channel 1', 'Channel 2']},
...         'Plane': {'PositionX': [0.0] * 16, 'PositionXUnit': ['µm'] * 16},
...         'Description': 'A multi-dimensional, multi-resolution image',
...         'MapAnnotation': {  # for OMERO
...             'Namespace': 'openmicroscopy.org/PyramidResolution',
...             '1': '256 256',
...             '2': '128 128',
...         },
...     }
...     options = dict(
...         photometric='rgb',
...         tile=(128, 128),
...         compression='jpeg',
...         resolutionunit='CENTIMETER',
...         maxworkers=2,
...     )
...     tif.write(
...         data,
...         subifds=subresolutions,
...         resolution=(1e4 / pixelsize, 1e4 / pixelsize),
...         metadata=metadata,
...         **options,
...     )
...     # write pyramid levels to the two subifds
...     # in production use resampling to generate sub-resolution images
...     for level in range(subresolutions):
...         mag = 2 ** (level + 1)
...         tif.write(
...             data[..., ::mag, ::mag, :],
...             subfiletype=1,  # FILETYPE.REDUCEDIMAGE
...             resolution=(1e4 / mag / pixelsize, 1e4 / mag / pixelsize),
...             **options,
...         )
...     # add a thumbnail image as a separate series
...     # it is recognized by QuPath as an associated image
...     thumbnail = (data[0, 0, ::8, ::8] >> 2).astype('uint8')
...     tif.write(thumbnail, metadata={'Name': 'thumbnail'})
...

Access image levels in the pyramidal OME-TIFF file:

>>> baseimage = imread('temp.ome.tif')
>>> second_level = imread('temp.ome.tif', series=0, level=1)
>>> with TiffFile('temp.ome.tif') as tif:
...     series = tif.series[0]
...     assert series.kind == 'ome'
...     assert series.sizes == {'T': 8, 'C': 2, 'Y': 512, 'X': 512, 'S': 3}
...     baseimage = series.asarray()
...     second_level = series.levels[1].asarray()
...     number_levels = len(series.levels)  # includes base level
...

Read image data from a generic kind of series, ignoring OME metadata:

>>> with TiffFile('temp.ome.tif') as tif:
...     series = tif.series(kind='generic')[0]
...     assert series.kind == 'generic'
...     assert series.sizes == {'I': 16, 'Y': 512, 'X': 512, 'S': 3}
...     image = series.asarray()
...

Iterate over and decode single JPEG compressed tiles in the TIFF file:

>>> with TiffFile('temp.ome.tif') as tif:
...     fh = tif.filehandle
...     for page in tif.pages:
...         for index, (offset, bytecount) in enumerate(
...             zip(page.dataoffsets, page.databytecounts)
...         ):
...             _ = fh.seek(offset)
...             data = fh.read(bytecount)
...             tile, indices, shape = page.decode(
...                 data, index, jpegtables=page.jpegtables
...             )
...

Use Zarr to read parts of the tiled, pyramidal images in the TIFF file:

>>> import zarr
>>> store = imread('temp.ome.tif', return_as='zarr')
>>> z = zarr.open(store, mode='r')
>>> z
<Group ZarrTiffStore>
>>> z['0']  # base layer
 <Array ZarrTiffStore/0 shape=(8, 2, 512, 512, 3) dtype=uint8>
>>> z['0'][2, 0, 128:384, 256:].shape  # read a tile from the base layer
(256, 256, 3)
>>> store.close()

Load the base layer from the Zarr store as a dask array:

>>> import dask.array
>>> store = imread('temp.ome.tif', return_as='zarr')
>>> dask.array.from_zarr(store, '0')
dask.array<...shape=(8, 2, 512, 512, 3)...chunksize=(1, 1, 128, 128, 3)...
>>> store.close()

Write the Zarr store to a fsspec ReferenceFileSystem in JSON format:

>>> store = imread('temp.ome.tif', return_as='zarr')
>>> store.write_fsspec('temp.ome.tif.json', url='file://', zarr_format=3)
>>> store.close()

Open the fsspec ReferenceFileSystem as a Zarr group and read the first layer:

>>> from kerchunk.utils import refs_as_store
>>> import imagecodecs.zarr
>>> imagecodecs.zarr.register_codecs(verbose=False)
>>> z = zarr.open(refs_as_store('temp.ome.tif.json'), mode='r')
>>> z['1']  # first layer
<Array <FsspecStore(ReferenceFileSystem, /)>/1 shape=(8, 2, 256, 256, 3) ...>

Create an OME-TIFF file containing an empty, tiled image series and write to it via the Zarr interface (note: this does not work with compression):

>>> 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
<Array ZarrTiffStore shape=(8, 800, 600) dtype=uint16>
>>> z[3, 100:200, 200:300:2] = 1024
>>> store.close()

Read images from a sequence of TIFF files as NumPy array using two I/O worker threads:

>>> imwrite('temp_C001T001.tif', numpy.random.rand(64, 64))
>>> imwrite('temp_C001T002.tif', numpy.random.rand(64, 64))
>>> image_sequence = imread(
...     ['temp_C001T001.tif', 'temp_C001T002.tif'], ioworkers=2, maxworkers=1
... )
>>> image_sequence.shape
(2, 64, 64)
>>> image_sequence.dtype
dtype('float64')

Read an image stack from a series of TIFF files with a file name pattern as NumPy or Zarr arrays:

>>> image_sequence = TiffSequence('temp_C0*.tif', pattern=r'_(C)(\d+)(T)(\d+)')
>>> image_sequence.shape
(1, 2)
>>> image_sequence.axes
'CT'
>>> data = image_sequence.asarray()
>>> data.shape
(1, 2, 64, 64)
>>> store = image_sequence.aszarr()
>>> zarr.open(store, mode='r', ioworkers=2, maxworkers=1)
<Array ZarrFileSequenceStore shape=(1, 2, 64, 64) dtype=float64>
>>> image_sequence.close()

Write the Zarr store to a fsspec ReferenceFileSystem in JSON format:

>>> store = image_sequence.aszarr()
>>> store.write_fsspec('temp.json', url='file://', zarr_format=3)

Open the fsspec ReferenceFileSystem as a Zarr array:

>>> from kerchunk.utils import refs_as_store
>>> import tifffile.zarr
>>> tifffile.zarr.register_codec()
>>> zarr.open(refs_as_store('temp.json'), mode='r')
<Array <FsspecStore(ReferenceFileSystem, /)> shape=(1, 2, 64, 64) ...>

Inspect the TIFF file from the command line:

$ python -m tifffile temp.ome.tif

License

Copyright (c) 2008-2026, Christoph Gohlke
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

tifffile module

tifffile.__version__ = '2026.5.15'

Tifffile version string.

final class tifffile.FileCache(size=None, *, lock=None)

Bases: object

Keep FileHandles open.

Parameters:
  • size (int | None) – Maximum number of files to keep open. The default is 8.

  • lock (threading.RLock | NullContext | None) – Reentrant lock to synchronize reads and writes.

__init__(size=None, *, lock=None)
Parameters:
  • size (int | None)

  • lock (threading.RLock | NullContext | None)

Return type:

None

past: list[FileHandle]

FIFO list of opened files.

files: dict[FileHandle, int]

Reference counts of opened files.

keep: set[FileHandle]

Set of files to keep open.

size: int

Maximum number of files to keep open.

lock: threading.RLock | NullContext

Reentrant lock to synchronize reads and writes.

open(fh, /)

Open file, re-open if necessary.

Parameters:

fh (FileHandle)

Return type:

None

close(fh, /)

Decrement reference count of file handle and trim cache.

Parameters:

fh (FileHandle)

Return type:

None

clear()

Close all file handles opened by cache.

Return type:

None

read(fh, /, offset, bytecount, whence=0)

Return bytes read from binary file.

Parameters:
  • fh (FileHandle) – File handle to read from.

  • offset (int) – Position in file to start reading from relative to the position indicated by whence.

  • bytecount (int) – Number of bytes to read.

  • whence (int) – Relative position of offset. 0 (os.SEEK_SET) beginning of file (default). 1 (os.SEEK_CUR) current position. 2 (os.SEEK_END) end of file.

Return type:

bytes

write(fh, /, offset, data, whence=0)

Write bytes to binary file and return number of bytes written.

Parameters:
  • fh (FileHandle) – File handle to write to.

  • offset (int) – Position in file to start writing from relative to the position indicated by whence.

  • data (bytes) – Bytes to write.

  • whence (int) – Relative position of offset. 0 (os.SEEK_SET) beginning of file (default). 1 (os.SEEK_CUR) current position. 2 (os.SEEK_END) end of file.

Return type:

int

__len__()

Return number of tracked file handles.

Return type:

int

__repr__()

Return repr(self).

Return type:

str

final class tifffile.FileHandle(file, /, mode=None, *, name=None, offset=None, size=None)

Bases: object

Binary file handle.

A limited, special purpose binary file handle that can:

  • handle embedded files (for example, LSM within LSM files).

  • re-open closed files (for multi-file formats, such as OME-TIFF).

  • read and write NumPy arrays and records from file-like objects.

When initialized from another file handle, do not use the other handle unless this FileHandle is closed.

FileHandle instances are not thread-safe.

Parameters:
  • file (str | os.PathLike[Any] | FileHandle | IO[bytes]) – File name or seekable binary stream, such as open file, BytesIO, or fsspec OpenFile.

  • mode (Literal['r', 'r+', 'w', 'x', 'rb', 'r+b', 'wb', 'xb'] | None) – File open mode if file is file name. The default is ‘rb’. Files are always opened in binary mode.

  • name (str | None) – Name of file if file is binary stream.

  • offset (int | None) – Start position of embedded file. The default is the current file position.

  • size (int | None) – Size of embedded file. The default is the number of bytes from offset to the end of the file.

__init__(file, /, mode=None, *, name=None, offset=None, size=None)
Parameters:
  • file (str | os.PathLike[Any] | FileHandle | IO[bytes])

  • mode (Literal['r', 'r+', 'w', 'x', 'rb', 'r+b', 'wb', 'xb'] | None)

  • name (str | None)

  • offset (int | None)

  • size (int | None)

Return type:

None

open()

Open or re-open file.

Return type:

None

close()

Close file handle.

Return type:

None

fileno()

Return underlying file descriptor if exists, else raise OSError.

Return type:

int

writable()

Return True if stream supports writing.

Return type:

bool

seekable()

Return True if stream supports random access.

Return type:

bool

tell()

Return file’s current position.

Return type:

int

seek(offset, /, whence=0)

Set file’s current position.

Parameters:
  • offset (int) – Position of file handle relative to position indicated by whence.

  • whence (int) – Relative position of offset. 0 (os.SEEK_SET) beginning of file (default). 1 (os.SEEK_CUR) current position. 2 (os.SEEK_END) end of file.

Return type:

int

read(size=-1, /)

Return bytes read from file.

Parameters:

size (int) – Number of bytes to read from file. By default, read until the end of the file.

Return type:

bytes

readinto(buffer, /)

Read bytes from file into buffer and return number of bytes read.

Parameters:

buffer (bytearray) – Buffer to read into.

Return type:

int

write(buffer, /)

Write bytes to file and return number of bytes written.

Parameters:

buffer (bytes | memoryview[Any]) – Bytes to write to file.

Return type:

int

flush()

Flush write buffers of stream if applicable.

Return type:

None

memmap_array(dtype, shape, offset=0, *, mode='r', order='C')

Return numpy.memmap of array data stored in file.

Parameters:
  • dtype (DTypeLike | None) – Data type of array in file.

  • shape (tuple[int, ...]) – Shape of array in file.

  • offset (int) – Start position of array-data in file.

  • mode (str) – File is opened in this mode. The default is read-only.

  • order (str) – Order of ndarray memory layout. The default is ‘C’.

Return type:

NDArray[Any]

read_array(dtype, count=-1, offset=0, *, out=None)

Return NumPy array from file in native byte order.

Parameters:
  • dtype (DTypeLike | None) – Data type of array to read.

  • count (int) – Number of items to read. By default, all items are read.

  • offset (int) – Start position of array-data in file.

  • out (NDArray[Any] | None) – NumPy array to read into. By default, a new array is created.

Return type:

NDArray[Any]

read_record(dtype, shape=1, *, byteorder=None)

Return NumPy record from file.

Parameters:
  • dtype (DTypeLike | None) – Data type of record array to read.

  • shape (tuple[int, ...] | int | None) – Shape of record array to read.

  • byteorder (Literal['S', '<', '>', '=', '|'] | None) – Byte order of record array to read.

Return type:

numpy.recarray[Any, Any]

write_empty(size, /)

Append null-bytes to file.

The file position must be at the end of the file.

Parameters:

size (int) – Number of null-bytes to write to file.

Return type:

int

write_array(data, dtype=None, /)

Write NumPy array to file in C contiguous order.

Parameters:
  • data (NDArray[Any]) – Array to write to file.

  • dtype (DTypeLike | None)

Return type:

int

read_segments(offsets, bytecounts, /, indices=None, length=None, *, sort=True, lock=None, buffersize=None, flat=True)

Return iterator over segments read from file and their indices.

The purpose of this function is to

  • reduce small or random reads.

  • reduce acquiring reentrant locks.

  • synchronize seeks and reads.

  • limit size of segments read into memory at once. (ThreadPoolExecutor.map is not collecting iterables lazily).

Parameters:
  • offsets (Sequence[int]) – Offsets of segments to read from file.

  • bytecounts (Sequence[int]) – Byte counts of segments to read from file.

  • indices (Sequence[int] | None) – Indices of segments in image. The default is range(length).

  • length (int | None) – Number of segments to read from file. By default, len(offsets).

  • sort (bool) – Read segments from file in order of their offsets.

  • lock (threading.RLock | NullContext | None) – Reentrant lock to synchronize seeks and reads.

  • buffersize (int | None) – Approximate number of bytes to read from file in one pass. The default is _TIFF.BUFFERSIZE.

  • flat (bool) – Return iterator over individual (segment, index) tuples. If False, return an iterator over a list of (segment, index) tuples that are acquired in one pass.

Yields:

Individual or lists of (segment, index) tuples.

Return type:

Iterator[tuple[bytes | None, int]] | Iterator[list[tuple[bytes | None, int]]]

__repr__()

Return repr(self).

Return type:

str

__str__()

Return str(self).

Return type:

str

property name: str

Name of file or stream.

property dirname: str

Directory in which file is stored.

property path: str

Absolute path of file.

property extension: str

File name extension of file or stream.

property size: int

Size of file in bytes.

property closed: bool

File is closed.

property lock: threading.RLock | NullContext

Reentrant lock to synchronize reads and writes.

set_lock(lock)

Set reentrant lock to synchronize reads and writes.

Parameters:

lock (bool)

Return type:

None

property has_lock: bool

File uses reentrant lock to synchronize reads and writes.

property is_file: bool

File has fileno and can be memory-mapped.

class tifffile.FileSequence(imread, files, *, container=None, sort=None, parse=None, **kwargs)

Bases: Sequence[str]

Sequence of files containing compatible array data.

Parameters:
  • imread (Callable[..., NDArray[Any]]) – Function to read image array from single file.

  • files (str | os.PathLike[Any] | Sequence[str | os.PathLike[Any]] | None) – Glob file name pattern or sequence of file names. If None, use ‘*’. All files must contain array data of same shape and dtype. Binary streams are not supported.

  • container (str | os.PathLike[Any] | None) – Name or open instance of ZIP file in which files are stored.

  • sort (Callable[..., Any] | bool | None) – Function to sort file names if files is a pattern. The default is natural_sorted(). If False, disable sorting.

  • parse (Callable[..., Any] | None) – Function to parse sequence of sorted file names to dims, shape, chunk indices, and filtered file names. The default is parse_filenames`() if kwargs` contains ``'pattern'.

  • **kwargs (Any) – Additional arguments passed to parse function.

Examples

>>> filenames = ['temp_C001T002.tif', 'temp_C001T001.tif']
>>> ims = TiffSequence(filenames, pattern=r'_(C)(\d+)(T)(\d+)')
>>> ims[0]
'temp_C001T002.tif'
>>> ims.shape
(1, 2)
>>> ims.axes
'CT'
__init__(imread, files, *, container=None, sort=None, parse=None, **kwargs)
Parameters:
  • imread (Callable[..., NDArray[Any]])

  • files (str | os.PathLike[Any] | Sequence[str | os.PathLike[Any]] | None)

  • container (str | os.PathLike[Any] | None)

  • sort (Callable[..., Any] | bool | None)

  • parse (Callable[..., Any] | None)

  • kwargs (Any)

Return type:

None

imread: Callable[..., NDArray[Any]]

Function to read image array from single file.

axes: str

Character codes for dimensions in shape.

dims: tuple[str, ...]

Names of dimensions in shape.

shape: tuple[int, ...]

Shape of file series. Excludes shape of chunks in files.

indices: tuple[tuple[int, ...]]

Indices of files in shape.

asarray(*, imreadargs=None, chunkshape=None, chunkdtype=None, axestiled=None, ioworkers=1, out_inplace=None, out=None, **kwargs)

Return images from files as NumPy array.

Parameters:
  • imreadargs (dict[str, Any] | None) – Arguments passed to FileSequence.imread.

  • chunkshape (tuple[int, ...] | None) – Shape of chunk in each file. Must match FileSequence.imread(file, **imreadargs).shape. By default, this is determined by reading the first file.

  • chunkdtype (DTypeLike | None) – Data type of chunk in each file. Must match FileSequence.imread(file, **imreadargs).dtype. By default, this is determined by reading the first file.

  • axestiled (dict[int, int] | Sequence[tuple[int, int]] | None) – Axes to be tiled. Map stacked sequence axis to chunk axis.

  • ioworkers (int | None) – Maximum number of threads to execute FileSequence.imread asynchronously. If 0, use up to _TIFF.MAXIOWORKERS threads. Using threads can significantly improve runtime when reading many small files from a network share. If enabled, internal threading for the imread function should be disabled.

  • out_inplace (bool | None) – Decode directly into output array without intermediate copy. Not all FileSequence.imread functions support this, especially in non-contiguous cases.

  • out (OutputType) – Output array, ‘memmap’, or file for image data. By default, create a new array. If a numpy.ndarray, a writable array to which the images are copied. If ‘memmap’, create a memory-mapped array in a temporary file. If a string or open file, the file used to create a memory-mapped array.

  • **kwargs (Any) – Deprecated: Arguments passed to FileSequence.imread in addition to imreadargs.

Raises:

IndexError, ValueError – Array shapes do not match.

Return type:

NDArray[Any]

aszarr(**kwargs)

Return images from files as Zarr store.

Parameters:

**kwargs (Any) – Arguments passed to ZarrFileSequenceStore.

Return type:

ZarrFileSequenceStore

close()

Close open files.

Return type:

None

commonpath()

Return longest common sub-path of each file in sequence.

Return type:

str

property files_missing: int

Number of missing files in sequence.

__iter__()

Return iterator over all file names.

Return type:

Iterator[str]

__repr__()

Return repr(self).

Return type:

str

__str__()

Return str(self).

Return type:

str

__weakref__

list of weak references to the object

final class tifffile.NullContext

Bases: object

Null context manager and dummy reentrant lock.

Can replace threading.RLock where no synchronization is needed. Implements both the context manager and lock interfaces.

>>> with NullContext():
...     pass
...
acquire(blocking=True, timeout=-1)

Acquire lock immediately and return True.

Parameters:
  • blocking (bool)

  • timeout (float)

Return type:

bool

release()

Release lock (no-op).

Return type:

None

locked()

Return False; lock is never held.

Return type:

bool

__repr__()

Return repr(self).

Return type:

str

final class tifffile.OmeXml(**metadata)

Bases: object

Create OME-TIFF XML metadata.

https://www.openmicroscopy.org/Schemas/OME/

Parameters:

**metadata (Any) –

Additional OME-XML attributes or elements to be stored.

Creator:

Name of creating application. The default is ‘tifffile.py and version’.

UUID:

Unique identifier.

Experimenter:

Dict of Experimenter attributes (FirstName, LastName, Email, Institution, UserName, etc.). A list of dicts creates multiple Experimenter elements.

Project:

Dict of Project attributes (Name, Description). A list of dicts creates multiple Project elements.

Examples

>>> omexml = OmeXml()
>>> omexml.addimage(
...     dtype='uint16',
...     shape=(32, 256, 256),
...     storedshape=(32, 1, 1, 256, 256, 1),
...     axes='CYX',
...     Name='First Image',
...     PhysicalSizeX=2.0,
...     MapAnnotation={'key': 'value'},
...     Dataset={'Name': 'FirstDataset'},
... )
>>> xml = omexml.tostring()
>>> xml
'<OME ...<Image ID="Image:0" Name="First Image">...</Image>...</OME>'
>>> OmeXml.validate(xml)
True
__init__(**metadata)
Parameters:

metadata (Any)

Return type:

None

images: list[str]

OME-XML Image elements.

annotations: list[str]

OME-XML Annotation elements.

datasets: list[str]

OME-XML Dataset elements.

experimenters: list[str]

OME-XML Experimenter elements.

projects: list[str]

OME-XML Project elements.

addimage(dtype, shape, storedshape, *, axes=None, **metadata)

Add image to OME-XML.

The OME model can handle up to 9 dimensional images for selected axes orders. Refer to the OME-XML specification for details. Non-TZCYXS (modulo) dimensions must be after a TZC dimension or require an unused TZC dimension.

Parameters:
  • dtype (DTypeLike | None) – Data type of image array.

  • shape (Sequence[int]) – Shape of image array.

  • storedshape (tuple[int, int, int, int, int, int] | StoredShape) – Normalized shape describing how image array is stored in TIFF file as (pages, separate_samples, depth, length, width, contig_samples).

  • axes (str | None) – Character codes for dimensions in shape. By default, axes is determined from the DimensionOrder metadata attribute or matched to the shape in reverse order of TZC(S)YX(S) based on storedshape. The following codes are supported: ‘S’ sample, ‘X’ width, ‘Y’ length, ‘Z’ depth, ‘C’ channel, ‘T’ time, ‘A’ angle, ‘P’ phase, ‘R’ tile, ‘H’ lifetime, ‘E’ lambda, ‘Q’ other.

  • **metadata (Any) –

    Additional OME-XML attributes or elements to be stored.

    Image/Pixels:

    Name, Description, DimensionOrder, TypeDescription, PhysicalSizeX, PhysicalSizeXUnit, PhysicalSizeY, PhysicalSizeYUnit, PhysicalSizeZ, PhysicalSizeZUnit, TimeIncrement, TimeIncrementUnit, StructuredAnnotations, BooleanAnnotation, DoubleAnnotation, LongAnnotation, CommentAnnotation, MapAnnotation, Dataset, Experimenter

    Per Plane:

    DeltaT, DeltaTUnit, ExposureTime, ExposureTimeUnit, PositionX, PositionXUnit, PositionY, PositionYUnit, PositionZ, PositionZUnit.

    Per Channel:

    Name, AcquisitionMode, Color, ContrastMethod, EmissionWavelength, EmissionWavelengthUnit, ExcitationWavelength, ExcitationWavelengthUnit, Fluor, IlluminationType, NDFilter, PinholeSize, PinholeSizeUnit, PockelCellSetting.

Raises:

OmeXmlError – Image format not supported.

Return type:

None

tostring(*, declaration=False)

Return OME-XML string.

Parameters:

declaration (bool) – Include XML declaration.

Return type:

str

__repr__()

Return repr(self).

Return type:

str

__str__()

Return OME-XML string.

Return type:

str

static validate(omexml, /, omexsd=None, *, assert_=True)

Return if OME-XML is valid according to XMLSchema.

Parameters:
  • omexml (str) – OME-XML string to validate.

  • omexsd (bytes | None) – Content of OME-XSD schema to validate against. By default, the 2016-06 OME XMLSchema is downloaded on first run.

  • assert_ (bool) – Raise AssertionError if validation fails.

Returns:

True if validation passed. False if validation failed and assert\_ is False. None if the XMLSchema could not be loaded.

Raises:

AssertionError – Validation failed and assert\_ is True.

Return type:

bool | None

class tifffile.OmeXmlError

Bases: Exception

Exception to indicate invalid OME-XML or unsupported cases.

__weakref__

list of weak references to the object

final class tifffile.StoredShape(frames=1, separate_samples=1, depth=1, length=1, width=1, contig_samples=1, extrasamples=0)

Bases: Sequence[int]

Normalized shape of image array in TIFF pages.

Parameters:
  • frames (int) – Number of TIFF pages.

  • separate_samples (int) – Number of separate samples.

  • depth (int) – Image depth.

  • length (int) – Image length (height).

  • width (int) – Image width.

  • contig_samples (int) – Number of contiguous samples.

  • extrasamples (int) – Number of extra samples.

__init__(frames=1, separate_samples=1, depth=1, length=1, width=1, contig_samples=1, extrasamples=0)
Parameters:
  • frames (int)

  • separate_samples (int)

  • depth (int)

  • length (int)

  • width (int)

  • contig_samples (int)

  • extrasamples (int)

Return type:

None

frames: int

Number of TIFF pages.

separate_samples: int

Number of separate samples.

depth: int

Image depth. Value of ImageDepth tag or 1.

length: int

Image length (height). Value of ImageLength tag.

width: int

Image width. Value of ImageWidth tag.

contig_samples: int

Number of contiguous samples.

extrasamples: int

Number of extra samples. Count of ExtraSamples tag or 0.

property size: int

Product of all dimensions.

property samples: int

Number of samples. Count of SamplesPerPixel tag.

property photometric_samples: int

Number of photometric samples.

property shape: tuple[int, int, int, int, int, int]

Normalized 6D shape of image array in all pages.

property page_shape: tuple[int, int, int, int, int]

Normalized 5D shape of image array in single page.

property page_size: int

Product of dimensions in single page.

property squeezed: tuple[int, ...]

Shape with length-1 dimensions removed, except length and width.

property is_valid: bool

Shape is valid.

property is_planar: bool

Shape contains planar samples.

property planarconfig: int | None

Value of PlanarConfiguration tag.

__hash__()

Return hash(self).

Return type:

int

__eq__(other, /)

Return self==value.

Parameters:

other (object)

Return type:

bool

__repr__()

Return repr(self).

Return type:

str

final class tifffile.TiffFile(file, /, *, mode=None, name=None, offset=None, size=None, omexml=None, superres=None, _multifile=None, _useframes=None, _root=None, **is_flags)

Bases: object

Read image and metadata from TIFF file.

TiffFile instances must be closed with TiffFile.close(), which is automatically called when using the ‘with’ context manager.

TiffFile instances are not thread-safe. All attributes are read-only.

Parameters:
  • file (str | os.PathLike[Any] | FileHandle | IO[bytes]) – Specifies TIFF file to read. File objects must be open in binary mode and positioned at the TIFF header.

  • mode (Literal['r', 'r+'] | None) – File open mode if file is file name. The default is ‘rb’.

  • name (str | None) – Name of file if file is file handle.

  • offset (int | None) – Start position of embedded file. The default is the current file position.

  • size (int | None) – Size of embedded file. The default is the number of bytes from the offset to the end of the file.

  • omexml (str | None) – OME metadata in XML format, for example, from external companion file or sanitized XML overriding XML in file.

  • superres (int | None) – EER super-resolution level to decode. The default is 0 (no super-resolution).

  • _multifile (bool) – Internal use.

  • _useframes (bool | None) – Internal use.

  • _root (TiffFile) – Internal use.

  • **is_flags (bool | None) –

    Override TiffFile.is_ flags, for example:

    is_ome=False: disable processing of OME-XML metadata. is_lsm=False: disable special handling of LSM files. is_ndpi=True: force file to be NDPI format.

Raises:

TiffFileError – Invalid TIFF structure.

__init__(file, /, *, mode=None, name=None, offset=None, size=None, omexml=None, superres=None, _multifile=None, _useframes=None, _root=None, **is_flags)
Parameters:
  • file (str | os.PathLike[Any] | FileHandle | IO[bytes])

  • mode (Literal['r', 'r+'] | None)

  • name (str | None)

  • offset (int | None)

  • size (int | None)

  • omexml (str | None)

  • superres (int | None)

  • _multifile (bool | None)

  • _useframes (bool | None)

  • _root (TiffFile | None)

  • is_flags (bool | None)

Return type:

None

tiff: TiffFormat

Properties of TIFF file format.

pages: TiffPages

Sequence of pages in TIFF file.

property byteorder: Literal['>', '<']

Byteorder of TIFF file.

property filehandle: FileHandle

File handle of TIFF file.

property filename: str

Name of TIFF file.

property root: TiffFile

Root TiffFile for OME multi-file series, else self.

In an OME-TIFF dataset that spans multiple files, all secondary files hold a reference to the first-opened (root) file. For single-file TIFFs this property returns the instance itself.

property fstat: Any

OS status of file handle descriptor, or None if unavailable.

close()

Close open file handle(s).

Return type:

None

asarray(key=None, *, series=None, kind=None, level=None, squeeze=None, out=None, maxworkers=None, buffersize=None)

Return images from select pages as NumPy array.

By default, the image array from the first level of the first series is returned.

Parameters:
  • key (int | slice | Sequence[int] | None) – Specifies which pages to return as array. By default, the image of the specified series and level is returned. If not None, the images from the specified pages in the whole file (if series is None) or a specified series are returned as a stacked array. Requesting an array from multiple pages that are not compatible with respect to shape, dtype, compression etc. is undefined, that is, it may crash or return incorrect values.

  • series (int | TiffPageSeries | None) – Specifies which series of pages to return as array. The default is 0.

  • kind (str | None) – Series format kind, such as 'ome' or 'imagej'. By default, the format is auto-detected.

  • level (int | None) – Specifies which level of multi-resolution series to return as array. The default is 0.

  • squeeze (bool | None) – Remove length-1 dimensions from image array, except X and Y. If False, preserve all dimensions. Single pages are returned as 5D array of shape TiffPage.shaped. For series, the shape of the returned array also includes singlet dimensions specified in some file formats. For example, ImageJ series and most commonly also OME series, are returned in TZCYXS order. If None (default), remove length-1 dimensions except for 'shaped' series.

  • out (OutputType) – Output array, ‘memmap’, or file for image data. By default, a new NumPy array is created. If a numpy.ndarray, a writable array to which the image is copied. If ‘memmap’, directly memory-map the image data in the file if possible; else create a memory-mapped array in a temporary file. If a string or open file, the file used to create a memory-mapped array.

  • maxworkers (int | None) – Maximum number of threads to concurrently decode data from multiple pages or compressed segments. If None or 0, use up to _TIFF.MAXWORKERS threads. Reading data from file is limited to the main thread. Using multiple threads can significantly speed up this function if the bottleneck is decoding compressed data, for example, in case of large LZW compressed LSM files or JPEG compressed tiled slides. If the bottleneck is I/O or pure Python code, using multiple threads might be detrimental.

  • buffersize (int | None) – Approximate number of bytes to read from file in one pass. The default is _TIFF.BUFFERSIZE.

Returns:

Images from specified pages. See TiffPage.asarray for operations that are applied (or not) to the image data stored in the file.

Return type:

NDArray[Any]

asxarray(key=None, *, series=None, kind=None, level=None, squeeze=None, maxworkers=None, buffersize=None)

Return images from select pages as xarray DataArray.

By default, the image array from the first level of the first series is returned.

Parameters:
  • key (int | slice | Sequence[int] | None) – Specifies which page to return as DataArray. By default, the image of the specified series and level is returned. If not None and an integer, the image from the specified page is returned. Requesting a DataArray from multiple pages (slice or sequence) is not supported.

  • series (int | TiffPageSeries | None) – Specifies which series of pages to return as DataArray. The default is 0.

  • kind (str | None) – Series format kind, such as 'ome' or 'imagej'. By default, the format is auto-detected.

  • level (int | None) – Specifies which level of multi-resolution series to return as DataArray. The default is 0.

  • squeeze (bool | None) – Remove length-1 dimensions from image array, except X and Y. If False, preserve all dimensions. If None (default), remove length-1 dimensions except for 'shaped' series.

  • maxworkers (int | None) – Maximum number of threads to concurrently decode data. See TiffFile.asarray() for details.

  • buffersize (int | None) – Approximate number of bytes to read from file in one pass. The default is _TIFF.BUFFERSIZE.

Returns:

xarray.DataArray

Image data with coordinates, dimensions, and attributes.

Return type:

DataArray

aszarr(key=None, *, series=None, kind=None, level=None, squeeze=None, **kwargs)

Return images from select pages as Zarr store.

By default, the images from the first series, including all levels, are wrapped as a Zarr store.

Parameters:
  • key (int | None) – Index of page in file or series to wrap as Zarr store. By default, a series is wrapped.

  • series (int | TiffPageSeries | None) – Index of series to wrap as Zarr store. The default is 0 (if key is None).

  • kind (str | None) – Series format kind, such as 'ome' or 'imagej'. By default, the format is auto-detected.

  • level (int | None) – Index of pyramid level in series to wrap as Zarr store. By default, all levels are included as a multi-scale group.

  • squeeze (bool | None) – Remove length-1 dimensions from image array, except X and Y. If False, preserve all dimensions. If None (default), remove length-1 dimensions except for 'shaped' series.

  • **kwargs (Any) – Additional arguments passed to TiffPage.aszarr() or TiffPageSeries.aszarr().

Return type:

ZarrTiffStore

property series: TiffSeries

Series of pages with compatible shape and data type.

Call with parameters to get differently configured series:

tif.series                    # default series, squeezed
tif.series(squeeze=False)     # unsqueezed
tif.series(kind='generic')    # specific kind

Notes

After accessing this property, TiffFile.pages might contain TiffPage and TiffFrame instead of only TiffPage instances.

__getattr__(name, /)

Return is_flag attributes from first page.

Parameters:

name (str)

Return type:

Any

__repr__()

Return repr(self).

Return type:

str

__str__()

Return str(self).

Return type:

str

property flags: set[str]

Set of file flags.

May be expensive to compute.

property is_uniform: bool

File contains uniform series of pages.

property is_appendable: bool

Pages can be appended to file without corrupting.

property is_bigtiff: bool

File has BigTIFF format.

property is_ndtiff: bool

File has NDTiff format.

property is_mmstack: bool

File has Micro-Manager stack format.

property is_mdgel: bool

File has MD Gel format.

property is_sis: bool

File is Olympus SIS format.

property is_svs: bool

File is Aperio SVS format.

property is_c2pa: bool

File contains embedded C2PA manifest in last page.

A potential expensive check.

property shaped_metadata: tuple[dict[str, Any], ...] | None

Tifffile metadata from JSON formatted ImageDescription tags.

property ome_metadata: str | None

OME XML metadata from ImageDescription tag.

property scn_metadata: str | None

Leica SCN XML metadata from ImageDescription tag.

property philips_metadata: str | None

Philips DP XML metadata from ImageDescription tag.

property indica_metadata: str | None

IndicaLabs XML metadata from ImageDescription tag.

property qpi_metadata: str | None

PerkinElmer QPI XML metadata from ImageDescription tag.

property bif_metadata: str | None

Ventana BIF XML metadata from XMP tag.

property avs_metadata: str | None

Argos AVS XML metadata from tag 65000.

property lsm_metadata: dict[str, Any] | None

LSM metadata from CZ_LSMINFO tag.

property stk_metadata: dict[str, Any] | None

STK metadata from UIC tags.

property imagej_metadata: dict[str, Any] | None

ImageJ metadata from ImageDescription and IJMetadata tags.

property fluoview_metadata: dict[str, Any] | None

FluoView metadata from MM_Header and MM_Stamp tags.

property nih_metadata: dict[str, Any] | None

NIHImage metadata from NIHImageHeader tag.

property fei_metadata: dict[str, Any] | None

FEI metadata from SFEG or HELIOS tags.

property sem_metadata: dict[str, Any] | None

SEM metadata from CZ_SEM tag.

property sis_metadata: dict[str, Any] | None

Olympus SIS metadata from OlympusSIS and OlympusINI tags.

property mdgel_metadata: dict[str, Any] | None

MD-GEL metadata from MDFileTag tags.

property eer_metadata: dict[str, Any] | None

EER metadata from tags 65001-65009.

property nuvu_metadata: dict[str, Any] | None

Nuvu metadata from tags >= 65000.

property andor_metadata: dict[str, Any] | None

Andor metadata from Andor tags.

property epics_metadata: dict[str, Any] | None

EPICS metadata from areaDetector tags.

property tvips_metadata: dict[str, Any] | None

TVIPS metadata from tag.

property metaseries_metadata: dict[str, Any] | None

MetaSeries metadata from ImageDescription tag of first page.

property pilatus_metadata: dict[str, Any] | None

Pilatus metadata from ImageDescription tag.

property micromanager_metadata: dict[str, Any] | None

Non-TIFF Micro-Manager metadata.

property scanimage_metadata: dict[str, Any] | None

ScanImage non-varying frame and ROI metadata.

The returned dict may contain ‘FrameData’, ‘RoiGroups’, and ‘version’ keys.

Varying frame data can be found in the ImageDescription tags.

property geotiff_metadata: dict[str, Any] | None

GeoTIFF metadata from tags.

property gdal_metadata: dict[str, Any] | None

GDAL XML metadata from GDAL_METADATA tag.

property gdal_structural_metadata: dict[str, Any] | None

Non-TIFF GDAL structural metadata.

property astrotiff_metadata: dict[str, Any] | None

AstroTIFF metadata from ImageDescription tag.

property streak_metadata: dict[str, Any] | None

Hamamatsu streak metadata from ImageDescription tag.

property c2pa_metadata: bytes | None

C2PA manifest from C2PAManifestStore tag of last page.

__weakref__

list of weak references to the object

class tifffile.TiffFileError

Bases: ValueError

Exception to indicate invalid TIFF structure.

__weakref__

list of weak references to the object

final class tifffile.TiffFormat(version, byteorder, offsetsize, offsetformat, tagnosize, tagnoformat, tagsize, tagformat1, tagformat2, tagoffsetthreshold)

Bases: object

TIFF format properties.

Parameters:
  • version (int)

  • byteorder (Literal['>', '<'])

  • offsetsize (int)

  • offsetformat (str)

  • tagnosize (int)

  • tagnoformat (str)

  • tagsize (int)

  • tagformat1 (str)

  • tagformat2 (str)

  • tagoffsetthreshold (int)

__init__(version, byteorder, offsetsize, offsetformat, tagnosize, tagnoformat, tagsize, tagformat1, tagformat2, tagoffsetthreshold)
Parameters:
  • version (int)

  • byteorder (Literal['>', '<'])

  • offsetsize (int)

  • offsetformat (str)

  • tagnosize (int)

  • tagnoformat (str)

  • tagsize (int)

  • tagformat1 (str)

  • tagformat2 (str)

  • tagoffsetthreshold (int)

Return type:

None

version: int

Version of TIFF header.

byteorder: Literal['>', '<']

Byteorder of TIFF header.

offsetsize: int

Byte size of offset fields.

offsetformat: str

Struct format for offset values.

tagnosize: int

Byte size of the tag count field.

tagnoformat: str

Struct format for number of TIFF tags.

tagsize: int

Byte size of one IFD entry.

tagformat1: str

Struct format for code and dtype of TIFF tag.

tagformat2: str

Struct format for count and value of TIFF tag.

tagheaderformat: str

Struct format for code, dtype, count, and value of TIFF tag.

tagoffsetthreshold: int

Maximum byte count of tag value stored inline in IFD entry.

property is_bigtiff: bool

Format is 64-bit BigTIFF.

property is_ndpi: bool

Format is 32-bit TIFF with 64-bit offsets used by NDPI.

__eq__(other)

Return self==value.

Parameters:

other (object)

Return type:

bool

__hash__()

Return hash(self).

Return type:

int

__repr__()

Return repr(self).

Return type:

str

__str__()

Return str(self).

Return type:

str

final class tifffile.TiffFrame(parent, /, index, *, offset=None, keyframe=None, dataoffsets=None, databytecounts=None)

Bases: object

Lightweight TIFF image file directory (IFD).

The purpose of TiffFrame is to reduce resource usage and speed up reading image data from file compared to TiffPage. Properties other than offset, index, dataoffsets, databytecounts, subifds, and jpegtables are assumed to be identical with a specified TiffPage instance, the keyframe. TiffFrame instances have no tags property. Virtual frames just reference the image data in the file. They may not have an IFD structure in the file.

TiffFrame instances are not thread-safe. All attributes are read-only.

Parameters:
  • parent (TiffFile) – TiffFile instance to read frame from. The file handle position must be at an offset to an IFD structure. Only a limited number of tag values are read from file.

  • index (int | Sequence[int]) – Index of frame in IFD tree.

  • offset (int) – Position of frame in file, or zero for virtual frame.

  • keyframe (TiffPage | None) – TiffPage instance with same hash as frame.

  • dataoffsets (tuple[int, ...]) – Data offsets of “virtual frame”.

  • databytecounts (tuple[int, ...]) – Data bytecounts of “virtual frame”.

parent: TiffFile

TiffFile instance frame belongs to.

offset: int

Position of frame in file.

dataoffsets: tuple[int, ...]

Positions of strips or tiles in file.

databytecounts: tuple[int, ...]

Byte counts of strips or tiles in file.

subifds: tuple[int, ...] | None

Positions of SubIFDs in file.

jpegtables: bytes | None

JPEG quantization and Huffman tables.

__init__(parent, /, index, *, offset=None, keyframe=None, dataoffsets=None, databytecounts=None)
Parameters:
  • parent (TiffFile)

  • index (int | Sequence[int])

  • offset (int | None)

  • keyframe (TiffPage | None)

  • dataoffsets (tuple[int, ...] | None)

  • databytecounts (tuple[int, ...] | None)

Return type:

None

aspage()

Return TiffPage from file.

Raise ValueError if frame is virtual.

Return type:

TiffPage

asarray(**kwargs)

Return image from frame as NumPy array.

Parameters:

**kwargs (Any) – Arguments passed to TiffPage.asarray().

Return type:

NDArray[Any]

asxarray(**kwargs)

Return image data from frame as xarray DataArray.

Parameters:

**kwargs (Any) – Arguments passed to TiffPage.asarray().

Return type:

DataArray

aszarr(**kwargs)

Return image from frame as Zarr store.

Parameters:

**kwargs (Any) – Arguments passed to ZarrTiffStore.

Return type:

ZarrTiffStore

property index: int

Index of frame in IFD chain.

property treeindex: tuple[int, ...]

Index of frame in IFD tree.

property keyframe: TiffPage | None

TiffPage with same hash as this frame.

property is_frame: bool

Object is TiffFrame instance.

property is_virtual: bool

Frame does not have IFD structure in file.

property is_subifd: bool

Frame is SubIFD of another page.

property is_final: bool

Image data is stored in final form. Excludes byte-swapping.

property is_contiguous: bool

Image data is stored contiguously.

See TiffPage.is_contiguous.

property is_memmappable: bool

Image data in file can be memory-mapped to NumPy array.

property hash: int

Checksum to identify pages in same series.

See TiffPage.hash.

property shape: tuple[int, ...]

Shape of image array in page.

property shaped: tuple[int, int, int, int, int]

Normalized 5-dimensional shape of image array in page.

See TiffPage.shaped.

property chunks: tuple[int, ...]

Shape of single tile or strip.

property chunked: tuple[int, ...]

Number of tiles or strips per dimension in image.

property tile: tuple[int, ...] | None

Tile length and width, or depth, length, and width if volumetric.

property name: str

Name of image array.

property ndim: int

Number of dimensions in image array.

property dims: tuple[str, ...]

Names of dimensions in image array.

property sizes: dict[str, int]

Ordered map of dimension names to lengths.

property coords: dict[str, NDArray[Any]]

Ordered map of dimension names to coordinate arrays.

property size: int

Number of elements in image array.

property nbytes: int

Number of bytes in image array.

property dtype: numpy.dtype[Any] | None

Data type of image array in page.

property axes: str

Character codes for dimensions in image array.

See TiffPage.axes.

get_resolution(unit=None, scale=None)

Return number of pixels per unit in X and Y dimensions.

See TiffPage.get_resolution.

Parameters:
  • unit (RESUNIT | int | str | None)

  • scale (float | None)

Return type:

tuple[float, float]

property resolution: tuple[float, float]

Number of pixels per resolutionunit in X and Y directions.

property resolutionunit: int

Unit of measurement for X and Y resolutions.

property datetime: datetime | None

Date and time of image creation.

property compression: int

COMPRESSION scheme used on image data.

property decode: Callable[[...], DecodeResult]

Return decoded segment, its shape, and indices in image.

See TiffPage.decode.

__repr__()

Return repr(self).

Return type:

str

__str__()

Return str(self).

Return type:

str

final class tifffile.TiffPage(parent, /, index, *, keyframe=None)

Bases: object

TIFF image file directory (IFD).

TiffPage instances are not thread-safe. All attributes are read-only.

Parameters:
  • parent (TiffFile) – TiffFile instance to read page from. The file handle position must be at an offset to an IFD structure.

  • index (int | Sequence[int]) – Index of page in IFD tree.

  • keyframe (TiffPage | None) – Not used. For API compatibility with TiffFrame.

Raises:

TiffFileError – Invalid TIFF structure.

tags: TiffTags

Tags belonging to page.

parent: TiffFile

TiffFile instance page belongs to.

offset: int

Position of page in file.

shape: tuple[int, ...]

Shape of image array in page.

dtype: numpy.dtype[Any] | None

Data type of image array in page.

shaped: tuple[int, int, int, int, int]

Normalized 5-dimensional shape of image array in page:

  1. separate samplesperpixel or 1.

  2. imagedepth or 1.

  3. imagelength.

  4. imagewidth.

  5. contig samplesperpixel or 1.

axes: str

Character codes for dimensions in image array: ‘S’ sample, ‘X’ width, ‘Y’ length, ‘Z’ depth.

dataoffsets: tuple[int, ...]

Positions of strips or tiles in file.

databytecounts: tuple[int, ...]

Byte counts of strips or tiles in file.

subfiletype: int = 0

FILETYPE kind of image.

imagewidth: int = 0

Number of columns (pixels per row) in image.

imagelength: int = 0

Number of rows in image.

imagedepth: int = 1

Number of Z slices in image.

tilewidth: int = 0

Number of columns in each tile.

tilelength: int = 0

Number of rows in each tile.

tiledepth: int = 1

Number of Z slices in each tile.

samplesperpixel: int = 1

Number of components per pixel.

bitspersample: int = 1

Number of bits per pixel component.

sampleformat: int = 1

SAMPLEFORMAT type of pixel components.

rowsperstrip: int = 4294967295

Number of rows per strip.

compression: int = 1

COMPRESSION scheme used on image data.

planarconfig: int = 1

PLANARCONFIG type of storage of components in pixel.

fillorder: int = 1

Logical order of bits within byte of image data.

photometric: int = 0

PHOTOMETRIC color space of image.

predictor: int = 1

PREDICTOR applied to image data before compression.

extrasamples: tuple[int, ...] = ()

EXTRASAMPLE interpretation of extra components in pixel.

subsampling: tuple[int, int] | None = None

Subsampling factors used for chrominance components.

subifds: tuple[int, ...] | None = None

Positions of SubIFDs in file.

jpegtables: bytes | None = None

JPEG quantization and Huffman tables.

jpegheader: bytes | None = None

JPEG header extracted from NDPI JPEG stream.

software: str = ''

Software used to create image.

description: str = ''

Value of ImageDescription tag.

description1: str = ''

Value of second ImageDescription tag.

nodata: float = 0

Missing data sentinel value from GDAL_NODATA tag, or 0 if absent.

__init__(parent, /, index, *, keyframe=None)
Parameters:
Return type:

None

init_decode()

Initialize decode function from the main thread.

decode() is a functools.cached_property() and is not thread-safe on first access. Call this method from the main thread before decoding segments concurrently to avoid a race condition where multiple threads compute the decoder simultaneously.

Return type:

None

property decode: Callable[[...], DecodeResult]

Return decoded segment, its shape, and indices in image.

The decode function is implemented as a closure and has the following signature:

Parameters:
  • data (Union[bytes, None]) – Encoded bytes of segment or None for empty segments.

  • index (int) – Index of segment in Offsets and Bytecount tag values.

  • jpegtables (Optional[bytes]) – For JPEG compressed segments only, value of JPEGTables tag if any.

Returns:

  • Decoded segment or None for empty segments.

  • Position of segment in image array of normalized shape (separate sample, depth, length, width, contig sample).

  • Shape of segment (depth, length, width, contig samples). The shape of strips depends on their linear index.

Raises:
  • ValueError or NotImplementedError – Decoding is not supported.

  • TiffFileError – Invalid TIFF structure.

segments(*, lock: threading.RLock | NullContext | None = None, maxworkers: int | None = None, func: None = None, sort: bool = False, buffersize: int | None = None, _fullsize: bool | None = None) Iterator[DecodeResult]
segments(*, lock: threading.RLock | NullContext | None = None, maxworkers: int | None = None, func: Callable[[DecodeResult], Any], sort: bool = False, buffersize: int | None = None, _fullsize: bool | None = None) Iterator[Any]

Return iterator over decoded tiles or strips.

Parameters:
  • lock (threading.RLock | NullContext | None) – Reentrant lock to synchronize file seeks and reads.

  • maxworkers (int | None) – Maximum number of threads to concurrently decode segments. The default is TiffPage.maxworkers.

  • func (Callable[[DecodeResult], Any] | None) – Function to process decoded segment. The default yields each decoded result unmodified.

  • sort (bool) – Read order by file offset rather than segment index.

  • buffersize (int | None) – Approximate number of bytes to read from file in one pass. The default is _TIFF.BUFFERSIZE.

  • _fullsize (bool | None) – Internal use.

Yields:
  • Decoded segment or None for empty segments.

  • Position of segment in image array of normalized shape (separate sample, depth, length, width, contig sample).

  • Shape of segment (depth, length, width, contig samples). The shape of strips depends on their linear index.

Return type:

Iterator[DecodeResult] | Iterator[Any]

asarray(*, out=None, squeeze=True, lock=None, maxworkers=None, buffersize=None)

Return image from page as NumPy array.

Parameters:
  • out (OutputType) – Output array, ‘memmap’, or file for image data. By default, a new NumPy array is created. If a numpy.ndarray, a writable array to which the image is copied. If ‘memmap’, directly memory-map the image data in the file if possible; else create a memory-mapped array in a temporary file. If a string or open file, the file used to create a memory-mapped array.

  • squeeze (bool) – Remove length-1 dimensions from image array, except X and Y. If False, return the image array with normalized 5-dimensional shape TiffPage.shaped.

  • lock (threading.RLock | NullContext | None) – Reentrant lock to synchronize seeks and reads from file. The default is the lock of the parent’s file handle.

  • maxworkers (int | None) – Maximum number of threads to concurrently decode segments. If None or 0, use up to _TIFF.MAXWORKERS threads. See remarks in TiffFile.asarray().

  • buffersize (int | None) – Approximate number of bytes to read from file in one pass. The default is _TIFF.BUFFERSIZE.

Returns:

NumPy array of decompressed, unpredicted, and unpacked image data read from Strip/Tile Offsets/ByteCounts, formatted according to shape and dtype metadata found in tags and keyword arguments. Photometric conversion, premultiplied alpha, orientation, and colorimetry corrections are not applied. Specifically, CMYK images are not converted to RGB, MinIsWhite images are not inverted, color palettes are not applied, gamma is not corrected, and CFA images are not demosaiced. Exceptions are YCbCr JPEG compressed images, which are converted to RGB. Return an empty, two-dimensional array if the page contains no image or is missing required tags.

Raises:
  • TiffFileError – Missing data offset or invalid TIFF structure.

  • ValueError – Format of image in file is not supported and cannot be decoded.

Return type:

NDArray[Any]

asxarray(**kwargs)

Return image data from page as xarray DataArray.

Parameters:

**kwargs (Any) – Passed to asarray().

Returns:

xarray.DataArray

Image data with coordinates, dimensions, and attributes.

Return type:

DataArray

aszarr(**kwargs)

Return image from page as Zarr store.

Parameters:

**kwargs (Any) – Passed to ZarrTiffStore.

Return type:

ZarrTiffStore

aspage()

Return TiffPage instance.

Return type:

TiffPage

property index: int

Index of page in IFD chain.

property treeindex: tuple[int, ...]

Index of page in IFD tree.

property keyframe: TiffPage

Self; TiffPage is its own keyframe.

property name: str

Name of image array.

property ndim: int

Number of dimensions in image array.

property dims: tuple[str, ...]

Character codes of dimensions in image array.

property sizes: dict[str, int]

Ordered map of dimension character codes to lengths.

property coords: dict[str, NDArray[Any]]

Ordered map of dimension character codes to coordinate arrays.

Only axes with physical coordinate information are included. Axes without resolution tags or sample names are omitted.

property attrs: dict[str, Any]

Metadata dictionary for image array.

property size: int

Number of elements in image array.

property nbytes: int

Number of bytes in image array.

property colormap: NDArray[numpy.uint16] | None

Value of Colormap tag.

property iccprofile: bytes | None

Value of InterColorProfile tag.

property transferfunction: NDArray[numpy.uint16] | None

Value of TransferFunction tag.

get_resolution(unit=None, scale=None)

Return number of pixels per unit in X and Y dimensions.

By default, the raw XResolution and YResolution rational tag values are returned without any unit conversion. Missing tag values are set to 1.

Parameters:
  • unit (RESUNIT | int | str | None) – Unit of measurement of returned values. If specified, values are converted using the ResolutionUnit tag (default INCH) as the stored unit. Accepts a RESUNIT member, its integer value, or a case-insensitive name string such as 'inch'.

  • scale (float | None) – Multiplier applied to raw rational tag values. If unit is also given, scale overrides reading the ResolutionUnit tag and is used as the source scale (pixels per meter for the stored unit), which is then divided by the scale for unit. If only scale is given (unit=None), it is applied directly to the raw tag values. The default, when neither unit nor scale is given, is 1 (no conversion).

Returns:

Number of pixels per unit in X and Y dimensions.

Return type:

tuple[float, float]

property resolution: tuple[float, float]

Number of pixels per resolutionunit in X and Y directions.

property resolutionunit: int

Unit of measurement for X and Y resolutions.

property datetime: datetime | None

Date and time of image creation.

property tile: tuple[int, ...] | None

Tile length and width, or depth, length, and width if volumetric.

property chunks: tuple[int, ...]

Shape of single tile or strip.

property chunked: tuple[int, ...]

Number of tiles or strips per dimension in image.

property hash: int

Checksum to identify pages in same series.

Pages with the same hash can use the same decode function. The hash is calculated from the following properties: TiffFile.tiff, TiffPage.shaped, TiffPage.rowsperstrip, TiffPage.tilewidth, TiffPage.tilelength, TiffPage.tiledepth, TiffPage.sampleformat, TiffPage.bitspersample, TiffPage.fillorder, TiffPage.predictor, TiffPage.compression, TiffPage.extrasamples, and TiffPage.photometric.

property pages: TiffPages | None

Sequence of sub-pages, SubIFDs.

property maxworkers: int

Maximum number of threads for decoding segments.

A value of 0 disables multi-threading also when stacking pages.

property is_contiguous: bool

Image data is stored contiguously.

Contiguous image data can be read from offset=TiffPage.dataoffsets[0] with size=TiffPage.nbytes. Excludes prediction and fillorder.

property is_final: bool

Image data is stored in final form. Excludes byte-swapping.

property is_memmappable: bool

Image data in file can be memory-mapped to NumPy array.

__repr__()

Return repr(self).

Return type:

str

__str__()

Return str(self).

Return type:

str

property flags: set[str]

Set of is\_\* properties that are True.

property eer_tags: dict[str, Any] | None

Consolidated metadata from EER tags 65001-65009.

property nuvu_tags: dict[str, Any] | None

Consolidated metadata from Nuvu tags.

property andor_tags: dict[str, Any] | None

Consolidated metadata from Andor tags.

property epics_tags: dict[str, Any] | None

Consolidated metadata from EPICS areaDetector tags.

Use the epics_datetime() function to get a datetime object from the epicsTSSec and epicsTSNsec tags.

property ndpi_tags: dict[str, Any] | None

Consolidated metadata from Hamamatsu NDPI tags.

property geotiff_tags: dict[str, Any] | None

Consolidated metadata from GeoTIFF tags.

property shaped_description: str | None

Shaped array description string, or None if absent.

property imagej_description: str | None

ImageJ description string, or None if absent.

property is_jfif: bool

JPEG compressed segments contain JFIF metadata.

property is_frame: bool

Object is TiffFrame instance.

property is_virtual: bool

Page does not have IFD structure in file.

property is_subifd: bool

Page is SubIFD of another page.

property is_reduced: bool

Page is reduced image of another image.

property is_multipage: bool

Page is part of multi-page image.

property is_mask: bool

Page is transparency mask for another image.

property is_mrc: bool

Page is part of Mixed Raster Content.

property is_tiled: bool

Page contains tiled image.

property is_subsampled: bool

Page contains chroma subsampled image.

property is_imagej: bool

Page contains ImageJ description metadata.

property is_shaped: bool

Page contains Tifffile JSON metadata.

property is_mdgel: bool

Page contains MDFileTag.

property is_agilent: bool

Page contains Agilent Technologies tags.

property is_mediacy: bool

Page contains Media Cybernetics Id tag.

property is_stk: bool

Page contains UIC1Tag.

property is_lsm: bool

Page contains CZ_LSMINFO tag.

property is_fluoview: bool

Page contains FluoView MM_STAMP tag.

property is_nih: bool

Page contains NIHImageHeader tag.

property is_volumetric: bool

Page contains SGI ImageDepth tag with value > 1.

property is_vista: bool

Software tag is ‘ISS Vista’.

property is_metaseries: bool

Page contains MDS MetaSeries metadata in ImageDescription tag.

property is_ome: bool

Page contains OME-XML in ImageDescription tag.

property is_scn: bool

Page contains Leica SCN XML in ImageDescription tag.

property is_micromanager: bool

Page contains MicroManagerMetadata tag.

property is_andor: bool

Page contains Andor Technology tags 4864-5030.

property is_nuvu: bool

Page contains Nuvu cameras tags >= 65000.

property is_pilatus: bool

Page contains Pilatus tags.

property is_epics: bool

Page contains EPICS areaDetector tags.

property is_tvips: bool

Page contains TVIPS metadata.

property is_fei: bool

Page contains FEI_SFEG or FEI_HELIOS tags.

property is_sem: bool

Page contains CZ_SEM tag.

property is_svs: bool

Page contains Aperio metadata.

property is_bif: bool

Page contains Ventana metadata.

property is_scanimage: bool

Page contains ScanImage metadata.

property is_indica: bool

Page contains IndicaLabs metadata.

property is_avs: bool

Page contains Argos AVS XML metadata.

property is_qpi: bool

Page contains PerkinElmer tissue images metadata.

property is_geotiff: bool

Page contains GeoTIFF metadata.

property is_gdal: bool

Page contains GDAL metadata.

property is_astrotiff: bool

Page contains AstroTIFF FITS metadata.

property is_streak: bool

Page contains Hamamatsu streak metadata.

property is_dng: bool

Page contains DNG metadata.

property is_tiffep: bool

Page contains TIFF/EP metadata.

property is_sis: bool

Page contains Olympus SIS metadata.

property is_ndpi: bool

Page contains NDPI metadata.

property is_philips: bool

Page contains Philips DP metadata.

property is_eer: bool

Page contains EER acquisition metadata.

property is_c2pa: bool

Page contains embedded C2PA manifest.

__weakref__

list of weak references to the object

final class tifffile.TiffPages(arg, /, *, index=None)

Bases: Sequence[TiffPage | TiffFrame]

Sequence of TIFF image file directories (IFD chain).

TiffPages instances have a state, such as a cache and keyframe, and are not thread-safe. All attributes are read-only.

Parameters:
  • arg (TiffFile | TiffPage | TiffFrame) – If a TiffFile, the file position must be at offset to offset to TiffPage. If a TiffPage or TiffFrame, page offsets are read from the SubIFDs tag. Only the first page is initially read from the file.

  • index (Sequence[int] | int | None) – Position of IFD chain in IFD tree.

__init__(arg, /, *, index=None)
Parameters:
Return type:

None

parent: TiffFile | None = None

TiffFile instance pages belong to.

property first: TiffPage

First page as TiffPage, or raise IndexError if absent.

property is_multipage: bool

IFD chain contains more than one page.

property cache: bool

Pages and frames are being cached.

When set to False, the cache is cleared.

property useframes: bool

Use TiffFrame (True) or TiffPage (False).

property keyframe: TiffPage | None

TiffPage used as keyframe for new TiffFrames.

set_keyframe(index, /)

Set keyframe to TiffPage specified by index.

If not found in the cache, the TiffPage at index is loaded from file and added to the cache.

Parameters:

index (int)

Return type:

None

property next_page_offset: int | None

File position where next IFD offset can be stored.

get(key: int, /, default: None = None, *, validate: int = 0, cache: bool = False, aspage: bool = True) TiffPage | TiffFrame
get(key: int, /, default: TiffPage | TiffFrame, *, validate: int = 0, cache: bool = False, aspage: bool = True) TiffPage | TiffFrame

Return specified page from cache or file.

The specified TiffPage or TiffFrame is read from file if it is not found in the cache.

Parameters:
  • key (int) – Index of requested page in IFD chain.

  • default (TiffPage | TiffFrame | None) – Page or frame to return if key is out of bounds. By default, an IndexError is raised if key is out of bounds.

  • validate (int) – If non-zero, raise RuntimeError if value does not match hash of TiffPage or TiffFrame.

  • cache (bool) – Store returned page in cache for future use.

  • aspage (bool) – Return TiffPage instance.

Return type:

TiffPage | TiffFrame

__bool__()

Return True if file contains any pages.

Return type:

bool

__len__()

Return number of pages in file.

Return type:

int

__repr__()

Return repr(self).

Return type:

str

__weakref__

list of weak references to the object

class tifffile.TiffPageSeries(pages, /, shape=None, dtype=None, axes=None, *, attrs=None, coords=None, units=None, index=None, parent=None, name=None, kind=None, truncated=False, multifile=False, transform=None)

Bases: Sequence[TiffPage | TiffFrame | None]

Sequence of TIFF pages making up multi-dimensional image.

Many TIFF based formats, such as OME-TIFF, use series of TIFF pages to store chunks of larger, multi-dimensional images. The image shape and position of chunks in the multi-dimensional image is defined in format-specific metadata. All pages in a series must have the same TiffPage.hash(), that is, the same shape, data type, and storage properties. Items of a series may be None (missing) or instances of TiffPage or TiffFrame, possibly belonging to different files.

Parameters:
  • pages (Sequence[TiffPage | TiffFrame | None]) – List of TiffPage, TiffFrame, or None. The file handles of TiffPages or TiffFrames may not be open.

  • shape (Sequence[int] | None) – Shape of image array in series.

  • dtype (DTypeLike | None) – Data type of image array in series.

  • axes (str | None) – Character codes for dimensions in shape. Length must match shape.

  • attrs (Mapping[str, Any] | None) – Arbitrary metadata associated with series.

  • coords (Mapping[str, NDArray[Any] | tuple[float, float]] | None) – Ordered map of dimension character codes to coordinate arrays.

  • units (Mapping[str, str] | None) – Map of dimension character codes to unit strings.

  • index (int | None) – Index of series in multi-series files.

  • parent (TiffFile | None) – TiffFile instance series belongs to.

  • name (str | None) – Name of series.

  • kind (str | None) – Nature of series, such as, ‘ome’ or ‘imagej’.

  • truncated (bool) – Series is truncated, for example, ImageJ hyperstack > 4 GB.

  • multifile (bool) – Series contains pages from multiple files.

  • transform (Callable[[NDArray[Any]], NDArray[Any]] | None) – Function to transform image data after decoding.

levels: list[TiffPageSeries]

Multi-resolution, pyramidal levels. levels[0] is self.

parent: TiffFile | None

TiffFile instance series belongs to.

keyframe: TiffPage

Representative TiffPage of series.

dtype: numpy.dtype[Any]

Data type (native byte order) of image array in series.

kind: str

Nature of series.

name: str

Name of image series from metadata.

transform: Callable[[NDArray[Any]], NDArray[Any]] | None

Function to transform image data after decoding.

is_multifile: bool

Series contains pages from multiple files.

is_truncated: bool

Series contains single page describing multi-dimensional image.

__init__(pages, /, shape=None, dtype=None, axes=None, *, attrs=None, coords=None, units=None, index=None, parent=None, name=None, kind=None, truncated=False, multifile=False, transform=None)
Parameters:
  • pages (Sequence[TiffPage | TiffFrame | None])

  • shape (Sequence[int] | None)

  • dtype (DTypeLike | None)

  • axes (str | None)

  • attrs (Mapping[str, Any] | None)

  • coords (Mapping[str, NDArray[Any] | tuple[float, float]] | None)

  • units (Mapping[str, str] | None)

  • index (int | None)

  • parent (TiffFile | None)

  • name (str | None)

  • kind (str | None)

  • truncated (bool)

  • multifile (bool)

  • transform (Callable[[NDArray[Any]], NDArray[Any]] | None)

Return type:

None

property is_pyramidal: bool

Series contains multiple resolutions.

property dataoffset: int | None

Offset to contiguous image data in file.

property axes: str

Character codes for dimensions in image array.

property shape: tuple[int, ...]

Shape of image array in series.

property ndim: int

Number of dimensions in image array.

property dims: tuple[str, ...]

Character codes of dimensions in image array.

property sizes: dict[str, int]

Ordered map of dimension character codes to lengths.

property size: int

Number of elements in image array.

property nbytes: int

Number of bytes in image array.

property mpp: tuple[float, float] | None

Pixel spacing in micrometer as (x, y), or None if unavailable.

property coords: dict[str, NDArray[Any]]

Ordered map of dimension character codes to coordinate arrays.

property coord_scales: dict[str, float]

Coordinate step sizes per axis.

Map dimension character codes to the spacing between consecutive coordinate values. Only axes with numeric, approximately uniformly spaced coordinates are included. The scale is the average step size (last - first) / (n - 1), provided all individual steps are within 5% of that average.

property coord_offsets: dict[str, float]

Coordinate offsets (first pixel position) per axis.

Map dimension character codes to the coordinate value of the first pixel. Only axes with numeric coordinates are included.

property coord_units: dict[str, str]

Coordinate unit strings per axis.

Map dimension character codes to their unit string.

property attrs: dict[str, Any]

Metadata dictionary for series.

asarray(*, level=None, **kwargs)

Return images from series of pages as NumPy array.

Parameters:
  • level (int | None) – Pyramid level to return. By default, the base level is returned.

  • **kwargs (Any) – Additional arguments passed to TiffFile.asarray().

Return type:

NDArray[Any]

asxarray(*, level=None, squeeze=None, **kwargs)

Return image data from series of pages as xarray DataArray.

Parameters:
  • level (int | None) – Pyramid level to return. By default, the base level is returned.

  • squeeze (bool | None) – Remove length-1 dimensions from image array, except X and Y. If False, preserve all dimensions. If None (default), remove length-1 dimensions except for 'shaped' series.

  • **kwargs (Any) – Passed to asarray().

Returns:

xarray.DataArray

Image data with coordinates, dimensions, and attributes.

Return type:

DataArray

aszarr(*, level=None, squeeze=None, **kwargs)

Return images from series of pages as Zarr store.

Parameters:
  • level (int | None) – Pyramid level to return. By default, a multi-resolution store is returned.

  • squeeze (bool | None) – Remove length-1 dimensions from image array, except X and Y. If False, preserve all dimensions. If None (default), remove length-1 dimensions except for 'shaped' series.

  • **kwargs (Any) – Additional arguments passed to ZarrTiffStore.

Return type:

ZarrTiffStore

property pages: TiffPageSeries

Return self for backwards compatibility.

Deprecated since version Access: the series directly instead of via series.pages.

__getitem__(key: int | numpy.integer[Any], /) TiffPage | TiffFrame | None
__getitem__(key: slice | Sequence[int], /) list[TiffPage | TiffFrame | None]

Return specified page(s).

Parameters:

key (int | numpy.integer[Any] | slice | Sequence[int])

Return type:

TiffPage | TiffFrame | list[TiffPage | TiffFrame | None] | None

__iter__()

Return iterator over pages in series.

Return type:

Iterator[TiffPage | TiffFrame | None]

__len__()

Return number of pages in series.

Return type:

int

__repr__()

Return repr(self).

Return type:

str

__str__()

Return str(self).

Return type:

str

__weakref__

list of weak references to the object

tifffile.TiffReader

alias of TiffFile

final class tifffile.TiffSequence(files=None, *, imread=imread, **kwargs)

Bases: FileSequence

Sequence of TIFF files containing compatible array data.

Same as FileSequence with the imread() function, '\*.tif' glob pattern, and out_inplace enabled by default.

Parameters:
  • files (str | os.PathLike[Any] | Sequence[str | os.PathLike[Any]] | None)

  • imread (Callable[..., NDArray[Any]])

  • kwargs (Any)

__init__(files=None, *, imread=imread, **kwargs)
Parameters:
  • files (str | os.PathLike[Any] | Sequence[str | os.PathLike[Any]] | None)

  • imread (Callable[..., NDArray[Any]])

  • kwargs (Any)

Return type:

None

__repr__()

Return repr(self).

Return type:

str

final class tifffile.TiffSeries(parent, /, *, kind=None, squeeze=True)

Bases: Sequence[TiffPageSeries]

Sequence of TiffPageSeries in TIFF file.

Returned by TiffFile.series.

Items can be accessed by index or iterated over. A new TiffSeries with different kind and squeeze settings is returned by calling the instance.

Parameters:
  • parent (TiffFile) – TiffFile instance series belongs to.

  • kind (str | None) – Filter series by kind, such as ‘ome’ or ‘imagej’. If None, the default series are returned.

  • squeeze (bool) – Remove length-1 dimensions from series shapes, except X and Y. If False, series shapes include all dimensions.

Examples

>>> with TiffFile('temp.ome.tif') as tif:
...     series = tif.series
...     series[0].shape
...     series(squeeze=False)[0].shape
...     series(kind='generic')[0].shape
...
(8, 2, 512, 512, 3)
(8, 2, 1, 512, 512, 3)
(16, 512, 512, 3)
__init__(parent, /, *, kind=None, squeeze=True)
Parameters:
  • parent (TiffFile)

  • kind (str | None)

  • squeeze (bool)

Return type:

None

__call__(*, kind=None, squeeze=True)

Return new TiffSeries with specified kind and squeeze settings.

Parameters:
  • kind (str | None) – Filter series by kind, such as ‘ome’ or ‘imagej’. If None, the default series are returned.

  • squeeze (bool) – Remove length-1 dimensions from series shapes, except X and Y. If False, series shapes include all dimensions.

Return type:

TiffSeries

__getitem__(key: int | numpy.integer[Any], /) TiffPageSeries
__getitem__(key: slice | Sequence[int], /) list[TiffPageSeries]

Return specified series.

Parameters:

key (int | numpy.integer[Any] | slice | Sequence[int])

Return type:

TiffPageSeries | list[TiffPageSeries]

__len__()

Return number of series.

Return type:

int

__iter__()

Return iterator over series.

Return type:

Iterator[TiffPageSeries]

__bool__()

Return True if any series exist.

Return type:

bool

__repr__()

Return repr(self).

Return type:

str

__str__()

Return str(self).

Return type:

str

__weakref__

list of weak references to the object

final class tifffile.TiffTag(parent, offset, code, dtype, count, value, valueoffset, /)

Bases: object

TIFF tag structure.

TiffTag instances are not thread-safe. All attributes are read-only.

Parameters:
  • parent (TiffFile | TiffWriter) – TIFF file tag belongs to.

  • offset (int) – Position of tag structure in file.

  • code (int) – Decimal code of tag.

  • dtype (DATATYPE | int) – Data type of tag value item.

  • count (int) – Number of items in tag value.

  • valueoffset (int) – Position of tag value in file.

  • value (Any)

__init__(parent, offset, code, dtype, count, value, valueoffset, /)
Parameters:
Return type:

None

parent: TiffFile | TiffWriter

TIFF file tag belongs to.

offset: int

Position of tag structure in file.

code: int

Decimal code of tag.

count: int

Number of items in tag value.

valueoffset: int

Position of tag value in file.

dtype: int

DATATYPE of tag value item.

classmethod fromfile(parent, /, *, offset=None, header=None, validate=True)

Return TiffTag instance from file.

Parameters:
  • parent (TiffFile) – TiffFile instance tag is read from.

  • offset (int | None) – Position of tag structure in file. The default is the position of the file handle.

  • header (bytes | None) – Tag structure as bytes. The default is read from the file.

  • validate (bool) – Raise TiffFileError if data type or value offset are invalid.

Raises:

TiffFileError – Data type or value offset are invalid and validate is True.

Return type:

TiffTag

property value: Any

Value of tag, delay-loaded from file if necessary.

property dtype_name: str

Name of data type of tag value.

property name: str

Name of tag from _TIFF.TAGS registry.

property dataformat: str

Data type as struct.pack format.

property valuebytecount: int

Number of bytes of tag value in file.

astuple()

Return tag code, dtype, count, and encoded value.

The encoded value is read from file if necessary.

Return type:

TagTuple

overwrite(value, /, *, dtype=None, erase=True)

Write new tag value to file and return new TiffTag instance.

Warning: changing tag values in TIFF files might result in corrupted files or have unexpected side effects.

The packed value is appended to the file if it is longer than the old value. The file position is left where it was.

Overwriting tag values in NDPI files > 4 GB is only supported if single integer values and new offsets do not exceed the 32-bit range.

Parameters:
  • value (Any) – New tag value to write. Must be compatible with the struct.pack formats corresponding to the tag’s data type.

  • dtype (DATATYPE | int | str | None) – New tag data type. By default, the data type is not changed.

  • erase (bool) – Overwrite previous tag value in file with zeros.

Raises:
  • struct.error – Value is not compatible with dtype or new offset exceeds TIFF size limit.

  • ValueError – Invalid value or dtype, or old integer value in NDPI files exceeds 32-bit range.

Return type:

TiffTag

__repr__()

Return repr(self).

Return type:

str

__str__()

Return str(self).

Return type:

str

final class tifffile.TiffTagRegistry(arg, /)

Bases: object

Registry of TIFF tag codes and names.

Map tag codes and names to names and codes respectively. One tag code may be registered with several names, for example, 34853 is used for GPSTag or OlympusSIS2. Different tag codes may be registered with the same name, for example, 37387 and 41483 are both named FlashEnergy.

Parameters:

arg (TiffTagRegistry | dict[int, str] | Sequence[tuple[int, str]]) – Mapping of codes to names.

Examples

>>> tags = TiffTagRegistry([(34853, 'GPSTag'), (34853, 'OlympusSIS2')])
>>> tags.add(37387, 'FlashEnergy')
>>> tags.add(41483, 'FlashEnergy')
>>> tags['GPSTag']
34853
>>> tags[34853]
'GPSTag'
>>> tags.getall(34853)
['GPSTag', 'OlympusSIS2']
>>> tags.getall('FlashEnergy')
[37387, 41483]
>>> len(tags)
4
__init__(arg, /)
Parameters:

arg (TiffTagRegistry | dict[int, str] | Sequence[tuple[int, str]])

Return type:

None

update(arg, /)

Add mapping of codes to names to registry.

Parameters:

arg (TiffTagRegistry | dict[int, str] | Sequence[tuple[int, str]]) – Mapping of codes to names.

Return type:

None

add(code, name, /)

Add code and name to registry.

Parameters:
  • code (int)

  • name (str)

Return type:

None

items()

Return all registry items as (code, name).

Return type:

list[tuple[int, str]]

get(key: int, /, default: None) str | None
get(key: str, /, default: None) int | None
get(key: int, /, default: str) str
get(key: str, /, default: int) int

Return first code or name if exists, else default.

Parameters:
  • key (int | str) – tag code or name to lookup.

  • default (str | int | None) – value to return if key is not found.

Return type:

str | int | None

getall(key: int, /, default: None) list[str] | None
getall(key: str, /, default: None) list[int] | None
getall(key: int, /, default: list[str]) list[str]
getall(key: str, /, default: list[int]) list[int]

Return list of all codes or names if exists, else default.

Parameters:
  • key (int | str) – tag code or name to lookup.

  • default (list[str] | list[int] | None) – value to return if key is not found.

Return type:

list[str] | list[int] | None

__getitem__(key: int, /) str
__getitem__(key: str, /) int

Return first code or name. Raise KeyError if not found.

Parameters:

key (int | str)

Return type:

int | str

__delitem__(key, /)

Delete all tags of code or name.

Parameters:

key (int | str)

Return type:

None

__contains__(item, /)

Return if code or name is in registry.

Parameters:

item (int | str)

Return type:

bool

__iter__()

Return iterator over all items in registry.

Return type:

Iterator[tuple[int, str]]

__len__()

Return number of registered tags.

Return type:

int

__repr__()

Return repr(self).

Return type:

str

__str__()

Return str(self).

Return type:

str

final class tifffile.TiffTags

Bases: object

Multidict-like interface to TiffTag instances in TiffPage.

Differences to a regular dict:

  • values are instances of TiffTag.

  • keys are TiffTag.code (int).

  • multiple values can be stored per key.

  • can be indexed by TiffTag.name` (str), slower than by key.

  • iter() returns values instead of keys.

  • values() and items() contain all values sorted by offset.

  • len() returns number of all values.

  • get() takes optional index argument.

  • some functions are not implemented, such as, update and pop.

__init__()
Return type:

None

add(tag, /)

Add tag.

Parameters:

tag (TiffTag)

Return type:

None

keys()

Return codes of all tags.

Return type:

list[int]

values()

Return all tags in order they are stored in file.

Return type:

list[TiffTag]

items()

Return all (code, tag) pairs in order tags are stored in file.

Return type:

list[tuple[int, TiffTag]]

valueof(key, /, default=None, index=None)

Return value of tag by code or name if exists, else default.

Parameters:
  • key (int | str) – Code or name of tag to return.

  • default (Any) – Another value to return if specified tag is corrupted or not found.

  • index (int | None) – Specifies tag in case of multiple tags with identical code. The default is the first tag.

Return type:

Any

get(key, /, default=None, index=None)

Return tag by code or name if exists, else default.

Parameters:
  • key (int | str) – Code or name of tag to return.

  • default (TiffTag | None) – Another tag to return if specified tag is corrupted or not found.

  • index (int | None) – Specifies tag in case of multiple tags with identical code. The default is the first tag.

Return type:

TiffTag | None

getall(key, /, default=None)

Return list of all tags by code or name if exists, else default.

Parameters:
  • key (int | str) – Code or name of tags to return.

  • default (Any) – Value to return if no tags are found.

Return type:

list[TiffTag] | None

__getitem__(key, /)

Return first tag by code or name. Raise KeyError if not found.

Parameters:

key (int | str)

Return type:

TiffTag

__setitem__(code, tag, /)

Add tag.

Parameters:
Return type:

None

__delitem__(key, /)

Delete all tags by code or name.

Parameters:

key (int | str)

Return type:

None

__contains__(item, /)

Return if tag is in map.

Parameters:

item (object)

Return type:

bool

__iter__()

Return iterator over all tags.

Return type:

Iterator[TiffTag]

__len__()

Return number of tags.

Return type:

int

__repr__()

Return repr(self).

Return type:

str

__str__()

Return str(self).

Return type:

str

final class tifffile.TiffWriter(file, /, *, mode=None, bigtiff=False, byteorder=None, append=False, kind=None, imagej=False, ome=None, shaped=None)

Bases: object

Write arrays and image data to TIFF file.

TiffWriter’s main purpose is to save multi-dimensional NumPy arrays in TIFF containers, not to create any possible TIFF format. Specifically, ExifIFD and GPSIFD tags are not supported.

TiffWriter instances must be closed with TiffWriter.close(), which is automatically called when using the ‘with’ context manager.

TiffWriter instances are not thread-safe. All attributes are read-only.

Parameters:
  • file (str | os.PathLike[Any] | FileHandle | IO[bytes]) – Specifies file to write.

  • mode (Literal['w', 'x', 'r+'] | None) – Binary file open mode if file is a file name. The default is ‘w’, which opens files for writing, truncating existing files. ‘x’ opens files for exclusive creation, failing on existing files. ‘r+’ opens files for updating, enabling append.

  • bigtiff (bool) – Write 64-bit BigTIFF formatted file, which can exceed 4 GB. By default, a classic 32-bit TIFF file is written, which is limited to 4 GB. If append is True, the format of the existing file is used. Using BigTIFF with kind='imagej' produces a non-conformant file and raises a UserWarning.

  • byteorder (ByteOrder | None) – Endianness of TIFF format. One of ‘<’, ‘>’, ‘=’, or ‘|’. The default is the system’s native byte order.

  • append (bool | str) – If file is an existing standard TIFF file, append image data and tags to the file. Pass 'force' to append to files containing metadata (such as OME-TIFF), which may corrupt the existing metadata. Parameters bigtiff and byteorder are set from the existing file. Appending does not scale well with the number of pages already in the file and may corrupt specifically formatted TIFF files such as OME-TIFF, LSM, STK, ImageJ, or FluoView.

  • kind (Literal['generic', 'imagej', 'ome', 'shaped'] | None) –

    Kind of TIFF file to write.

    If 'ome', write OME-TIFF compatible file. By default, the OME-TIFF format is used if the file name extension contains ‘.ome.’ and description is not specified in the first call to TiffWriter.write(). The format supports multiple image series up to 9 dimensions. The default axes order is TZC(S)YX(S). Refer to the OME model for restrictions of this format.

    If 'imagej', write ImageJ hyperstack compatible file. This format handles data types uint8, uint16, or float32 and shapes up to 6 dimensions in TZCYXS order. RGB images (S=3 or S=4) must be uint8. ImageJ hyperstacks do not support BigTIFF or compression. The ImageJ file format is undocumented.

    If 'shaped', write tifffile “shaped” TIFF file. The image shape is stored in JSON format in an ImageDescription tag of the first page of a series. Suppresses auto-detection of OME-TIFF format from the file name extension. This is the default format used by tifffile if the file name extension does not contain ‘.ome.’ and metadata=None is not passed to TiffWriter.write().

    If 'generic', write generic TIFF file without extra metadata. Image series written to generic TIFF may not be recoverable.

    If None (default), 'shaped' is used unless the file name extension contains ‘.ome.’, in which case 'ome' is used.

  • imagej (bool) – Deprecated. Use kind='imagej' instead.

  • ome (bool | None) – Deprecated. Use kind='ome' instead.

  • shaped (bool | None) – Deprecated. Use kind='shaped' or kind='generic' instead.

Raises:

ValueError – The file contains metadata and cannot be appended to without append='force'. mode is not ‘r+’ when append is True. byteorder is not a valid byte order character.

__init__(file, /, *, mode=None, bigtiff=False, byteorder=None, append=False, kind=None, imagej=False, ome=None, shaped=None)
Parameters:
  • file (str | os.PathLike[Any] | FileHandle | IO[bytes])

  • mode (Literal['w', 'x', 'r+'] | None)

  • bigtiff (bool)

  • byteorder (ByteOrder | None)

  • append (bool | str)

  • kind (Literal['generic', 'imagej', 'ome', 'shaped'] | None)

  • imagej (bool)

  • ome (bool | None)

  • shaped (bool | None)

Return type:

None

tiff: TiffFormat

Format of TIFF file being written.

write(data=None, *, shape=None, dtype=None, photometric=None, planarconfig=None, extrasamples=None, volumetric=False, tile=None, rowsperstrip=None, bitspersample=None, compression=None, compressionargs=None, predictor=None, subsampling=None, jpegtables=None, iccprofile=None, colormap=None, description=None, datetime=None, resolution=None, resolutionunit=None, subfiletype=None, software=None, subifds=None, metadata=METADATA_DEFAULT, extratags=None, contiguous=False, truncate=False, align=None, maxworkers=None, buffersize=None, returnoffset=False)

Write multi-dimensional image to series of TIFF pages.

Metadata in JSON, ImageJ, or OME-XML format are written to the ImageDescription tag of the first page of a series by default, such that the image can later be read back as an array of the same shape.

The values of the ImageWidth, ImageLength, ImageDepth, and SamplesPerPixel tags are inferred from the last dimensions of the data’s shape. The value of the SampleFormat tag is inferred from the data’s dtype. Image data are written uncompressed in one strip per plane by default. Dimensions higher than 2 to 4 (depending on photometric mode, planar configuration, and volumetric mode) are flattened and written as separate pages. If the data size is zero, write a single page with shape (0, 0).

Parameters:
  • data (ArrayLike | Iterator[NDArray[Any] | None] | Iterator[bytes] | Iterator[tuple[bytes, int]] | None) – Image data to write. If None, an empty image is written, which size and type must be specified using shape and dtype arguments. This option cannot be used with compression, predictors, packed integers, or bilevel images. A copy of array-like data is made if it is not a C-contiguous NumPy or dask array with the same byteorder as the TIFF file. Iterators must yield ndarrays or bytes compatible with the file’s byteorder as well as the shape and dtype arguments. Iterator bytes must be compatible with the compression, predictor, subsampling, and jpegtables arguments. If tile is specified, iterator items must match the tile shape. Incomplete tiles are zero-padded. Iterators of non-tiled images must yield ndarrays of shape[1:] or strips as bytes. Iterators of strip ndarrays are not supported. Writing dask arrays might be excruciatingly slow for arrays with many chunks or files with many segments. (https://github.com/dask/dask/issues/8570).

  • shape (Sequence[int] | None) – Shape of image to write. The default is inferred from the data argument if possible. A ValueError is raised if the value is incompatible with the data or other arguments.

  • dtype (DTypeLike | None) – NumPy data type of image to write. The default is inferred from the data argument if possible. A ValueError is raised if the value is incompatible with the data argument.

  • photometric (PHOTOMETRIC | int | str | None) – Color space of image. The default is inferred from the data shape, dtype, and the colormap argument. A UserWarning is logged if RGB color space is auto-detected. Specify this parameter to silence the warning and to avoid ambiguities. MINISBLACK: for bilevel and grayscale images, 0 is black. MINISWHITE: for bilevel and grayscale images, 0 is white. RGB: the image contains red, green and blue samples. SEPARATED: the image contains CMYK samples. PALETTE: the image is used as an index into a colormap. CFA: the image is a Color Filter Array. The CFARepeatPatternDim, CFAPattern, and other DNG or TIFF/EP tags must be specified in extratags to produce a valid file. The value is written to the PhotometricInterpretation tag.

  • planarconfig (PLANARCONFIG | int | str | None) – Interleaved or planar sample storage. CONTIG: the last dimension contains samples. SEPARATE: the 3rd or 4th last dimension contains samples. The default is inferred from the data shape and photometric mode. If this parameter is set, extra samples are used to store grayscale images. The value is written to the PlanarConfiguration tag.

  • extrasamples (Sequence[EXTRASAMPLE | int | str] | None) – Interpretation of extra components in pixels. UNSPECIFIED: no transparency information (default). ASSOCALPHA: true transparency with premultiplied color. UNASSALPHA: independent transparency masks. The values are written to the ExtraSamples tag.

  • volumetric (bool) – Volumetric image stored on single page via SGI ImageDepth tag. The volumetric format is not part of the TIFF specification, and few software can read it. OME and ImageJ formats are not compatible with volumetric storage.

  • tile (Sequence[int] | None) – Shape ([depth,] length, width) of image tiles to write. By default, image data are written in strips. The tile length and width must be a multiple of 16. If a tile depth is provided, the SGI ImageDepth and TileDepth tags are used to write volumetric data. Tiles cannot be used to write contiguous series, except if the tile shape matches the data shape. The values are written to the TileWidth, TileLength, and TileDepth tags.

  • rowsperstrip (int | None) – Number of rows per strip. By default, strips are about 256 KB if compression is enabled, else rowsperstrip is set to the image length. The value is written to the RowsPerStrip tag.

  • bitspersample (int | None) – Number of bits per sample. The default is the number of bits of the data’s dtype. Different values per samples are not supported. Unsigned integer data are packed into bytes as tightly as possible. Valid values are 1-8 for uint8, 9-16 for uint16, and 17-32 for uint32. This setting cannot be used with compression, contiguous series, or empty files. The value is written to the BitsPerSample tag.

  • compression (COMPRESSION | int | str | bool | None) – Compression scheme used on image data. By default, image data are written uncompressed. Compression cannot be used to write contiguous series. Compressors may require certain data shapes, types or value ranges. For example, JPEG compression requires grayscale or RGB(A), uint8 or 12-bit uint16. JPEG compression is experimental. JPEG markers and TIFF tags may not match. Only a limited set of compression schemes are implemented. ‘ZLIB’ is short for ADOBE_DEFLATE. The value is written to the Compression tag.

  • compressionargs (dict[str, Any] | None) – Extra keyword arguments for compression codec. Refer to the Imagecodecs implementation for supported arguments.

  • predictor (PREDICTOR | int | str | bool | None) – Differencing predictor applied before compression. By default, no operator is applied. Predictors can only be used with certain compression schemes and data types. The value is written to the Predictor tag.

  • subsampling (tuple[int, int] | None) – Chroma subsampling factors for JPEG-compressed RGB images. Values: (1, 1), (2, 1), (2, 2), or (4, 1). The default is (2, 2). Currently applies to JPEG compression of RGB images only. Images are stored in YCbCr color space, the value of the PhotometricInterpretation tag is YCBCR. Segment widths must be a multiple of 8 times the horizontal factor. Segment lengths and rowsperstrip must be a multiple of 8 times the vertical factor. The values are written to the YCbCrSubSampling tag.

  • jpegtables (bytes | None) – JPEG quantization and Huffman tables. Use for copying pre-compressed JPEG segments. The value is written to the JPEGTables tag.

  • iccprofile (bytes | None) – ICC device profile characterizing image color space. The value is written verbatim to the InterColorProfile tag.

  • colormap (ArrayLike | None) – RGB color values for corresponding data value. The colormap array must be of shape (3, 2\*\*(data.itemsize*8)) (or (3, 256) for ImageJ) and dtype uint16. The image’s data type must be uint8 or uint16 (or float32 for ImageJ) and the values are indices into the last dimension of the colormap. The value is written to the ColorMap tag.

  • description (str | bytes | None) – Subject of image. Must be 7-bit ASCII. Cannot be used with the ImageJ or OME formats. The value is written to the ImageDescription tag of the first page of a series.

  • datetime (str | bool | DateTime | None) – Date and time of image creation. String in %Y:%m:%d %H:%M:%S format, datetime.datetime object, or True for now. The value is written to the DateTime tag of the first page of a series.

  • resolution (tuple[float | tuple[int, int], float | tuple[int, int]] | None) – Number of pixels per resolutionunit in X and Y directions. Values are float or rational numbers. The default is (1.0, 1.0). The values are written to the YResolution and XResolution tags.

  • resolutionunit (RESUNIT | int | str | None) – Unit of measurement for resolution values. The default is NONE if resolution is not specified and for ImageJ format, else INCH. The value is written to the ResolutionUnit tags.

  • subfiletype (FILETYPE | int | None) – Bitfield to indicate kind of image. Set bit 0 if the image is a reduced-resolution version of another image. Set bit 1 if the image is part of a multi-page image. Set bit 2 if the image is transparency mask for another image (photometric must be MASK, SamplesPerPixel and bitspersample must be 1).

  • software (str | bytes | bool | None) – Name of software used to create file. Must be 7-bit ASCII. The default is ‘tifffile.py’. Unless False, the value is written to the Software tag of the first page of a series.

  • subifds (int | Sequence[int] | None) – Number of child IFDs to write per page (int or sequence). If a sequence is given, its length is used (for example, a TiffPage.subifds tuple). If greater than 0, the following subifds number of series are written as child IFDs of the current series as a SubIFD tree: all SubIFD offsets are stored directly in the parent’s SubIFDs tag and all SubIFD NextIFD fields are zero, as required by DNG and TIFF-EP. If less than 0, abs(subifds) SubIFD levels are written as a SubIFD chain: only the first SubIFD offset is stored in the parent’s SubIFDs tag, and subsequent SubIFDs are linked via their NextIFD fields. The number of IFDs written for each SubIFD level must match the number of IFDs written for the current series. All pages written to a certain SubIFD level of the current series must have the same hash. SubIFDs cannot be used with truncated or ImageJ files. SubIFDs in OME-TIFF files must be sub-resolutions of the main IFDs.

  • metadata (dict[str, Any] | None) – Additional metadata for ImageDescription or IJMetadata tags. Metadata do not determine, but must match, how image data is written to the file. By default, the image shape and dtype are written in shaped format with no additional metadata keys. If None, or the shaped argument to TiffWriter is False, no information in JSON format is written to the ImageDescription tag. The ‘axes’ item defines the character codes for dimensions in data or shape. Refer to OmeXml for supported keys when writing OME-TIFF. Refer to imagej_description() and imagej_metadata_tag() for items supported by the ImageJ format. Items ‘Info’, ‘Labels’, ‘Ranges’, ‘LUTs’, ‘Plot’, ‘ROI’, and ‘Overlays’ are written to the IJMetadata and IJMetadataByteCounts tags. Strings must be 7-bit ASCII. Written with the first page of a series only.

  • extratags (Sequence[TagTuple] | None) –

    Additional tags to write. A list of tuples with 5 items:

    1. code (int): Tag Id.

    2. dtype (DATATYPE): Data type of items in value.

    3. count (int): Number of data values. Not used for string or bytes values.

    4. value (Sequence[Any]): count values compatible with dtype. Bytes must contain count values of dtype packed as binary data.

    5. writeonce (bool): Write tag to first page of a series only.

    Duplicate and select tags in TIFF.TAG_FILTERED are not written if the extratag is specified by integer code. Extratags cannot be used to write IFD type tags.

  • contiguous (bool) – Write data contiguously after the previous series. If False (default), write data to a new series. If True and the data and arguments are compatible with previous written ones (same shape, no compression, etc.), the image data are stored contiguously after the previous one. In that case, photometric, planarconfig, and rowsperstrip are ignored. Metadata such as description, metadata, datetime, and extratags are written to the first page of a contiguous series only. Contiguous mode cannot be used with the OME or ImageJ formats.

  • truncate (bool) – Write only first page of contiguous series if possible. If True, only write first page of contiguous series if possible (uncompressed, contiguous, not tiled). Other TIFF readers will only be able to read part of the data. Cannot be used with the OME format.

  • align (int | None) – Byte boundary on which to align image data in file. The default is 16. Use mmap.ALLOCATIONGRANULARITY for memory-mapped data. Following contiguous writes are not aligned.

  • maxworkers (int | None) – Maximum number of threads for compressing tiles or strips. If None or 0, use up to _TIFF.MAXWORKERS CPU cores for compressing large segments. Using multiple threads can significantly speed up this function if the bottleneck is encoding the data, for example, in case of large JPEG compressed tiles. If the bottleneck is I/O or pure Python code, using multiple threads might be detrimental.

  • buffersize (int | None) – Approximate number of bytes to compress in one pass. The default is _TIFF.BUFFERSIZE * 2.

  • returnoffset (bool) – Return offset and byte count of memory-mappable image data.

Returns:

If returnoffset is True and the image data in the file are memory-mappable, return the offset and number of bytes of the image data in the file.

Return type:

tuple[int, int] | None

overwrite_description(description, /)

Overwrite value of last ImageDescription tag.

Can be used to write OME-XML after writing images. Ends a contiguous series.

Parameters:

description (str)

Return type:

None

close()

Write remaining pages and close file handle.

Return type:

None

property filehandle: FileHandle

File handle of TIFF file being written.

__repr__()

Return repr(self).

Return type:

str

__weakref__

list of weak references to the object

final class tifffile.TiledSequence(stackshape, chunkshape, /, *, axestiled=None, axes=None)

Bases: object

Tiled sequence of chunks.

Transform a sequence of stacked chunks to tiled chunks.

Parameters:
  • stackshape (Sequence[int]) – Shape of stacked sequence excluding chunks.

  • chunkshape (Sequence[int]) – Shape of chunks.

  • axestiled (dict[int, int] | Sequence[tuple[int, int]] | None) – Axes to be tiled. Map stacked sequence axis to chunk axis. By default, the sequence is not tiled.

  • axes (str | tuple[str, ...] | None) – Character codes for dimensions in stackshape and chunkshape.

Examples

>>> ts = TiledSequence((1, 2), (3, 4), axestiled={1: 0}, axes='ABYX')
>>> ts.shape
(1, 6, 4)
>>> ts.chunks
(1, 3, 4)
>>> ts.axes
'AYX'
__init__(stackshape, chunkshape, /, *, axestiled=None, axes=None)
Parameters:
  • stackshape (Sequence[int])

  • chunkshape (Sequence[int])

  • axestiled (dict[int, int] | Sequence[tuple[int, int]] | None)

  • axes (str | Sequence[str] | None)

Return type:

None

shape: tuple[int, ...]

Shape of tiled sequence including chunks.

chunks: tuple[int, ...]

Shape of chunks in tiled sequence.

axes: str | tuple[str, ...] | None

Dimension codes of tiled sequence.

shape_squeezed: tuple[int, ...]

Shape of tiled sequence with length-1 dimensions removed.

axes_squeezed: str | tuple[str, ...] | None

Dimension codes of tiled sequence with length-1 dimensions removed.

indices(indices, /)

Return iterator over chunk indices of tiled sequence.

Parameters:

indices (Iterable[Sequence[int]]) – Indices of chunks in stacked sequence.

Return type:

Iterator[tuple[int, …]]

slices(indices=None, /)

Return iterator over slices of chunks in tiled sequence.

Parameters:

indices (Iterable[Sequence[int]] | None) – Indices of chunks in stacked sequence. By default, iterate over all chunks in stacked sequence.

Return type:

Iterator[tuple[int | slice, …]]

property ndim: int

Number of dimensions in tiled sequence.

property is_tiled: bool

Sequence is tiled.

__repr__()

Return repr(self).

Return type:

str

final class tifffile.Timer(message=None, *, end=' ', started=None)

Bases: object

Stopwatch for timing execution speed.

Parameters:
  • message (str | None) – Message to print.

  • end (str) – End of print statement.

  • started (float) – Value of performance counter when started. The default is the current performance counter.

Examples

>>> import time
>>> with Timer('sleep:'):
...     time.sleep(1.05)
sleep: 1.0... s
__init__(message=None, *, end=' ', started=None)
Parameters:
  • message (str | None)

  • end (str)

  • started (float | None)

Return type:

None

duration: float

Duration between started and stopped in seconds.

started: float

Value of performance counter when started.

stopped: float

Value of performance counter when stopped.

start(message=None, *, end=' ')

Start timer and return current time.

Parameters:
  • message (str | None)

  • end (str)

Return type:

float

stop(message=None, *, end=' ')

Return duration of timer since start.

Parameters:
  • message (str | None) – Message to print.

  • end (str) – End of print statement.

Return type:

float

print(message=None, *, end=None)

Print duration from timer start till last stop or now.

Parameters:
  • message (str | None) – Message to print.

  • end (str | None) – End of print statement.

Return type:

None

static clock()

Return value of performance counter.

Return type:

float

__str__()

Return duration from timer start till last stop or now.

Return type:

str

__repr__()

Return repr(self).

Return type:

str

tifffile.askopenfilename(**kwargs)

Return file name from Tkinter’s file open dialog, or ‘’ if cancelled.

Parameters:

kwargs (Any)

Return type:

str

tifffile.astype(value, /, types=None)

Return argument converted to first matching type.

By default, tries to convert to int, float, bool (via asbool), and str (via bytes2str), in that order.

>>> astype('42')
42
>>> astype('3.14')
3.14
>>> astype('True')
True
>>> astype(b'Neee-Wom')
'Neee-Wom'
Parameters:
  • value (Any)

  • types (Sequence[Callable[..., Any]] | None)

Return type:

Any

tifffile.create_output(out, /, shape, dtype, *, mode='w+', suffix=None, fillvalue=None)

Return NumPy array where data of shape and dtype can be copied.

Parameters:
  • out (OutputType) –

    Specifies kind of array of shape and dtype to return:

    None:

    Return new array.

    numpy.ndarray:

    Return view of existing array.

    'memmap' or 'memmap:tempdir':

    Return memory-map to array stored in temporary binary file.

    str or open file:

    Return memory-map to array stored in specified binary file.

  • shape (Sequence[int]) – Shape of array to return.

  • dtype (DTypeLike | None) – Data type of array to return. If out is an existing array, dtype must be castable to its data type.

  • mode (Literal['r+', 'w+', 'r', 'c']) – File mode to create memory-mapped array. Only used when out is a file path or 'memmap'. The default is ‘w+’ to create new, or overwrite existing file for reading and writing.

  • suffix (str | None) – Suffix of NamedTemporaryFile if out is 'memmap'. Only used when out is 'memmap'. The default is ‘.memmap’.

  • fillvalue (float | None) – Value to initialize output array. By default, return uninitialized array.

Returns:

NumPy array or memory-mapped array of shape and dtype.

Raises:

ValueError – Existing array cannot be reshaped to shape or cast to dtype.

Return type:

NDArray[Any] | numpy.memmap[Any, Any]

tifffile.enumarg(enumtype, arg, /)

Return enum member from its name or value.

Parameters:
  • enumtype (type[enum.IntEnum]) – Type of IntEnum.

  • arg (Any) – Name or value of enum member.

Returns:

Enum member matching name or value.

Raises:

ValueError – No enum member matches name or value.

Return type:

enum.IntEnum

Examples

>>> enumarg(PHOTOMETRIC, 2)
<PHOTOMETRIC.RGB: 2>
>>> enumarg(PHOTOMETRIC, 'RGB')
<PHOTOMETRIC.RGB: 2>
tifffile.enumstr(member, /)

Return short string representation of Enum member.

>>> enumstr(PHOTOMETRIC.RGB)
'RGB'
Parameters:

member (Enum)

Return type:

str

tifffile.format_size(size, /, threshold=1536)

Return file size as string from byte size.

Sizes below 1.5 KiB (1536 B) are shown in bytes; larger sizes are shown in the largest unit that keeps the value below the threshold.

>>> format_size(1234)
'1234 B'
>>> format_size(12345678901)
'11.50 GiB'
Parameters:
  • size (float)

  • threshold (float)

Return type:

str

tifffile.hexdump(data, /, *, width=75, height=24, snipat=0.75, modulo=2, ellipsis=None)

Return hexdump representation of bytes.

Parameters:
  • data (bytes) – Bytes to represent as hexdump.

  • width (int) – Maximum width of hexdump.

  • height (int) – Maximum number of lines of hexdump.

  • snipat (float | None) – Approximate position at which to split long hexdump.

  • modulo (int) – Number of bytes represented in line of hexdump are modulus of this value.

  • ellipsis (str | None) – Characters to insert for snipped content of long hexdump. The default is ‘…’.

Return type:

str

Examples

>>> import binascii
>>> hexdump(binascii.unhexlify('49492a00080000000e00fe0004000100'))
'49 49 2a 00 08 00 00 00 0e 00 fe 00 04 00 01 00 II*.............'
tifffile.imagej_description(shape, /, axes=None, *, rgb=None, colormapped=False, **metadata)

Return ImageJ image description from data shape and metadata.

Parameters:
  • shape (Sequence[int]) – Shape of image array.

  • axes (str | None) – Character codes for dimensions in shape. ImageJ can handle up to 6 dimensions in order TZCYXS. Axes and shape are used to determine the images, channels, slices, and frames entries of the image description.

  • rgb (bool | None) – Image is RGB type.

  • colormapped (bool) – Image is indexed color.

  • **metadata (Any) –

    Additional items to be included in image description:

    ImageJ (str):

    ImageJ version string. The default is ‘1.11a’.

    hyperstack (bool):

    Image is a hyperstack. The default is True unless colormapped is True.

    mode (str):

    Display mode: ‘grayscale’, ‘composite’, or ‘color’. The default is ‘grayscale’ unless rgb or colormapped are True. Ignored if hyperstack is False.

    loop (bool):

    Loop frames back and forth. The default is False.

    finterval (float):

    Frame interval in seconds.

    fps (float):

    Frames per seconds. The inverse of finterval.

    spacing (float):

    Voxel spacing in unit units.

    unit (str):

    Unit for spacing and X/YResolution tags. Usually ‘um’ (micrometer) or ‘pixel’.

    xorigin, yorigin, zorigin (float):

    X, Y, and Z origins in pixel units.

    images, channels, slices, frames (int):

    Ignored.

Return type:

str

Examples

>>> print(imagej_description((51, 5, 2, 196, 171)))
ImageJ=1.11a
images=510
channels=2
slices=5
frames=51
hyperstack=true
mode=grayscale
loop=false
tifffile.imagej_metadata_tag(metadata, byteorder, /)

Return IJMetadata and IJMetadataByteCounts tags from metadata dict.

Parameters:
  • metadata (dict[str, Any]) –

    May contain the following keys and values:

    ’Info’ (str):

    Human-readable information as string.

    ’Labels’ (Sequence[str]):

    Human-readable label for each image.

    ’Ranges’ (Sequence[float]):

    Lower and upper values for each channel.

    ’LUTs’ (list[numpy.ndarray[(3, 256), ‘uint8’]]):

    Color palettes for each channel.

    ’Plot’ (bytes):

    Undocumented ImageJ internal format.

    ’ROI’, ‘Overlays’ (bytes):

    Undocumented ImageJ internal region of interest and overlay format. Can be created with the roifile package.

    ’Properties’ (dict[str, str]):

    Map of key, value items.

  • byteorder (ByteOrder) – Byte order of TIFF file.

Returns:

IJMetadata and IJMetadataByteCounts tags in TiffWriter.write() extratags format.

Return type:

tuple[tuple[int, int, int, bytes, bool], tuple[int, int, int, bytes, bool]]

tifffile.imread(files: str | os.PathLike[Any] | FileHandle | IO[bytes] | Sequence[str | os.PathLike[Any]] | None = None, *, selection: Any | None = None, return_as: Literal['xarray'], key: int | slice | Sequence[int] | None = None, series: int | None = None, kind: str | None = None, level: int | None = None, squeeze: bool | None = None, maxworkers: int | None = None, buffersize: int | None = None, mode: Literal['r', 'r+'] | None = None, name: str | None = None, offset: int | None = None, size: int | None = None, pattern: str | None = None, axesorder: Sequence[int] | None = None, categories: dict[str, dict[str, int]] | None = None, imread: Callable[..., NDArray[Any]] | None = None, imreadargs: dict[str, Any] | None = None, sort: Callable[..., Any] | bool | None = None, container: str | os.PathLike[Any] | None = None, chunkshape: tuple[int, ...] | None = None, chunkdtype: DTypeLike | None = None, axestiled: dict[int, int] | Sequence[tuple[int, int]] | None = None, ioworkers: int | None = 1, chunkmode: CHUNKMODE | int | str | None = None, fillvalue: float | None = None, zattrs: dict[str, Any] | None = None, multiscales: bool | None = None, omexml: str | None = None, superres: int | None = None, out: OutputType = None, out_inplace: bool | None = None, _multifile: bool | None = None, _useframes: bool | None = None, **kwargs: Any) DataArray
tifffile.imread(files: str | os.PathLike[Any] | FileHandle | IO[bytes] | Sequence[str | os.PathLike[Any]] | None = None, *, selection: Any | None = None, return_as: Literal['zarr'], key: int | slice | Sequence[int] | None = None, series: int | None = None, kind: str | None = None, level: int | None = None, squeeze: bool | None = None, maxworkers: int | None = None, buffersize: int | None = None, mode: Literal['r', 'r+'] | None = None, name: str | None = None, offset: int | None = None, size: int | None = None, pattern: str | None = None, axesorder: Sequence[int] | None = None, categories: dict[str, dict[str, int]] | None = None, imread: Callable[..., NDArray[Any]] | None = None, imreadargs: dict[str, Any] | None = None, sort: Callable[..., Any] | bool | None = None, container: str | os.PathLike[Any] | None = None, chunkshape: tuple[int, ...] | None = None, chunkdtype: DTypeLike | None = None, axestiled: dict[int, int] | Sequence[tuple[int, int]] | None = None, ioworkers: int | None = 1, chunkmode: CHUNKMODE | int | str | None = None, fillvalue: float | None = None, zattrs: dict[str, Any] | None = None, multiscales: bool | None = None, omexml: str | None = None, superres: int | None = None, out: OutputType = None, out_inplace: bool | None = None, _multifile: bool | None = None, _useframes: bool | None = None, **kwargs: Any) ZarrTiffStore | ZarrFileSequenceStore
tifffile.imread(files: str | os.PathLike[Any] | FileHandle | IO[bytes] | Sequence[str | os.PathLike[Any]] | None = None, *, selection: Any | None = None, return_as: Literal['numpy'] | None = None, key: int | slice | Sequence[int] | None = None, series: int | None = None, kind: str | None = None, level: int | None = None, squeeze: bool | None = None, maxworkers: int | None = None, buffersize: int | None = None, mode: Literal['r', 'r+'] | None = None, name: str | None = None, offset: int | None = None, size: int | None = None, pattern: str | None = None, axesorder: Sequence[int] | None = None, categories: dict[str, dict[str, int]] | None = None, imread: Callable[..., NDArray[Any]] | None = None, imreadargs: dict[str, Any] | None = None, sort: Callable[..., Any] | bool | None = None, container: str | os.PathLike[Any] | None = None, chunkshape: tuple[int, ...] | None = None, chunkdtype: DTypeLike | None = None, axestiled: dict[int, int] | Sequence[tuple[int, int]] | None = None, ioworkers: int | None = 1, chunkmode: CHUNKMODE | int | str | None = None, fillvalue: float | None = None, zattrs: dict[str, Any] | None = None, multiscales: bool | None = None, omexml: str | None = None, superres: int | None = None, out: OutputType = None, out_inplace: bool | None = None, _multifile: bool | None = None, _useframes: bool | None = None, **kwargs: Any) NDArray[Any]

Return image from TIFF file(s) as NumPy array or Zarr store.

The first image series in the file(s) is returned by default.

Parameters:
  • files (str | os.PathLike[Any] | FileHandle | IO[bytes] | Sequence[str | os.PathLike[Any]] | None) – File name, seekable binary stream, glob pattern, or sequence of file names. May be None if container is specified.

  • selection (Any | None) – Subset of image to be extracted. If not None, a Zarr array is created internally, indexed with the selection value, and returned as a NumPy array (not a store). Only segments that are part of the selection will be read from file. Refer to the Zarr documentation for valid selections. Depending on selection size, image size, and storage properties, it may be more efficient to read the whole image from file and then index it.

  • return_as (Literal['numpy', 'xarray', 'zarr'] | None) – Return type of image data. If 'xarray', return as xarray.DataArray. Cannot be combined with selection. Not supported for file sequences. If 'zarr', return as Zarr store. When selection is not None, a Zarr store is used internally regardless of this value, but a NumPy array is returned. If 'numpy' or None (default), return as NumPy array.

  • aszarr (bool) – Deprecated: use return_as='zarr'.

  • mode (Literal['r', 'r+'] | None) – Passed to TiffFile.

  • name (str | None) – Passed to TiffFile.

  • offset (int | None) – Passed to TiffFile.

  • size (int | None) – Passed to TiffFile.

  • superres (int | None) – Passed to TiffFile.

  • omexml (str | None) – Passed to TiffFile.

  • _multifile (bool | None) – Passed to TiffFile.

  • _useframes (bool | None) – Passed to TiffFile.

  • key (int | slice | Sequence[int] | None) – Passed to TiffFile.asarray(), TiffFile.asxarray(), or TiffFile.aszarr(). When return_as='zarr' or return_as='xarray' and reading a single file, key must be None or an integer.

  • series (int | None) – Passed to TiffFile.asarray(), TiffFile.asxarray(), or TiffFile.aszarr(). When return_as='zarr' or return_as='xarray' and reading a single file, key must be None or an integer.

  • kind (str | None) – Passed to TiffFile.asarray(), TiffFile.asxarray(), or TiffFile.aszarr(). When return_as='zarr' or return_as='xarray' and reading a single file, key must be None or an integer.

  • level (int | None) – Passed to TiffFile.asarray(), TiffFile.asxarray(), or TiffFile.aszarr(). When return_as='zarr' or return_as='xarray' and reading a single file, key must be None or an integer.

  • squeeze (bool | None) – Passed to TiffFile.asarray(), TiffFile.asxarray(), or TiffFile.aszarr(). When return_as='zarr' or return_as='xarray' and reading a single file, key must be None or an integer.

  • maxworkers (int | None) – Passed to TiffFile.asarray(), TiffFile.asxarray(), or TiffFile.aszarr(). When return_as='zarr' or return_as='xarray' and reading a single file, key must be None or an integer.

  • buffersize (int | None) – Passed to TiffFile.asarray(), TiffFile.asxarray(), or TiffFile.aszarr(). When return_as='zarr' or return_as='xarray' and reading a single file, key must be None or an integer.

  • imread (Callable[..., NDArray[Any]] | None) – Passed to FileSequence.

  • container (str | os.PathLike[Any] | None) – Passed to FileSequence.

  • sort (Callable[..., Any] | bool | None) – Passed to FileSequence.

  • pattern (str | None) – Passed to FileSequence.

  • axesorder (Sequence[int] | None) – Passed to FileSequence.

  • axestiled (dict[int, int] | Sequence[tuple[int, int]] | None) – Passed to FileSequence.

  • categories (dict[str, dict[str, int]] | None) – Passed to FileSequence.

  • chunkmode (CHUNKMODE | int | str | None) – Passed to ZarrTiffStore or ZarrFileSequenceStore.

  • fillvalue (float | None) – Passed to ZarrTiffStore or ZarrFileSequenceStore.

  • zattrs (dict[str, Any] | None) – Passed to ZarrTiffStore or ZarrFileSequenceStore.

  • multiscales (bool | None) – Passed to ZarrTiffStore or ZarrFileSequenceStore.

  • chunkshape (tuple[int, ...] | None) – Passed to FileSequence.asarray() or ZarrFileSequenceStore.

  • chunkdtype (DTypeLike | None) – Passed to FileSequence.asarray() or ZarrFileSequenceStore.

  • ioworkers (int | None) – Passed to FileSequence.asarray() or ZarrFileSequenceStore.

  • out_inplace (bool | None) – Passed to FileSequence.asarray().

  • out (OutputType) – Passed to TiffFile.asarray(), FileSequence.asarray(), or zarr_selection().

  • imreadargs (dict[str, Any] | None) – Additional arguments passed to FileSequence.imread.

  • **kwargs (Any) – Additional arguments passed to TiffFile or FileSequence.imread.

Returns:

Images from specified files, series, or pages. Zarr store instances must be closed after use. See TiffPage.asarray() for operations that are applied (or not) to the image data stored in the file.

Raises:
  • ValueError – No files matching the pattern were found. Binary IO streams are not supported with container. key is not None or an integer when return_as='zarr' or return_as='xarray'. return_as='xarray' and aszarr are both set.

  • NotImplementedErrorreturn_as='xarray' and a file sequence is used. return_as='xarray' and selection are both specified.

  • TypeError – Unexpected keyword arguments were passed.

Return type:

NDArray[Any] | ZarrTiffStore | ZarrFileSequenceStore | DataArray

tifffile.imshow(data, /, *, photometric=None, planarconfig=None, bitspersample=None, nodata=0, interpolation=None, cmap=None, vmin=None, vmax=None, figure=None, subplot=None, title=None, window_title=None, dpi=96, maxdim=None, background=None, show=False, **kwargs)

Plot n-dimensional images with matplotlib.pyplot.

Parameters:
  • data (NDArray[Any]) – Image array to display.

  • photometric (PHOTOMETRIC | int | str | None) – Color space of image.

  • planarconfig (PLANARCONFIG | int | str | None) – How components of each pixel are stored.

  • bitspersample (int | None) – Number of bits per channel in integer RGB images.

  • interpolation (str | None) – Image interpolation method used in matplotlib.imshow. The default is ‘bilinear’ for image dimensions > 512, else ‘nearest’.

  • cmap (Any) – Colormap mapping non-RGBA scalar data to colors. See matplotlib.colors.Colormap.

  • vmin (float | None) – Minimum of data range covered by colormap. By default, the complete range of the data is covered.

  • vmax (float | None) – Maximum of data range covered by colormap. By default, the complete range of the data is covered.

  • figure (Any) – Matplotlib figure to use for plotting. See matplotlib.figure.Figure.

  • subplot (Any) – A matplotlib.pyplot.subplot axis.

  • title (str | bytes | None) – Subplot title.

  • window_title (str | None) – Window title.

  • dpi (int) – Resolution of figure.

  • maxdim (int | None) – Maximum image width and length.

  • background (tuple[float, float, float] | str | None) – Background color.

  • show (bool) – Display figure.

  • **kwargs (Any) – Additional arguments passed to matplotlib.pyplot.imshow().

  • nodata (float)

Returns:

Matplotlib figure, subplot, and plot axis.

Return type:

tuple[Any, Any, Any]

tifffile.imwrite(file, /, data=None, *, mode=None, bigtiff=None, byteorder=None, kind=None, imagej=False, ome=None, shaped=None, append=False, shape=None, dtype=None, photometric=None, planarconfig=None, extrasamples=None, volumetric=False, tile=None, rowsperstrip=None, bitspersample=None, compression=None, compressionargs=None, predictor=None, subsampling=None, jpegtables=None, iccprofile=None, colormap=None, description=None, datetime=None, resolution=None, resolutionunit=None, subfiletype=None, software=None, metadata=METADATA_DEFAULT, extratags=None, contiguous=False, truncate=False, align=None, maxworkers=None, buffersize=None, returnoffset=False)

Write array or image data to TIFF file.

A BigTIFF file is written if the data size is larger than 4 GB less 32 MB for metadata, and bigtiff is not False, and imagej, truncate and compression are not enabled. Unless byteorder is specified, the TIFF file byte order is determined from the dtype of data or the dtype argument.

Parameters:
Returns:

If returnoffset is True and the image data in the file are memory-mappable, a tuple of (offset, bytecount). Otherwise None.

Raises:

ValueErrordata is None and shape or dtype is not provided.

Return type:

tuple[int, int] | None

tifffile.logger()

Return logger for tifffile module.

Return type:

Logger

tifffile.matlabstr2py(matlabstr, /)

Return Python object from Matlab string representation.

Use to access ScanImage metadata.

Parameters:

matlabstr (str) – String representation of Matlab objects.

Returns:

Matlab structures are returned as dict. Matlab arrays or cells are returned as lists. Other Matlab objects are returned as str, bool, int, or float.

Return type:

Any

Examples

>>> matlabstr2py('1')
1
>>> matlabstr2py("['x y z' true false; 1 2.0 -3e4; NaN Inf @class]")
[['x y z', True, False], [1, 2.0, -30000.0], [nan, inf, '@class']]
>>> d = matlabstr2py(
...     "SI.hChannels.channelType = {'stripe' 'stripe'}\n"
...     "SI.hChannels.channelsActive = 2"
... )
>>> d['SI.hChannels.channelType']
['stripe', 'stripe']
tifffile.memmap(filename, /, *, shape=None, dtype=None, page=None, series=None, kind=None, level=None, squeeze=None, mode='r+', **kwargs)

Return memory-mapped NumPy array of image data stored in TIFF file.

Memory-mapping requires the image data to be stored in native byte order, without tiling, compression, predictors, etc. If both shape and dtype are provided, a new TIFF file is created (overwriting or appending depending on the append keyword argument) and the image data region is memory-mapped read-write. Otherwise, the image data of a specified page or series in an existing file are memory-mapped. Call flush to write any changes in the array back to the file.

Parameters:
  • filename (str | os.PathLike[Any]) – Name of TIFF file to create or memory-map.

  • shape (Sequence[int] | None) – Shape of array to create. Requires dtype. If provided together with dtype, a new TIFF file is written.

  • dtype (DTypeLike | None) – Data type of array to create. Requires shape.

  • page (int | None) – Index of page whose image data to memory-map. If provided, series, kind, and level are ignored.

  • series (int | None) – Index of page series to memory-map (default is 0). Ignored if page is set.

  • kind (str | None) – Series format kind, such as 'ome' or 'imagej'. By default, the format is auto-detected. Ignored if page is set.

  • level (int | None) – Index of pyramid level to memory-map (default is 0). Ignored if page is set.

  • squeeze (bool | None) – Remove length-1 dimensions from the memory-mapped array shape, except X and Y. If False, preserve all dimensions. If None (default), remove length-1 dimensions except for 'shaped' series. For single pages, None is treated as True.

  • mode (Literal['r+', 'r', 'c']) – Memory-map file open mode for existing files. The default is ‘r+’ (read-write). Use ‘r’ for read-only or ‘c’ for copy-on-write. When creating a new file (shape and dtype provided), this argument is ignored and the file is always opened read-write.

  • **kwargs (Any) – Additional arguments passed to imwrite() when creating a new file, or to TiffFile when reading an existing file.

Returns:

Image data in TIFF file as memory-mapped NumPy array.

Raises:

ValueError – Image data in TIFF file are not memory-mappable.

Return type:

numpy.memmap[Any, Any]

tifffile.natural_sorted(iterable, /)

Return naturally sorted list of strings.

Use to sort file names containing numbers.

>>> natural_sorted(['f1', 'f2', 'f10'])
['f1', 'f2', 'f10']
Parameters:

iterable (Iterable[str])

Return type:

list[str]

tifffile.nullfunc(*args, **kwargs)

Null function.

>>> nullfunc('arg', kwarg='kwarg')
Parameters:
  • args (Any)

  • kwargs (Any)

Return type:

None

tifffile.parse_filenames(files, /, pattern=None, axesorder=None, categories=None, *, _shape=None)

Return shape and axes from sequence of file names matching pattern.

Parameters:
  • files (Sequence[str]) – Sequence of file names to parse.

  • pattern (str | None) – Regular expression pattern matching axes names and chunk indices in file names. By default, no pattern matching is performed. Axes names can be specified by matching groups preceding the index groups in the file name, be provided as group names for the index groups, or be omitted. The predefined ‘axes’ pattern matches Olympus OIF and Leica TIFF series.

  • axesorder (Sequence[int] | None) – Indices of axes in pattern. By default, axes are returned in the order they appear in pattern.

  • categories (dict[str, dict[str, int]] | None) – Map of index group matches to integer indices. {'axislabel': {'category': index}}

  • _shape (Sequence[int] | None) – Shape of file sequence. The default is maximum - minimum + 1 of the parsed indices for each dimension.

Returns:

  • Axes names for each dimension.

  • Shape of file series.

  • Index of each file in shape.

  • Filtered sequence of file names.

Return type:

tuple[tuple[str, …], tuple[int, …], list[tuple[int, …]], Sequence[str]]

Examples

>>> parse_filenames(
...     ['c1001.ext', 'c2002.ext'], r'([^\d])(\d)(?P<t>\d+)\.ext'
... )
(('c', 't'), (2, 2), [(0, 0), (1, 1)], ['c1001.ext', 'c2002.ext'])
tifffile.parse_kwargs(kwargs, /, *keys, **keyvalues)

Extract keys from kwargs into a new dict, removing them from kwargs.

Keys listed in keys are extracted by name only. Keys listed in keyvalues are extracted by name if present in kwargs, otherwise their default value is used. Extracted keys are deleted from kwargs.

>>> kwargs = {'one': 1, 'two': 2, 'four': 4}
>>> parse_kwargs(kwargs, 'two', 'three', four=None, five=5)
{'two': 2, 'four': 4, 'five': 5}
>>> kwargs
{'one': 1}
>>> parse_kwargs({}, 'a', b=2)
{'b': 2}
Parameters:
  • kwargs (dict[str, Any])

  • keys (str)

  • keyvalues (Any)

Return type:

dict[str, Any]

tifffile.pformat(arg, /, *, height=24, width=79, linewidth=288, compact=True)

Return pretty formatted representation of object as string.

Whitespace might be altered. Long lines are cut off.

Parameters:
  • arg (Any)

  • height (int | None)

  • width (int | None)

  • linewidth (int | None)

  • compact (bool)

Return type:

str

tifffile.product(iterable, /)

Return product of integers.

Equivalent of math.prod(iterable), but multiplying NumPy integers does not overflow.

>>> product([2**8, 2**30])
274877906944
>>> product([])
1
Parameters:

iterable (Iterable[int | integer])

Return type:

int

tifffile.rational(arg, /)

Return rational numerator and denominator from float or two integers.

>>> rational(0.5)
(1, 2)
>>> rational((3, 4))
(3, 4)
>>> rational(0)
(0, 1)
Parameters:

arg (float | tuple[int, int])

Return type:

tuple[int, int]

tifffile.read_gdal_structural_metadata(fh, /)

Read non-TIFF GDAL structural metadata from file.

Return None if the file does not contain valid GDAL structural metadata. The metadata can be used to optimize reading image data from a COG file.

Parameters:

fh (FileHandle | IO[bytes])

Return type:

dict[str, str] | None

tifffile.read_micromanager_metadata(fh, /, keys=None)

Return Micro-Manager non-TIFF settings from file.

The settings can be used to read image data without parsing any TIFF structures.

Parameters:
  • fh (FileHandle | IO[bytes]) – Open file handle to Micro-Manager TIFF file.

  • keys (Container[str] | None) – Name of keys to return in result.

Returns:

  • ‘MajorVersion’ (str)

  • ’MinorVersion’ (str)

  • ’Summary’ (dict): Specifies the dataset, such as shape, dimensions, and coordinates.

  • ’IndexMap’ (numpy.ndarray): (channel, slice, frame, position, ifd_offset) indices of all frames.

  • ’DisplaySettings’ (list[dict]): Image display settings such as channel contrast and colors.

  • ’Comments’ (dict): User comments.

Return type:

Micro-Manager non-TIFF settings, which may contain the following keys

Notes

Summary metadata are the same for all files in a dataset. DisplaySettings metadata are frequently corrupted, and Comments are often empty. The Summary and IndexMap metadata are stored at the beginning of the file, while DisplaySettings and Comments are towards the end. Excluding DisplaySettings and Comments from the results may significantly speed up reading metadata of interest.

References

tifffile.read_ndtiff_index(file, /)

Return iterator over fields in Micro-Manager NDTiff.index file.

Parameters:

file (str | os.PathLike[Any]) – Path of NDTiff.index file.

Yields:

Fields in NDTiff.index file

  • axes_dict: Axes indices of frame in image.

  • filename: Name of file containing frame and metadata.

  • dataoffset: Offset of frame data in file.

  • width: Width of frame.

  • height: Height of frame.

  • pixeltype: Pixel type. 0: 8-bit monochrome; 1: 16-bit monochrome; 2: 8-bit RGB; 3: 10-bit monochrome; 4: 12-bit monochrome; 5: 14-bit monochrome; 6: 11-bit monochrome.

  • compression: Pixel compression. 0: Uncompressed.

  • metaoffset: Offset of JSON metadata in file.

  • metabytecount: Length of metadata.

  • metacompression: Metadata compression. 0: Uncompressed.

Return type:

Iterator[tuple[dict[str, int | str], str, int, int, int, int, int, int, int, int]]

tifffile.read_scanimage_metadata(fh, /)

Read ScanImage BigTIFF v3 or v4 static and ROI metadata from file.

The settings can be used to read image and metadata without parsing the TIFF file.

Frame data and ROI groups can alternatively be obtained from the Software and Artist tags of any TIFF page.

Parameters:

fh (FileHandle) – Binary file handle to read from.

Returns:

  • Non-varying frame data, parsed with matlabstr2py().

  • ROI group data, parsed from JSON.

  • Version of metadata (3 or 4).

Raises:

ValueError – File does not contain valid ScanImage metadata.

Return type:

tuple[dict[str, Any], dict[str, Any], int]

tifffile.repeat_nd(a, repeats, /)

Return read-only view into input array with elements repeated.

Zoom image array by integer factors using nearest neighbor interpolation (box filter).

Parameters:
  • a (ArrayLike) – Input array.

  • repeats (Sequence[int]) – Number of repetitions to apply along each dimension of input. Length must equal the number of dimensions in a. All values must be positive integers.

Returns:

Read-only view of a with each element repeated along each axis.

Return type:

NDArray[Any]

Examples

>>> repeat_nd([[1, 2], [3, 4]], (2, 2))
array([[1, 1, 2, 2],
       [1, 1, 2, 2],
       [3, 3, 4, 4],
       [3, 3, 4, 4]])
tifffile.reshape_axes(axes: str, shape: Sequence[int], newshape: Sequence[int], /, unknown: str | None = None) str
tifffile.reshape_axes(axes: Sequence[str], shape: Sequence[int], newshape: Sequence[int], /, unknown: str | None = None) Sequence[str]

Return axes matching new shape.

Parameters:
  • axes (str | Sequence[str]) – Character codes for dimensions in shape.

  • shape (Sequence[int]) – Input shape matching axes.

  • newshape (Sequence[int]) – Output shape matching output axes. Size must match size of shape.

  • unknown (str | None) – Character used for new axes in output. The default is ‘Q’.

Returns:

Character codes for dimensions in newshape.

Return type:

str | Sequence[str]

Examples

>>> reshape_axes('YXS', (219, 301, 1), (219, 301))
'YX'
>>> reshape_axes('IYX', (12, 219, 301), (3, 4, 219, 1, 301, 1))
'QQYQXQ'
tifffile.reshape_nd(data_or_shape: tuple[int, ...], ndim: int, /) tuple[int, ...]
tifffile.reshape_nd(data_or_shape: NDArray[Any], ndim: int, /) NDArray[Any]

Return image array or shape with at least ndim dimensions.

Prepend 1s to image shape as necessary.

Parameters:
  • data_or_shape (tuple[int, ...] | NDArray[Any]) – Image array or shape tuple to expand.

  • ndim (int) – Minimum number of dimensions required. If the input already has at least ndim dimensions, it is returned unchanged.

Returns:

Array or shape tuple with at least ndim dimensions. Ones are prepended as needed.

Return type:

tuple[int, …] | NDArray[Any]

>>> import numpy
>>> reshape_nd(numpy.empty(0), 1).shape
(0,)
>>> reshape_nd(numpy.empty(1), 2).shape
(1, 1)
>>> reshape_nd(numpy.empty((2, 3)), 3).shape
(1, 2, 3)
>>> reshape_nd(numpy.empty((3, 4, 5)), 3).shape
(3, 4, 5)
>>> reshape_nd((2, 3), 3)
(1, 2, 3)
tifffile.strptime(datetime_string, fmt=None, /)

Return datetime corresponding to date string using common formats.

Parameters:
  • datetime_string (str) – String representation of date and time.

  • fmt (str | None) – Format of datetime_string. By default, several datetime formats commonly found in TIFF files are parsed.

Raises:

ValueErrordatetime_string does not match any known format.

Return type:

datetime

Examples

>>> strptime('2022:08:01 22:23:24')
datetime.datetime(2022, 8, 1, 22, 23, 24)
tifffile.transpose_axes(image, axes, /, asaxes=None)

Return image array with its axes permuted to match specified axes.

Parameters:
  • image (NDArray[Any]) – Image array to permute.

  • axes (str) – Character codes for dimensions in image array. Length must equal the number of dimensions in image.

  • asaxes (str | None) – Character codes for dimensions in output image array. The default is ‘CTZYX’.

Returns:

Transposed image array. A length-1 dimension is added for added dimensions. A view of the input array is returned if possible.

Return type:

NDArray[Any]

Examples

>>> import numpy
>>> transpose_axes(
...     numpy.zeros((2, 3, 4, 5)), 'TYXC', asaxes='CTZYX'
... ).shape
(5, 2, 1, 3, 4)
tifffile.update_kwargs(kwargs, /, **keyvalues)

Update dict with keys and values if keys do not already exist.

>>> kwargs = {'one': 1}
>>> update_kwargs(kwargs, one=None, two=2)
>>> kwargs
{'one': 1, 'two': 2}
Parameters:
  • kwargs (dict[str, Any])

  • keyvalues (Any)

Return type:

None

tifffile.validate_jhove(filename, /, jhove=None, ignore=None)

Validate TIFF file with jhove -m TIFF-hul.

JHOVE does not support the BigTIFF format, more than 50 IFDs, and many TIFF extensions.

Parameters:
  • filename (str) – Name of TIFF file to validate.

  • jhove (str | None) – Path of jhove app. The default is ‘jhove’.

  • ignore (Collection[str] | None) – Jhove error message to ignore.

Raises:

ValueError – Jhove printed error message and did not contain one of strings in ignore.

Return type:

None

References

tifffile.xml2dict(xml, /, *, sanitize=True, prefix=None, sep=',')

Return XML as dictionary.

Parameters:
  • xml (str) – XML data to convert.

  • sanitize (bool) – Remove prefix from from etree Element.

  • prefix (tuple[str, str] | None) – Prefixes for dictionary keys.

  • sep (str) – Sequence separator. Pass empty string to disable sequence parsing.

Return type:

dict[str, Any]

Examples

>>> xml2dict(
...     '<?xml version="1.0" ?><root attr="name"><key>1</key></root>'
... )
{'root': {'key': 1, 'attr': 'name'}}
>>> xml2dict('<level1><level2>3.5322,-3.14</level2></level1>')
{'level1': {'level2': (3.5322, -3.14)}}
class tifffile.CHUNKMODE(*values)

Bases: IntEnum

ZarrStore chunk modes.

Specifies how to chunk data in Zarr stores.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
STRILE = 0

Chunk is strip or tile.

PLANE = 1

Chunk is image plane.

PAGE = 2

Chunk is image in page.

FILE = 3

Chunk is image in file.

class tifffile.COMPRESSION(*values)

Bases: IntEnum

Values of Compression tag.

Compression scheme used on image data.

NONE = 1

No compression (default).

LZW = 5

Lempel-Ziv-Welch.

JPEG = 7

New style JPEG.

ADOBE_DEFLATE = 8

Deflate, aka ZLIB.

JPEGXR_NDPI = 22610

JPEG XR (Hammatsu NDPI).

PACKBITS = 32773

PackBits, aka Macintosh RLE.

APERIO_JP2000_YCBC = 33003

JPEG 2000 YCbCr (Leica Aperio).

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
JPEG_2000_LOSSY = 33004

Lossy JPEG 2000 (Bio-Formats).

APERIO_JP2000_RGB = 33005

JPEG 2000 RGB (Leica Aperio).

ALT_JPEG = 33007

JPEG (Bio-Formats).

JPEG2000 = 34712

JPEG 2000.

LERC = 34887

ESRI Limited Error Raster Compression.

LZMA = 34925

Lempel-Ziv-Markov chain Algorithm.

PNG = 34933

Portable Network Graphics (Zoomable Image File format).

JPEGXR = 34934

JPEG XR (Zoomable Image File format).

JETRAW = 48124

Jetraw by Dotphoton.

ZSTD = 50000

Zstandard.

WEBP = 50001

WebP.

JPEGXL = 50002

JPEG XL.

PIXTIFF = 50013

ZLIB (Atalasoft).

JPEGXL_DNG = 52546

JPEG XL (DNG).

__bool__()

True if self else False

Return type:

bool

class tifffile.DATATYPE(*values)

Bases: IntEnum

TIFF tag data types.

BYTE = 1

8-bit unsigned integer.

ASCII = 2

8-bit byte with last byte null, containing 7-bit ASCII code.

SHORT = 3

16-bit unsigned integer.

LONG = 4

32-bit unsigned integer.

RATIONAL = 5

Two 32-bit unsigned integers, numerator and denominator of fraction.

SBYTE = 6

8-bit signed integer.

UNDEFINED = 7

8-bit byte that may contain anything.

SSHORT = 8

16-bit signed integer.

SLONG = 9

32-bit signed integer.

SRATIONAL = 10

Two 32-bit signed integers, numerator and denominator of fraction.

FLOAT = 11

Single precision (4-byte) IEEE format.

DOUBLE = 12

Double precision (8-byte) IEEE format.

IFD = 13

Unsigned 4 byte IFD offset.

UNICODE = 14

UTF-16 (2-byte) unicode string.

COMPLEX = 15

Single precision (8-byte) complex number.

LONG8 = 16

Unsigned 8 byte integer (BigTIFF).

SLONG8 = 17

Signed 8 byte integer (BigTIFF).

IFD8 = 18

Unsigned 8 byte IFD offset (BigTIFF).

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
class tifffile.EXTRASAMPLE(*values)

Bases: IntEnum

Values of ExtraSamples tag.

Interpretation of extra components in a pixel.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
UNSPECIFIED = 0

Unspecified data.

ASSOCALPHA = 1

Associated alpha data with premultiplied color.

UNASSALPHA = 2

Unassociated alpha data.

class tifffile.FILETYPE(*values)

Bases: IntFlag

Values of NewSubfileType tag.

A general indication of the kind of the image.

__format__(format_spec, /)

Convert to a string according to format_spec.

__or__(other)

Return self|value.

__and__(other)

Return self&value.

__xor__(other)

Return self^value.

__ror__(other)

Return value|self.

__rand__(other)

Return value&self.

__rxor__(other)

Return value^self.

__invert__()

~self

__new__(value)
UNDEFINED = 0

Image is full-resolution (default).

REDUCEDIMAGE = 1

Image is reduced-resolution version of another image.

PAGE = 2

Image is single page of multi-page image.

MASK = 4

Image is transparency mask for another image.

MACRO = 8

Image is MACRO image (SVS) or depth map for another image (DNG).

ENHANCED = 16

Image contains enhanced image (DNG).

class tifffile.FILLORDER(*values)

Bases: IntEnum

Values of FillOrder tag.

The logical order of bits within a byte.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
MSB2LSB = 1

Pixel values are stored in higher-order bits of byte (default).

LSB2MSB = 2

Pixels values are stored in lower-order bits of byte.

class tifffile.OFILETYPE(*values)

Bases: IntEnum

Values of deprecated SubfileType tag.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
class tifffile.ORIENTATION(*values)

Bases: IntEnum

Values of Orientation tag.

The orientation of the image with respect to the rows and columns.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
class tifffile.PHOTOMETRIC(*values)

Bases: IntEnum

Values of PhotometricInterpretation tag.

The color space of the image.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
MINISWHITE = 0

For bilevel and grayscale images, 0 is imaged as white.

MINISBLACK = 1

For bilevel and grayscale images, 0 is imaged as black.

RGB = 2

Chroma components are Red, Green, Blue.

PALETTE = 3

Single chroma component is index into colormap.

SEPARATED = 5

Chroma components are Cyan, Magenta, Yellow, and Key (black).

YCBCR = 6

Chroma components are Luma, blue-difference, and red-difference.

CFA = 32803

Color Filter Array.

class tifffile.PLANARCONFIG(*values)

Bases: IntEnum

Values of PlanarConfiguration tag.

Specifies how components of each pixel are stored.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
CONTIG = 1

Chunky, component values are stored contiguously (default).

SEPARATE = 2

Planar, component values are stored in separate planes.

class tifffile.PREDICTOR(*values)

Bases: IntEnum

Values of Predictor tag.

A mathematical operator that is applied to the image data before compression.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
NONE = 1

No prediction scheme used (default).

HORIZONTAL = 2

Horizontal differencing.

FLOATINGPOINT = 3

Floating-point horizontal differencing.

__bool__()

True if self else False

Return type:

bool

class tifffile.RESUNIT(*values)

Bases: IntEnum

Values of ResolutionUnit tag.

The unit of measurement for XResolution and YResolution.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
NONE = 1

No absolute unit of measurement.

INCH = 2

Inch (default).

CENTIMETER = 3

Centimeter.

MILLIMETER = 4

Millimeter (DNG).

MICROMETER = 5

Micrometer (DNG).

__bool__()

True if self else False

Return type:

bool

class tifffile.SAMPLEFORMAT(*values)

Bases: IntEnum

Values of SampleFormat tag.

Data type of samples in a pixel.

__format__(format_spec, /)

Convert to a string according to format_spec.

__new__(value)
UINT = 1

Unsigned integer.

INT = 2

Signed integer.

IEEEFP = 3

IEEE floating-point

VOID = 4

Undefined.

COMPLEXINT = 5

Complex integer.

COMPLEXIEEEFP = 6

Complex floating-point.

tifffile.TIFF = <tifffile.tifffile._TIFF object>

Delay-loaded constants, accessible via TIFF instance.

tifffile.numcodecs

class tifffile.numcodecs.Tiff(key=None, series=None, kind=None, level=None, squeeze=None, buffersize=None, bigtiff=False, byteorder=None, photometric=None, planarconfig=None, extrasamples=None, volumetric=False, tile=None, rowsperstrip=None, bitspersample=None, compression=None, compressionargs=None, predictor=None, subsampling=None, metadata=METADATA_DEFAULT, extratags=None, truncate=False, maxworkers=None)

Bases: Codec

TIFF codec for Numcodecs.

Parameters:
  • key (int | slice | Sequence[int] | None)

  • series (int | None)

  • kind (Literal['generic', 'imagej', 'ome', 'shaped'] | None)

  • level (int | None)

  • squeeze (bool | None)

  • buffersize (int | None)

  • bigtiff (bool)

  • byteorder (ByteOrder | None)

  • photometric (PHOTOMETRIC | int | str | None)

  • planarconfig (PLANARCONFIG | int | str | None)

  • extrasamples (Sequence[EXTRASAMPLE | int | str] | None)

  • volumetric (bool)

  • tile (Sequence[int] | None)

  • rowsperstrip (int | None)

  • bitspersample (int | None)

  • compression (COMPRESSION | int | str | None)

  • compressionargs (dict[str, Any] | None)

  • predictor (PREDICTOR | int | str | bool | None)

  • subsampling (tuple[int, int] | None)

  • metadata (dict[str, Any] | None)

  • extratags (Sequence[TagTuple] | None)

  • truncate (bool)

  • maxworkers (int | None)

codec_id: str | None = 'tifffile'

Codec identifier.

__init__(key=None, series=None, kind=None, level=None, squeeze=None, buffersize=None, bigtiff=False, byteorder=None, photometric=None, planarconfig=None, extrasamples=None, volumetric=False, tile=None, rowsperstrip=None, bitspersample=None, compression=None, compressionargs=None, predictor=None, subsampling=None, metadata=METADATA_DEFAULT, extratags=None, truncate=False, maxworkers=None)
Parameters:
  • key (int | slice | Sequence[int] | None)

  • series (int | None)

  • kind (Literal['generic', 'imagej', 'ome', 'shaped'] | None)

  • level (int | None)

  • squeeze (bool | None)

  • buffersize (int | None)

  • bigtiff (bool)

  • byteorder (ByteOrder | None)

  • photometric (PHOTOMETRIC | int | str | None)

  • planarconfig (PLANARCONFIG | int | str | None)

  • extrasamples (Sequence[EXTRASAMPLE | int | str] | None)

  • volumetric (bool)

  • tile (Sequence[int] | None)

  • rowsperstrip (int | None)

  • bitspersample (int | None)

  • compression (COMPRESSION | int | str | None)

  • compressionargs (dict[str, Any] | None)

  • predictor (PREDICTOR | int | str | bool | None)

  • subsampling (tuple[int, int] | None)

  • metadata (dict[str, Any] | None)

  • extratags (Sequence[TagTuple] | None)

  • truncate (bool)

  • maxworkers (int | None)

Return type:

None

encode(buf)

Return TIFF file as bytes.

Parameters:

buf (Any)

Return type:

bytes

decode(buf, out=None)

Return decoded image as NumPy array.

Parameters:
  • buf (Any)

  • out (Any)

Return type:

Any

tifffile.numcodecs.register_codec(cls=Tiff, codec_id=None)

Register Tiff codec with Numcodecs.

Parameters:
  • cls (type[Codec])

  • codec_id (str | None)

Return type:

None

tifffile.zarr

class tifffile.zarr.Tiff(*, key=None, series=None, kind=None, level=None, squeeze=None, buffersize=None, bigtiff=False, byteorder=None, photometric=None, planarconfig=None, extrasamples=None, volumetric=False, tile=None, rowsperstrip=None, bitspersample=None, compression=None, compressionargs=None, predictor=None, subsampling=None, metadata=METADATA_DEFAULT, extratags=None, truncate=False, maxworkers=None)

Bases: ArrayBytesCodec

TIFF codec for Zarr 3.

Parameters:
  • key (int | slice | Sequence[int] | None)

  • series (int | None)

  • kind (Literal['generic', 'imagej', 'ome', 'shaped'] | None)

  • level (int | None)

  • squeeze (bool | None)

  • buffersize (int | None)

  • bigtiff (bool)

  • byteorder (ByteOrder | None)

  • photometric (PHOTOMETRIC | int | str | None)

  • planarconfig (PLANARCONFIG | int | str | None)

  • extrasamples (Sequence[EXTRASAMPLE | int | str] | None)

  • volumetric (bool)

  • tile (Sequence[int] | None)

  • rowsperstrip (int | None)

  • bitspersample (int | None)

  • compression (COMPRESSION | int | str | None)

  • compressionargs (dict[str, Any] | None)

  • predictor (PREDICTOR | int | str | bool | None)

  • subsampling (tuple[int, int] | None)

  • metadata (dict[str, Any] | None)

  • extratags (Sequence[TagTuple] | None)

  • truncate (bool)

  • maxworkers (int | None)

__init__(*, key=None, series=None, kind=None, level=None, squeeze=None, buffersize=None, bigtiff=False, byteorder=None, photometric=None, planarconfig=None, extrasamples=None, volumetric=False, tile=None, rowsperstrip=None, bitspersample=None, compression=None, compressionargs=None, predictor=None, subsampling=None, metadata=METADATA_DEFAULT, extratags=None, truncate=False, maxworkers=None)
Parameters:
  • key (int | slice | Sequence[int] | None)

  • series (int | None)

  • kind (Literal['generic', 'imagej', 'ome', 'shaped'] | None)

  • level (int | None)

  • squeeze (bool | None)

  • buffersize (int | None)

  • bigtiff (bool)

  • byteorder (ByteOrder | None)

  • photometric (PHOTOMETRIC | int | str | None)

  • planarconfig (PLANARCONFIG | int | str | None)

  • extrasamples (Sequence[EXTRASAMPLE | int | str] | None)

  • volumetric (bool)

  • tile (Sequence[int] | None)

  • rowsperstrip (int | None)

  • bitspersample (int | None)

  • compression (COMPRESSION | int | str | None)

  • compressionargs (dict[str, Any] | None)

  • predictor (PREDICTOR | int | str | bool | None)

  • subsampling (tuple[int, int] | None)

  • metadata (dict[str, Any] | None)

  • extratags (Sequence[TagTuple] | None)

  • truncate (bool)

  • maxworkers (int | None)

Return type:

None

classmethod from_dict(data)

Create instance of model from dictionary.

Parameters:

data (dict[str, JSON])

Return type:

Self

to_dict()

Convert instance of model to dictionary.

Return type:

dict[str, JSON]

compute_encoded_size(input_byte_length, chunk_spec)

Compute size of encoded chunk in bytes.

Parameters:
  • input_byte_length (int)

  • chunk_spec (ArraySpec)

Return type:

int

__delattr__(name)

Implement delattr(self, name).

__eq__(other)

Return self==value.

__hash__()

Return hash(self).

__repr__()

Return repr(self).

__setattr__(name, value)

Implement setattr(self, name, value).

class tifffile.zarr.ZarrFileSequenceStore(filesequence, /, *, fillvalue=None, chunkmode=None, chunkshape=None, chunkdtype=None, axestiled=None, dimension_names=None, zattrs=None, ioworkers=1, imreadargs=None, read_only=True, **kwargs)

Bases: ZarrStore

Zarr 3 store interface to image array in FileSequence.

The store uses Zarr v3 format.

Parameters:
  • filesequence (FileSequence) – FileSequence instance to wrap as Zarr store. Files in containers are not supported.

  • fillvalue (float | None) – Value to use for missing chunks. The default is 0.

  • chunkmode (CHUNKMODE | int | str | None) – Currently only one chunk per file is supported.

  • chunkshape (Sequence[int] | None) – Shape of chunk in each file. Must match FileSequence.imread(file, **imreadargs).shape.

  • chunkdtype (DTypeLike | None) – Data type of chunk in each file. Must match FileSequence.imread(file, **imreadargs).dtype.

  • axestiled (dict[int, int] | Sequence[tuple[int, int]] | None) – Axes to be tiled. Map stacked sequence axis to chunk axis.

  • dimension_names (Sequence[str] | None) – Names of dimensions in image array. If None and all chunk axes are tiled, derive from filesequence.dims. Otherwise not set in the store.

  • zattrs (dict[str, Any] | None) – Additional attributes to store in .zattrs.

  • ioworkers (int | None) – If not 1, asynchronously run imread function in separate thread. If enabled, internal threading for the imread function should be disabled.

  • read_only (bool) – Passed to zarr.abc.store.Store.

  • imreadargs (dict[str, Any] | None) – Arguments passed to FileSequence.imread.

  • **kwargs (Any) – Arguments passed to FileSequence.imread in addition to imreadargs.

Notes

If chunkshape or chunkdtype are None (default), their values are determined by reading the first file with FileSequence.imread(arg.files[0], **imreadargs).

__init__(filesequence, /, *, fillvalue=None, chunkmode=None, chunkshape=None, chunkdtype=None, axestiled=None, dimension_names=None, zattrs=None, ioworkers=1, imreadargs=None, read_only=True, **kwargs)
Parameters:
  • filesequence (FileSequence)

  • fillvalue (float | None)

  • chunkmode (CHUNKMODE | int | str | None)

  • chunkshape (Sequence[int] | None)

  • chunkdtype (DTypeLike | None)

  • axestiled (dict[int, int] | Sequence[tuple[int, int]] | None)

  • dimension_names (Sequence[str] | None)

  • zattrs (dict[str, Any] | None)

  • ioworkers (int | None)

  • imreadargs (dict[str, Any] | None)

  • read_only (bool)

  • kwargs (Any)

Return type:

None

async exists(key)

Return whether key exists in store.

Parameters:

key (str)

Return type:

bool

async get(key, prototype, byte_range=None)

Return value associated with key.

Parameters:
  • key (str)

  • prototype (BufferPrototype)

  • byte_range (ByteRequest | None)

Return type:

Buffer | None

write_fsspec(jsonfile, /, url, *, quote=None, groupname=None, templatename=None, codec_id=None, zarr_format=None, version=None, _append=False, _close=True)

Write fsspec ReferenceFileSystem as JSON to file.

Parameters:
  • jsonfile (str | os.PathLike[Any] | TextIO) – Name or open file handle of output JSON file.

  • url (str | None) – Remote location of TIFF file(s) without file name(s).

  • quote (bool | None) – Quote file names, that is, replace ‘ ‘ with ‘%20’. The default is True.

  • groupname (str | None) – Zarr group name.

  • templatename (str | None) – Version 1 URL template name. The default is ‘u’.

  • codec_id (str | None) – Name of Numcodecs (zarr format 2) or imagecodecs.zarr (zarr format 3) codec to decode files or chunks.

  • zarr_format (int | None) – Version of Zarr array format to write. The default is 2. If 3, write Zarr version 3 format using imagecodecs.zarr native codec specifications. Chunk keys use ‘c/’ prefix with ‘/’ separator and imagecodecs.zarr.register_codecs() must be called before reading the resulting store.

  • version (int | None) – Version of fsspec file to write. The default is 0.

  • _append (bool) – Experimental API.

  • _close (bool) – Experimental API.

Return type:

None

References

class tifffile.zarr.ZarrStore(*, fillvalue=None, chunkmode=None, read_only=True)

Bases: Store

Zarr 3 store base class.

Parameters:
  • fillvalue (float | None) – Value to use for missing chunks of Zarr store. The default is 0.

  • chunkmode (CHUNKMODE | int | str | None) – Specifies how to chunk data.

  • read_only (bool) – Passed to zarr.abc.store.Store.

References

  1. https://zarr.readthedocs.io/en/stable/api/zarr/abc/store/

  2. https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html

  3. https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html

  4. https://ngff.openmicroscopy.org/specifications/0.5/

__init__(*, fillvalue=None, chunkmode=None, read_only=True)
Parameters:
  • fillvalue (float | None)

  • chunkmode (CHUNKMODE | int | str | None)

  • read_only (bool)

Return type:

None

__hash__()

Return hash(self).

Return type:

int

__eq__(other)

Return whether objects are equal.

Parameters:

other (object)

Return type:

bool

async get_partial_values(prototype, key_ranges)

Return possibly partial values from given key_ranges.

Parameters:
  • prototype (BufferPrototype)

  • key_ranges (Iterable[tuple[str, ByteRequest | None]])

Return type:

list[Buffer | None]

property supports_writes: bool

Store supports writes.

async set(key, value)

Store (key, value) pair.

Parameters:
  • key (str)

  • value (Buffer)

Return type:

None

property supports_deletes: bool

Store supports deletes.

async delete(key)

Remove key from store.

Parameters:

key (str)

Return type:

None

property supports_listing: bool

Store supports listing.

async list()

Return all keys in store.

Return type:

AsyncIterator[str]

async list_prefix(prefix)

Return all keys in store that begin with prefix.

Keys are returned relative to the root of the store.

Parameters:

prefix (str)

Return type:

AsyncIterator[str]

async list_dir(prefix)

Return all keys and prefixes with prefix.

Keys and prefixes do not contain the character “/” after the given prefix.

Parameters:

prefix (str)

Return type:

AsyncIterator[str]

property is_multiscales: bool

Return whether ZarrStore contains multiscales.

__repr__()

Return repr(self).

Return type:

str

class tifffile.zarr.ZarrTiffStore(arg, /, *, level=None, chunkmode=None, fillvalue=None, dimension_names=None, zattrs=None, multiscales=None, lock=None, maxworkers=None, buffersize=None, read_only=None, _openfiles=None)

Bases: ZarrStore

Zarr 3 store interface to image array in TiffPage or TiffPageSeries.

The store uses Zarr v3 format. Pyramidal series use OME-Zarr v0.5 multiscales metadata.

ZarrTiffStore is using a TiffFile instance for reading and decoding chunks. Therefore, ZarrTiffStore instances cannot be pickled.

For writing, image data must be stored in uncompressed, unpredicted, and unpacked form. Sparse strips and tiles are not written.

Parameters:
  • arg (TiffPage | TiffFrame | TiffPageSeries) – TIFF page or series to wrap as Zarr store.

  • level (int | None) – Pyramidal level to wrap. The default is 0.

  • chunkmode (CHUNKMODE | int | str | None) – Use strips or tiles (0) or whole page data (2) as chunks. The default is 0.

  • fillvalue (float | None) – Value to use for missing chunks. The default is 0.

  • dimension_names (Sequence[str] | None) – Names of dimensions in image array. Overrides dimension names derived from series axes.

  • zattrs (dict[str, Any] | None) – Additional attributes to store in .zattrs.

  • multiscales (bool | None) – Create a multiscales-compatible Zarr group store. By default, create a Zarr array store for pages and non-pyramidal series. If True, encode coordinate metadata (pixel sizes, units, offsets) using the NGFF 0.5 multiscales structure.

  • lock (threading.RLock | NullContext | None) – Reentrant lock to synchronize seeks and reads from file. By default, the lock of the parent’s file handle is used.

  • maxworkers (int | None) – If chunkmode=0, asynchronously run chunk decode function in separate thread if greater than 1. If chunkmode=2, maximum number of threads to concurrently decode strips or tiles. If None or 0, use up to _TIFF.MAXWORKERS or asyncio assigned threads.

  • buffersize (int | None) – Approximate number of bytes to read from file in one pass if chunkmode=2. The default is _TIFF.BUFFERSIZE.

  • read_only (bool | None) – Passed to zarr.abc.store.Store.

  • _openfiles (int | None) – Internal API.

__init__(arg, /, *, level=None, chunkmode=None, fillvalue=None, dimension_names=None, zattrs=None, multiscales=None, lock=None, maxworkers=None, buffersize=None, read_only=None, _openfiles=None)
Parameters:
  • arg (TiffPage | TiffFrame | TiffPageSeries)

  • level (int | None)

  • chunkmode (CHUNKMODE | int | str | None)

  • fillvalue (float | None)

  • dimension_names (Sequence[str] | None)

  • zattrs (dict[str, Any] | None)

  • multiscales (bool | None)

  • lock (threading.RLock | NullContext | None)

  • maxworkers (int | None)

  • buffersize (int | None)

  • read_only (bool | None)

  • _openfiles (int | None)

Return type:

None

close()

Close store.

Return type:

None

write_fsspec(jsonfile, /, url, *, groupname=None, templatename=None, compressors=None, zarr_format=None, version=None, _shape=None, _axes=None, _index=None, _append=False, _close=True)

Write fsspec ReferenceFileSystem as JSON to file.

Parameters:
  • jsonfile (str | os.PathLike[Any] | TextIO) – Name or open file handle of output JSON file.

  • url (str | None) – Remote location of TIFF file(s) without file name(s).

  • groupname (str | None) – Zarr group name.

  • templatename (str | None) – Version 1 URL template name. The default is ‘u’.

  • compressors (dict[COMPRESSION | int, str | None] | None) – Mapping of COMPRESSION codes to Numcodecs codec names (zarr format 2) or imagecodecs.zarr codec names (zarr format 3).

  • zarr_format (int | None) – Version of Zarr array format to write. The default is 2. If 3, write Zarr version 3 format using imagecodecs.zarr native codec specifications. Chunk keys use ‘c/’ prefix with ‘/’ separator and imagecodecs.zarr.register_codecs() must be called before reading the resulting store.

  • version (int | None) – Version of fsspec file to write. The default is 0.

  • _shape (Sequence[int] | None) – Shape of file sequence (experimental).

  • _axes (Sequence[str] | None) – Axes of file sequence (experimental).

  • _index (Sequence[int] | None) – Index of file in sequence (experimental).

  • _append (bool) – If True, only write index keys and values (experimental).

  • _close (bool) – If True, no more appends (experimental).

Raises:

ValueError – ZarrTiffStore cannot be represented as ReferenceFileSystem due to features that are not supported by Zarr, Numcodecs, or Imagecodecs: - compressors, such as CCITT - filters, such as bitorder reversal, packed integers - dtypes, such as float24, complex integers - JPEGTables in multi-page series - incomplete chunks, such as imagelength % rowsperstrip != 0 Files containing incomplete tiles may fail at runtime.

Return type:

None

Notes

Parameters _shape, _axes, _index, _append, and _close are an experimental API for joining the ReferenceFileSystems of multiple files of a TiffSequence.

Multiscales metadata for pyramidal series uses OME-Zarr v0.5 when zarr_format=3 and OME-Zarr v0.4 when zarr_format=2.

References

async get(key, prototype, byte_range=None)

Return value associated with key.

Parameters:
  • key (str)

  • prototype (BufferPrototype)

  • byte_range (ByteRequest | None)

Return type:

Buffer | None

async exists(key)

Return whether key exists in store.

Parameters:

key (str)

Return type:

bool

async set(key, value)

Store (key, value) pair.

Parameters:
  • key (str)

  • value (Buffer)

Return type:

None

tifffile.zarr.register_codec()

Register zarr 3 tifffile codec.

Return type:

None