tifffile
| Language | Python 3.12+ |
|---|---|
| License | BSD 3-Clause |
| Repository | github.com/cgohlke/tifffile |
| Documentation | PyPI page with examples |
| Depends on | NumPy; imagecodecs for compressed files |
| Read / write | yes / yes, multi-page, BigTIFF, tiles, any bit depth and sample format, OME-TIFF, ImageJ hyperstacks, many compressions |
tifffile reads TIFF files into NumPy arrays and writes NumPy arrays as TIFF. It’s the standard library for scientific TIFF: microscopy (OME-TIFF, ImageJ, LSM, NDPI, SVS), medical and remote sensing data. It handles 8 to 64-bit integers, floats and complex numbers, any number of channels, multi-dimensional series and files larger than memory (memory mapping and Zarr access). scikit-image, napari, AICSImageIO and many others use it.
It doesn’t resize, convert colors or draw: it moves arrays in and out of files. Install imagecodecs (pip install tifffile[all]) to read and write LZW, Deflate, ZSTD, JPEG and other compressed files.
Installation#
Shell
pip install -U "tifffile[all]"
Basic usage: read and write an image#
Python
import numpy as np
import tifffile
data = tifffile.imread("in.tif") # NumPy array of the first series
print(data.shape, data.dtype)
rgb = np.random.randint(0, 255, (256, 256, 3), "uint8")
tifffile.imwrite("out.tif", rgb, photometric="rgb")
How to write a compressed TIFF#
Python
import numpy as np
import tifffile
data = np.random.rand(512, 512).astype("float32")
tifffile.imwrite(
"float.tif",
data,
compression="zlib", # Deflate; also "lzw", "zstd", "jpeg", "packbits"
compressionargs={"level": 6},
predictor=True,
)
How to read pages and tags#
Python
import tifffile
with tifffile.TiffFile("in.tif") as tif:
print(len(tif.pages), "pages, BigTIFF:", tif.is_bigtiff)
page = tif.pages[0]
print(page.shape, page.dtype, page.compression)
for tag in page.tags:
print(tag.code, tag.name, tag.value)
image = page.asarray()
Read one page directly with tifffile.imread("in.tif", key=2).
How to write a multi-page TIFF#
Write each page with a TiffWriter:
Python
import numpy as np
import tifffile
with tifffile.TiffWriter("pages.tif") as tif:
for i in range(3):
page = np.full((480, 640), i * 100, "uint8")
tif.write(page, compression="zlib")
How to write a tiled BigTIFF#
Python
import numpy as np
import tifffile
data = np.zeros((20000, 20000), "uint16")
tifffile.imwrite("big.tif", data, bigtiff=True, tile=(512, 512), compression="zstd")
How to read part of a large TIFF without loading it all#
Python
import tifffile
import zarr
store = tifffile.imread("big.tif", return_as="zarr")
z = zarr.open(store, mode="r")
region = z[1000:2000, 1000:2000] # reads only the tiles needed
store.close()
Tips#
tifffile.imwrite(path, data, kind="imagej", metadata={"axes": "TZCYX"})writes a hyperstack ImageJ and Fiji open with correct dimensions.- Write OME-TIFF with
kind="ome"(or a file name ending in.ome.tif) andmetadata={"axes": ...}. - The
tifffilecommand line (python -m tifffile file.tif) prints all pages and tags.