Read and write TIFF files for scientific and bioimaging applications with comprehensive format support
Essential functions for reading and writing TIFF files, providing both simple high-level interfaces and efficient access patterns for large scientific datasets. These functions form the foundation of tifffile's functionality and handle the most common use cases.
The primary function for reading TIFF files into NumPy arrays or Zarr stores, with extensive options for data selection, chunking, and format-specific handling.
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
):
"""
Read image from TIFF file(s) as NumPy array or Zarr store.
Parameters:
- files: str, PathLike, FileHandle, or sequence of files to read
- selection: slice, tuple, or array specifying data subset to read
- aszarr: bool, return ZarrStore instead of NumPy array
- key: int, slice, or sequence specifying pages/frames to read
- series: int, index of image series to read from multi-series files
- level: int, pyramid level to read from multi-resolution files
- squeeze: bool, remove singleton dimensions from output shape
- maxworkers: int, number of worker threads for parallel reading
- buffersize: int, buffer size for file I/O operations
- mode: str, file opening mode ('r', 'r+')
- name: str, name of file within container (for compound formats)
- offset: int, byte offset to start reading from file
- size: int, number of bytes to read from file
- pattern: str, glob pattern for file sequence reading
- axesorder: sequence of ints, reorder axes in output array
- categories: dict, category mappings for categorical data
- imread: callable, custom function for reading individual files
- imreadargs: dict, arguments passed to custom imread function
- sort: callable or bool, sorting function for file sequences
- container: str or PathLike, container file for compound formats
- chunkshape: tuple, shape of chunks for Zarr output
- chunkdtype: dtype, data type of chunks for Zarr output
- axestiled: dict or sequence, axes and tile sizes for tiled reading
- ioworkers: int, number of I/O worker threads
- chunkmode: CHUNKMODE enum, chunking strategy for large files
- fillvalue: numeric, fill value for missing data
- zattrs: dict, additional Zarr attributes
- multiscales: bool, create multiscale Zarr pyramid
- omexml: str, override OME-XML metadata
- out: array-like, pre-allocated output array
- out_inplace: bool, modify output array in place
Returns:
- NDArray or ZarrTiffStore or ZarrFileSequenceStore
"""# Basic file reading
image = tifffile.imread('image.tif')
# Read specific pages from multi-page file
pages = tifffile.imread('stack.tif', key=[0, 2, 4])
# Read with data selection (crop)
cropped = tifffile.imread('large.tif', selection=np.s_[100:200, 100:200])
# Read as Zarr store for large files
zarr_store = tifffile.imread('huge.tif', aszarr=True)
# Read file sequence as single array
sequence = tifffile.imread(['img001.tif', 'img002.tif', 'img003.tif'])
# Read with parallel processing
fast_read = tifffile.imread('big.tif', maxworkers=4)
# Read specific series from OME-TIFF
series_data = tifffile.imread('multi_series.ome.tif', series=1)
# Read pyramid level from multi-resolution file
thumbnail = tifffile.imread('pyramid.tif', level=2)Comprehensive function for writing NumPy arrays to TIFF files with extensive format options, compression support, and metadata handling.
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
):
"""
Write NumPy array to TIFF file.
Parameters:
- file: str, PathLike, or file handle for output TIFF file
- data: array-like, image data to write
- mode: str, file opening mode ('w', 'x', 'r+')
- bigtiff: bool, create BigTIFF format for files >4GB
- byteorder: str, byte order ('<', '>', '=', '|')
- imagej: bool, create ImageJ-compatible TIFF
- ome: bool, create OME-TIFF format
- shaped: bool, create shaped TIFF with custom dimensions
- append: bool, append to existing file
- shape: tuple, explicit shape for data
- dtype: dtype, data type for output
- photometric: PHOTOMETRIC enum or str, color interpretation
- planarconfig: PLANARCONFIG enum, sample organization
- extrasamples: sequence, interpretation of extra samples
- volumetric: bool, store as volumetric data
- tile: tuple, tile dimensions for tiled format
- rowsperstrip: int, rows per strip for stripped format
- bitspersample: int, bits per sample
- compression: COMPRESSION enum or str, compression algorithm
- compressionargs: dict, compression-specific parameters
- predictor: PREDICTOR enum or str, predictor scheme
- subsampling: tuple, chroma subsampling factors
- jpegtables: bytes, JPEG quantization/Huffman tables
- iccprofile: bytes, ICC color profile
- colormap: array-like, color palette for indexed images
- description: str, ImageDescription tag content
- datetime: datetime or str, creation timestamp
- resolution: tuple, X and Y resolution values
- resolutionunit: RESUNIT enum, resolution measurement unit
- subfiletype: FILETYPE flags, file type indicators
- software: str, software identifier
- metadata: dict, additional metadata
- extratags: sequence, custom TIFF tags
- contiguous: bool, write data contiguously
- truncate: bool, truncate file after writing
- align: int, byte alignment for data
- maxworkers: int, number of worker threads
- buffersize: int, I/O buffer size
- returnoffset: bool, return file offset and size
Returns:
- tuple of (offset, size) if returnoffset=True, else None
"""# Basic array writing
data = np.random.randint(0, 256, (100, 100), dtype=np.uint8)
tifffile.imwrite('output.tif', data)
# Write with LZW compression
tifffile.imwrite('compressed.tif', data, compression='lzw')
# Write RGB image with metadata
rgb_data = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
tifffile.imwrite(
'rgb.tif',
rgb_data,
photometric='rgb',
description='Test RGB image',
resolution=(300, 300),
resolutionunit='inch'
)
# Write ImageJ 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}
)
# Write OME-TIFF with metadata
tifffile.imwrite(
'ome.tif',
stack,
ome=True,
metadata={
'axes': 'TCYX',
'PhysicalSizeX': 0.1,
'PhysicalSizeY': 0.1,
'PhysicalSizeZ': 0.5
}
)
# Write tiled TIFF for large images
large_data = np.random.randint(0, 256, (2000, 2000), dtype=np.uint8)
tifffile.imwrite('tiled.tif', large_data, tile=(256, 256))
# Append to existing file
tifffile.imwrite('multi.tif', data, append=True)
# Write with custom tags
custom_tags = [(65000, 's', 1, 'Custom string tag', False)]
tifffile.imwrite('custom.tif', data, extratags=custom_tags)Efficient access to TIFF file data without loading entire contents into memory, particularly useful for large scientific datasets.
def memmap(
filename,
*,
shape=None,
dtype=None,
page=None,
series=0,
level=0,
mode='r+',
**kwargs
):
"""
Return memory-mapped NumPy array of image data in TIFF file.
Parameters:
- filename: str or PathLike, path to TIFF file
- mode: str, memory mapping mode ('r', 'r+', 'w+', 'c')
- **kwargs: additional arguments passed to imread()
Returns:
- np.memmap: Memory-mapped array providing direct file access
"""# Memory-map large file for reading
mmap_data = tifffile.memmap('large_file.tif')
print(f"Shape: {mmap_data.shape}, dtype: {mmap_data.dtype}")
# Access subset without loading full file
subset = mmap_data[1000:2000, 1000:2000]
# Memory-map for writing (modifies file directly)
mmap_write = tifffile.memmap('output.tif', mode='r+')
mmap_write[100:200, 100:200] = 255 # Modifies file directlyInteractive display utilities for TIFF files in web browsers and other viewers.
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
):
"""
Display TIFF file or image data in web browser or other viewer.
Parameters:
- data: str, PathLike, or array-like data to display
- **kwargs: additional arguments for display formatting
Returns:
- None (opens external viewer)
"""# Display TIFF file in browser
tifffile.imshow('image.tif')
# Display NumPy array
data = np.random.randint(0, 256, (100, 100), dtype=np.uint8)
tifffile.imshow(data)aszarr=True for extremely large files to avoid memory issuesmaxworkers for parallel processing of multi-page filesselection parameter to read only required data regionsmemmap() for repeated access to large filesbuffersize for I/O operationsout parameter to reuse pre-allocated arrayschunkmode settings for optimal memory usagesqueeze=False to preserve array dimensions when neededCommon exceptions and error conditions:
try:
image = tifffile.imread('corrupted.tif')
except tifffile.TiffFileError as e:
print(f"TIFF file error: {e}")
except IOError as e:
print(f"File access error: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-tifffile