Read and write TIFF files for scientific and bioimaging applications with comprehensive format support
npx @tessl/cli install tessl/pypi-tifffile@2025.8.0A comprehensive Python library for reading and writing TIFF (Tagged Image File Format) files, specifically designed for scientific and bioimaging applications. Tifffile enables storing NumPy arrays in TIFF files and reading image and metadata from various TIFF-like formats used in bioimaging including BigTIFF, OME-TIFF, GeoTIFF, Adobe DNG, ZIF, MetaMorph STK, Zeiss LSM, ImageJ hyperstack, and many others.
pip install tifffilepip install tifffile[all] for complete functionality including compression codecs, XML parsing, Zarr support, and plottingpip install tifffile[codecs] for imagecodecs compression supportpip install tifffile[zarr] for Zarr integrationimport tifffileCommon specific imports:
from tifffile import imread, imwrite, TiffFile, TiffWriterimport numpy as np
import tifffile
# Read a TIFF file as NumPy array
image = tifffile.imread('example.tif')
print(f"Image shape: {image.shape}, dtype: {image.dtype}")
# Write NumPy array to TIFF file
data = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
tifffile.imwrite('output.tif', data)
# Read with detailed file information
with tifffile.TiffFile('example.tif') as tif:
print(f"Number of pages: {len(tif.pages)}")
print(f"Image description: {tif.pages[0].description}")
image = tif.asarray()
# Write with compression and metadata
tifffile.imwrite(
'compressed.tif',
data,
compression='lzw',
description='Scientific image data',
photometric='rgb'
)
# Write ImageJ-compatible hyperstack
stack = np.random.randint(0, 256, (10, 5, 100, 100), dtype=np.uint8)
tifffile.imwrite(
'hyperstack.tif',
stack,
imagej=True,
metadata={'axes': 'TCYX', 'fps': 10.0}
)Tifffile follows a layered architecture designed for flexibility and performance:
imread(), imwrite() provide simple interfaces for common operationsTiffFile, TiffWriter offer detailed control over reading and writing operationsTiffPage, TiffPages represent individual image frames and collectionsTiffTag, TiffTags provide access to TIFF metadata and tag manipulationThis design enables tifffile to serve as both a simple image I/O library and a comprehensive toolkit for scientific image processing, supporting everything from basic file operations to complex multi-dimensional datasets with specialized metadata.
Essential functions for reading and writing TIFF files, including basic imread/imwrite operations, memory mapping for efficient large file access, and display utilities for interactive environments.
def imread(
files=None,
*,
selection=None,
aszarr=False,
key=None,
series=None,
level=None,
squeeze=None,
maxworkers=None,
buffersize=None,
mode=None,
name=None,
offset=None,
size=None,
pattern=None,
axesorder=None,
categories=None,
imread=None,
imreadargs=None,
sort=None,
container=None,
chunkshape=None,
chunkdtype=None,
axestiled=None,
ioworkers=1,
chunkmode=None,
fillvalue=None,
zattrs=None,
multiscales=None,
omexml=None,
out=None,
out_inplace=None,
**kwargs
): ...
def imwrite(
file,
data=None,
*,
mode=None,
bigtiff=None,
byteorder=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=None,
extratags=None,
contiguous=False,
truncate=False,
align=None,
maxworkers=None,
buffersize=None,
returnoffset=False
): ...
def memmap(
filename,
*,
shape=None,
dtype=None,
page=None,
series=0,
level=0,
mode='r+',
**kwargs
): ...
def 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,
**kwargs
): ...Object-oriented interfaces for detailed TIFF file manipulation, including TiffFile for reading with extensive metadata access, TiffWriter for controlled writing operations, and page-level classes for granular file structure access.
class TiffFile:
def __init__(self, file, *, mode='r', name=None, offset=None, size=None, **kwargs): ...
def asarray(self, key=None, series=None, level=None, **kwargs): ...
def aszarr(self, **kwargs): ...
def close(self): ...
class TiffWriter:
def __init__(self, file, *, mode='w', bigtiff=None, byteorder=None, **kwargs): ...
def write(self, data, **kwargs): ...
def close(self): ...
class TiffPage:
def asarray(self, **kwargs): ...
def aszarr(self, **kwargs): ...
class TiffPages:
def __init__(self, pages): ...
def __getitem__(self, key): ...
def __len__(self): ...
class TiffPageSeries:
def __init__(self, pages, **kwargs): ...
def asarray(self, **kwargs): ...
def aszarr(self, **kwargs): ...
class TiffSequence:
def __init__(self, files, **kwargs): ...
def asarray(self, **kwargs): ...
def close(self): ...Comprehensive TIFF tag system for reading and manipulating image metadata, including specialized parsers for scientific imaging formats and support for custom tag definitions.
class TiffTag:
def overwrite(self, value): ...
class TiffTags:
def get(self, key, default=None): ...
class TiffTagRegistry:
def add(self, code, name, **kwargs): ...
def read_micromanager_metadata(filename): ...
def read_scanimage_metadata(filename): ...
def tiffcomment(filename, comment=None): ...TIFF format constants, compression schemes, photometric interpretations, and other standardized values required for proper TIFF file creation and interpretation.
class COMPRESSION(IntEnum):
NONE = 1
LZW = 5
JPEG = 7
DEFLATE = 32946
...
class PHOTOMETRIC(IntEnum):
MINISWHITE = 0
MINISBLACK = 1
RGB = 2
PALETTE = 3
...
class PREDICTOR(IntEnum):
NONE = 1
HORIZONTAL = 2
FLOATINGPOINT = 3Zarr store implementations for cloud-native access to TIFF files and file sequences, enabling scalable processing of large scientific datasets without loading entire files into memory. These classes are available in the tifffile.zarr module.
# Import from tifffile.zarr module
from tifffile.zarr import ZarrTiffStore, ZarrFileSequenceStore, ZarrStore
class ZarrStore:
def __init__(self, fillvalue=0, chunkmode=None, read_only=False, **kwargs): ...
class ZarrTiffStore(ZarrStore):
def __init__(self, tifffile, **kwargs): ...
class ZarrFileSequenceStore(ZarrStore):
def __init__(self, files, **kwargs): ...Helper functions for file operations, data conversion, string processing, array manipulation, and scientific image format utilities that support the core TIFF functionality.
def format_size(size): ...
def hexdump(data, width=16): ...
def natural_sorted(iterable): ...
def xml2dict(xml_string): ...
def parse_filenames(pattern): ...
def transpose_axes(axes, source, target): ...
def read_ndtiff_index(filename): ...
def read_gdal_structural_metadata(filename): ...
def validate_jhove(filename, jhove=None): ...
def astype(data, dtype, **kwargs): ...
def enumarg(arg, enum): ...
def enumstr(arg, enum): ...Command-line interfaces for TIFF file inspection, metadata manipulation, format conversion, and fsspec integration for cloud-native workflows.
def main(): ...
def tiffcomment(filename, comment=None): ...
def lsm2bin(filename, output=None): ...
def tiff2fsspec(filename, url, out=None, key=None, series=None, level=None, chunkmode=None, version=None): ...Tifffile defines specific exceptions for different error conditions:
class TiffFileError(Exception):
"""Base exception for TIFF file related errors."""
class OmeXmlError(Exception):
"""Exception raised when parsing OME-XML metadata fails."""Common error scenarios:
# Version information
__version__: str # Library version string (e.g., '2025.8.28')
# Type aliases for common parameter types
ArrayLike = Union[np.ndarray, Sequence, Any]
DTypeLike = Union[np.dtype, str, type]
ByteOrder = Literal['<', '>', '=', '|']
OutputType = Union[np.ndarray, None]
# File handle types
FileHandle = Union[str, os.PathLike, IO[bytes]]
# Date/time types
DateTime = Union[datetime.datetime, str]
# Tag tuple format for custom tags
TagTuple = Tuple[int, Union[int, str], Any, Union[int, str], bool]