0
# Tifffile
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: tifffile
7
- **Language**: Python
8
- **Installation**: `pip install tifffile`
9
- **Optional Dependencies**:
10
- `pip install tifffile[all]` for complete functionality including compression codecs, XML parsing, Zarr support, and plotting
11
- `pip install tifffile[codecs]` for imagecodecs compression support
12
- `pip install tifffile[zarr]` for Zarr integration
13
14
## Core Imports
15
16
```python
17
import tifffile
18
```
19
20
Common specific imports:
21
22
```python
23
from tifffile import imread, imwrite, TiffFile, TiffWriter
24
```
25
26
## Basic Usage
27
28
```python
29
import numpy as np
30
import tifffile
31
32
# Read a TIFF file as NumPy array
33
image = tifffile.imread('example.tif')
34
print(f"Image shape: {image.shape}, dtype: {image.dtype}")
35
36
# Write NumPy array to TIFF file
37
data = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
38
tifffile.imwrite('output.tif', data)
39
40
# Read with detailed file information
41
with tifffile.TiffFile('example.tif') as tif:
42
print(f"Number of pages: {len(tif.pages)}")
43
print(f"Image description: {tif.pages[0].description}")
44
image = tif.asarray()
45
46
# Write with compression and metadata
47
tifffile.imwrite(
48
'compressed.tif',
49
data,
50
compression='lzw',
51
description='Scientific image data',
52
photometric='rgb'
53
)
54
55
# Write ImageJ-compatible hyperstack
56
stack = np.random.randint(0, 256, (10, 5, 100, 100), dtype=np.uint8)
57
tifffile.imwrite(
58
'hyperstack.tif',
59
stack,
60
imagej=True,
61
metadata={'axes': 'TCYX', 'fps': 10.0}
62
)
63
```
64
65
## Architecture
66
67
Tifffile follows a layered architecture designed for flexibility and performance:
68
69
- **High-level Functions**: `imread()`, `imwrite()` provide simple interfaces for common operations
70
- **File Classes**: `TiffFile`, `TiffWriter` offer detailed control over reading and writing operations
71
- **Page Classes**: `TiffPage`, `TiffPages` represent individual image frames and collections
72
- **Tag System**: `TiffTag`, `TiffTags` provide access to TIFF metadata and tag manipulation
73
- **Codec Support**: Built-in and imagecodecs-based compression/decompression for various formats
74
- **Format Support**: Specialized handling for scientific formats (OME-TIFF, ImageJ, LSM, etc.)
75
- **Memory Mapping**: Efficient access to large files without loading entire contents into memory
76
- **Zarr Integration**: Cloud-native access patterns for scalable image processing workflows
77
78
This 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.
79
80
## Capabilities
81
82
### Core I/O Operations
83
84
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.
85
86
```python { .api }
87
def imread(
88
files=None,
89
*,
90
selection=None,
91
aszarr=False,
92
key=None,
93
series=None,
94
level=None,
95
squeeze=None,
96
maxworkers=None,
97
buffersize=None,
98
mode=None,
99
name=None,
100
offset=None,
101
size=None,
102
pattern=None,
103
axesorder=None,
104
categories=None,
105
imread=None,
106
imreadargs=None,
107
sort=None,
108
container=None,
109
chunkshape=None,
110
chunkdtype=None,
111
axestiled=None,
112
ioworkers=1,
113
chunkmode=None,
114
fillvalue=None,
115
zattrs=None,
116
multiscales=None,
117
omexml=None,
118
out=None,
119
out_inplace=None,
120
**kwargs
121
): ...
122
123
def imwrite(
124
file,
125
data=None,
126
*,
127
mode=None,
128
bigtiff=None,
129
byteorder=None,
130
imagej=False,
131
ome=None,
132
shaped=None,
133
append=False,
134
shape=None,
135
dtype=None,
136
photometric=None,
137
planarconfig=None,
138
extrasamples=None,
139
volumetric=False,
140
tile=None,
141
rowsperstrip=None,
142
bitspersample=None,
143
compression=None,
144
compressionargs=None,
145
predictor=None,
146
subsampling=None,
147
jpegtables=None,
148
iccprofile=None,
149
colormap=None,
150
description=None,
151
datetime=None,
152
resolution=None,
153
resolutionunit=None,
154
subfiletype=None,
155
software=None,
156
metadata=None,
157
extratags=None,
158
contiguous=False,
159
truncate=False,
160
align=None,
161
maxworkers=None,
162
buffersize=None,
163
returnoffset=False
164
): ...
165
166
def memmap(
167
filename,
168
*,
169
shape=None,
170
dtype=None,
171
page=None,
172
series=0,
173
level=0,
174
mode='r+',
175
**kwargs
176
): ...
177
178
def imshow(
179
data,
180
*,
181
photometric=None,
182
planarconfig=None,
183
bitspersample=None,
184
nodata=0,
185
interpolation=None,
186
cmap=None,
187
vmin=None,
188
vmax=None,
189
figure=None,
190
subplot=None,
191
title=None,
192
window_title=None,
193
**kwargs
194
): ...
195
```
196
197
[Core I/O Operations](./core-io.md)
198
199
### TIFF File Classes
200
201
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.
202
203
```python { .api }
204
class TiffFile:
205
def __init__(self, file, *, mode='r', name=None, offset=None, size=None, **kwargs): ...
206
def asarray(self, key=None, series=None, level=None, **kwargs): ...
207
def aszarr(self, **kwargs): ...
208
def close(self): ...
209
210
class TiffWriter:
211
def __init__(self, file, *, mode='w', bigtiff=None, byteorder=None, **kwargs): ...
212
def write(self, data, **kwargs): ...
213
def close(self): ...
214
215
class TiffPage:
216
def asarray(self, **kwargs): ...
217
def aszarr(self, **kwargs): ...
218
219
class TiffPages:
220
def __init__(self, pages): ...
221
def __getitem__(self, key): ...
222
def __len__(self): ...
223
224
class TiffPageSeries:
225
def __init__(self, pages, **kwargs): ...
226
def asarray(self, **kwargs): ...
227
def aszarr(self, **kwargs): ...
228
229
class TiffSequence:
230
def __init__(self, files, **kwargs): ...
231
def asarray(self, **kwargs): ...
232
def close(self): ...
233
```
234
235
[TIFF File Classes](./file-classes.md)
236
237
### Metadata and Tags
238
239
Comprehensive TIFF tag system for reading and manipulating image metadata, including specialized parsers for scientific imaging formats and support for custom tag definitions.
240
241
```python { .api }
242
class TiffTag:
243
def overwrite(self, value): ...
244
245
class TiffTags:
246
def get(self, key, default=None): ...
247
248
class TiffTagRegistry:
249
def add(self, code, name, **kwargs): ...
250
251
def read_micromanager_metadata(filename): ...
252
def read_scanimage_metadata(filename): ...
253
def tiffcomment(filename, comment=None): ...
254
```
255
256
[Metadata and Tags](./metadata-tags.md)
257
258
### Constants and Enums
259
260
TIFF format constants, compression schemes, photometric interpretations, and other standardized values required for proper TIFF file creation and interpretation.
261
262
```python { .api }
263
class COMPRESSION(IntEnum):
264
NONE = 1
265
LZW = 5
266
JPEG = 7
267
DEFLATE = 32946
268
...
269
270
class PHOTOMETRIC(IntEnum):
271
MINISWHITE = 0
272
MINISBLACK = 1
273
RGB = 2
274
PALETTE = 3
275
...
276
277
class PREDICTOR(IntEnum):
278
NONE = 1
279
HORIZONTAL = 2
280
FLOATINGPOINT = 3
281
```
282
283
[Constants and Enums](./constants-enums.md)
284
285
### Zarr Integration
286
287
Zarr 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.
288
289
```python { .api }
290
# Import from tifffile.zarr module
291
from tifffile.zarr import ZarrTiffStore, ZarrFileSequenceStore, ZarrStore
292
293
class ZarrStore:
294
def __init__(self, fillvalue=0, chunkmode=None, read_only=False, **kwargs): ...
295
296
class ZarrTiffStore(ZarrStore):
297
def __init__(self, tifffile, **kwargs): ...
298
299
class ZarrFileSequenceStore(ZarrStore):
300
def __init__(self, files, **kwargs): ...
301
```
302
303
[Zarr Integration](./zarr-integration.md)
304
305
### Utility Functions
306
307
Helper functions for file operations, data conversion, string processing, array manipulation, and scientific image format utilities that support the core TIFF functionality.
308
309
```python { .api }
310
def format_size(size): ...
311
def hexdump(data, width=16): ...
312
def natural_sorted(iterable): ...
313
def xml2dict(xml_string): ...
314
def parse_filenames(pattern): ...
315
def transpose_axes(axes, source, target): ...
316
def read_ndtiff_index(filename): ...
317
def read_gdal_structural_metadata(filename): ...
318
def validate_jhove(filename, jhove=None): ...
319
def astype(data, dtype, **kwargs): ...
320
def enumarg(arg, enum): ...
321
def enumstr(arg, enum): ...
322
```
323
324
[Utility Functions](./utilities.md)
325
326
### Command-line Tools
327
328
Command-line interfaces for TIFF file inspection, metadata manipulation, format conversion, and fsspec integration for cloud-native workflows.
329
330
```python { .api }
331
def main(): ...
332
def tiffcomment(filename, comment=None): ...
333
def lsm2bin(filename, output=None): ...
334
def tiff2fsspec(filename, url, out=None, key=None, series=None, level=None, chunkmode=None, version=None): ...
335
```
336
337
[Command-line Tools](./cli-tools.md)
338
339
## Error Handling
340
341
Tifffile defines specific exceptions for different error conditions:
342
343
```python { .api }
344
class TiffFileError(Exception):
345
"""Base exception for TIFF file related errors."""
346
347
class OmeXmlError(Exception):
348
"""Exception raised when parsing OME-XML metadata fails."""
349
```
350
351
Common error scenarios:
352
- **TiffFileError**: Raised for corrupted files, unsupported formats, or invalid parameters
353
- **OmeXmlError**: Raised when OME-XML metadata cannot be parsed or is malformed
354
- **ValueError**: Raised for invalid compression parameters or incompatible data types
355
- **IOError**: Raised for file access issues or insufficient disk space during writing
356
357
## Types
358
359
```python { .api }
360
# Version information
361
__version__: str # Library version string (e.g., '2025.8.28')
362
363
# Type aliases for common parameter types
364
ArrayLike = Union[np.ndarray, Sequence, Any]
365
DTypeLike = Union[np.dtype, str, type]
366
ByteOrder = Literal['<', '>', '=', '|']
367
OutputType = Union[np.ndarray, None]
368
369
# File handle types
370
FileHandle = Union[str, os.PathLike, IO[bytes]]
371
372
# Date/time types
373
DateTime = Union[datetime.datetime, str]
374
375
# Tag tuple format for custom tags
376
TagTuple = Tuple[int, Union[int, str], Any, Union[int, str], bool]
377
```