or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-tools.mdconstants-enums.mdcore-io.mdfile-classes.mdindex.mdmetadata-tags.mdutilities.mdzarr-integration.md

core-io.mddocs/

0

# Core I/O Operations

1

2

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.

3

4

## Capabilities

5

6

### Reading TIFF Files

7

8

The primary function for reading TIFF files into NumPy arrays or Zarr stores, with extensive options for data selection, chunking, and format-specific handling.

9

10

```python { .api }

11

def imread(

12

files=None,

13

*,

14

selection=None,

15

aszarr=False,

16

key=None,

17

series=None,

18

level=None,

19

squeeze=None,

20

maxworkers=None,

21

buffersize=None,

22

mode=None,

23

name=None,

24

offset=None,

25

size=None,

26

pattern=None,

27

axesorder=None,

28

categories=None,

29

imread=None,

30

imreadargs=None,

31

sort=None,

32

container=None,

33

chunkshape=None,

34

chunkdtype=None,

35

axestiled=None,

36

ioworkers=1,

37

chunkmode=None,

38

fillvalue=None,

39

zattrs=None,

40

multiscales=None,

41

omexml=None,

42

out=None,

43

out_inplace=None,

44

**kwargs

45

):

46

"""

47

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

48

49

Parameters:

50

- files: str, PathLike, FileHandle, or sequence of files to read

51

- selection: slice, tuple, or array specifying data subset to read

52

- aszarr: bool, return ZarrStore instead of NumPy array

53

- key: int, slice, or sequence specifying pages/frames to read

54

- series: int, index of image series to read from multi-series files

55

- level: int, pyramid level to read from multi-resolution files

56

- squeeze: bool, remove singleton dimensions from output shape

57

- maxworkers: int, number of worker threads for parallel reading

58

- buffersize: int, buffer size for file I/O operations

59

- mode: str, file opening mode ('r', 'r+')

60

- name: str, name of file within container (for compound formats)

61

- offset: int, byte offset to start reading from file

62

- size: int, number of bytes to read from file

63

- pattern: str, glob pattern for file sequence reading

64

- axesorder: sequence of ints, reorder axes in output array

65

- categories: dict, category mappings for categorical data

66

- imread: callable, custom function for reading individual files

67

- imreadargs: dict, arguments passed to custom imread function

68

- sort: callable or bool, sorting function for file sequences

69

- container: str or PathLike, container file for compound formats

70

- chunkshape: tuple, shape of chunks for Zarr output

71

- chunkdtype: dtype, data type of chunks for Zarr output

72

- axestiled: dict or sequence, axes and tile sizes for tiled reading

73

- ioworkers: int, number of I/O worker threads

74

- chunkmode: CHUNKMODE enum, chunking strategy for large files

75

- fillvalue: numeric, fill value for missing data

76

- zattrs: dict, additional Zarr attributes

77

- multiscales: bool, create multiscale Zarr pyramid

78

- omexml: str, override OME-XML metadata

79

- out: array-like, pre-allocated output array

80

- out_inplace: bool, modify output array in place

81

82

Returns:

83

- NDArray or ZarrTiffStore or ZarrFileSequenceStore

84

"""

85

```

86

87

#### Usage Examples

88

89

```python

90

# Basic file reading

91

image = tifffile.imread('image.tif')

92

93

# Read specific pages from multi-page file

94

pages = tifffile.imread('stack.tif', key=[0, 2, 4])

95

96

# Read with data selection (crop)

97

cropped = tifffile.imread('large.tif', selection=np.s_[100:200, 100:200])

98

99

# Read as Zarr store for large files

100

zarr_store = tifffile.imread('huge.tif', aszarr=True)

101

102

# Read file sequence as single array

103

sequence = tifffile.imread(['img001.tif', 'img002.tif', 'img003.tif'])

104

105

# Read with parallel processing

106

fast_read = tifffile.imread('big.tif', maxworkers=4)

107

108

# Read specific series from OME-TIFF

109

series_data = tifffile.imread('multi_series.ome.tif', series=1)

110

111

# Read pyramid level from multi-resolution file

112

thumbnail = tifffile.imread('pyramid.tif', level=2)

113

```

114

115

### Writing TIFF Files

116

117

Comprehensive function for writing NumPy arrays to TIFF files with extensive format options, compression support, and metadata handling.

118

119

```python { .api }

120

def imwrite(

121

file,

122

data=None,

123

*,

124

mode=None,

125

bigtiff=None,

126

byteorder=None,

127

imagej=False,

128

ome=None,

129

shaped=None,

130

append=False,

131

shape=None,

132

dtype=None,

133

photometric=None,

134

planarconfig=None,

135

extrasamples=None,

136

volumetric=False,

137

tile=None,

138

rowsperstrip=None,

139

bitspersample=None,

140

compression=None,

141

compressionargs=None,

142

predictor=None,

143

subsampling=None,

144

jpegtables=None,

145

iccprofile=None,

146

colormap=None,

147

description=None,

148

datetime=None,

149

resolution=None,

150

resolutionunit=None,

151

subfiletype=None,

152

software=None,

153

metadata=None,

154

extratags=None,

155

contiguous=False,

156

truncate=False,

157

align=None,

158

maxworkers=None,

159

buffersize=None,

160

returnoffset=False

161

):

162

"""

163

Write NumPy array to TIFF file.

164

165

Parameters:

166

- file: str, PathLike, or file handle for output TIFF file

167

- data: array-like, image data to write

168

- mode: str, file opening mode ('w', 'x', 'r+')

169

- bigtiff: bool, create BigTIFF format for files >4GB

170

- byteorder: str, byte order ('<', '>', '=', '|')

171

- imagej: bool, create ImageJ-compatible TIFF

172

- ome: bool, create OME-TIFF format

173

- shaped: bool, create shaped TIFF with custom dimensions

174

- append: bool, append to existing file

175

- shape: tuple, explicit shape for data

176

- dtype: dtype, data type for output

177

- photometric: PHOTOMETRIC enum or str, color interpretation

178

- planarconfig: PLANARCONFIG enum, sample organization

179

- extrasamples: sequence, interpretation of extra samples

180

- volumetric: bool, store as volumetric data

181

- tile: tuple, tile dimensions for tiled format

182

- rowsperstrip: int, rows per strip for stripped format

183

- bitspersample: int, bits per sample

184

- compression: COMPRESSION enum or str, compression algorithm

185

- compressionargs: dict, compression-specific parameters

186

- predictor: PREDICTOR enum or str, predictor scheme

187

- subsampling: tuple, chroma subsampling factors

188

- jpegtables: bytes, JPEG quantization/Huffman tables

189

- iccprofile: bytes, ICC color profile

190

- colormap: array-like, color palette for indexed images

191

- description: str, ImageDescription tag content

192

- datetime: datetime or str, creation timestamp

193

- resolution: tuple, X and Y resolution values

194

- resolutionunit: RESUNIT enum, resolution measurement unit

195

- subfiletype: FILETYPE flags, file type indicators

196

- software: str, software identifier

197

- metadata: dict, additional metadata

198

- extratags: sequence, custom TIFF tags

199

- contiguous: bool, write data contiguously

200

- truncate: bool, truncate file after writing

201

- align: int, byte alignment for data

202

- maxworkers: int, number of worker threads

203

- buffersize: int, I/O buffer size

204

- returnoffset: bool, return file offset and size

205

206

Returns:

207

- tuple of (offset, size) if returnoffset=True, else None

208

"""

209

```

210

211

#### Usage Examples

212

213

```python

214

# Basic array writing

215

data = np.random.randint(0, 256, (100, 100), dtype=np.uint8)

216

tifffile.imwrite('output.tif', data)

217

218

# Write with LZW compression

219

tifffile.imwrite('compressed.tif', data, compression='lzw')

220

221

# Write RGB image with metadata

222

rgb_data = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)

223

tifffile.imwrite(

224

'rgb.tif',

225

rgb_data,

226

photometric='rgb',

227

description='Test RGB image',

228

resolution=(300, 300),

229

resolutionunit='inch'

230

)

231

232

# Write ImageJ hyperstack

233

stack = np.random.randint(0, 256, (10, 5, 100, 100), dtype=np.uint8)

234

tifffile.imwrite(

235

'hyperstack.tif',

236

stack,

237

imagej=True,

238

metadata={'axes': 'TCYX', 'fps': 10.0}

239

)

240

241

# Write OME-TIFF with metadata

242

tifffile.imwrite(

243

'ome.tif',

244

stack,

245

ome=True,

246

metadata={

247

'axes': 'TCYX',

248

'PhysicalSizeX': 0.1,

249

'PhysicalSizeY': 0.1,

250

'PhysicalSizeZ': 0.5

251

}

252

)

253

254

# Write tiled TIFF for large images

255

large_data = np.random.randint(0, 256, (2000, 2000), dtype=np.uint8)

256

tifffile.imwrite('tiled.tif', large_data, tile=(256, 256))

257

258

# Append to existing file

259

tifffile.imwrite('multi.tif', data, append=True)

260

261

# Write with custom tags

262

custom_tags = [(65000, 's', 1, 'Custom string tag', False)]

263

tifffile.imwrite('custom.tif', data, extratags=custom_tags)

264

```

265

266

### Memory Mapping

267

268

Efficient access to TIFF file data without loading entire contents into memory, particularly useful for large scientific datasets.

269

270

```python { .api }

271

def memmap(

272

filename,

273

*,

274

shape=None,

275

dtype=None,

276

page=None,

277

series=0,

278

level=0,

279

mode='r+',

280

**kwargs

281

):

282

"""

283

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

284

285

Parameters:

286

- filename: str or PathLike, path to TIFF file

287

- mode: str, memory mapping mode ('r', 'r+', 'w+', 'c')

288

- **kwargs: additional arguments passed to imread()

289

290

Returns:

291

- np.memmap: Memory-mapped array providing direct file access

292

"""

293

```

294

295

#### Usage Examples

296

297

```python

298

# Memory-map large file for reading

299

mmap_data = tifffile.memmap('large_file.tif')

300

print(f"Shape: {mmap_data.shape}, dtype: {mmap_data.dtype}")

301

302

# Access subset without loading full file

303

subset = mmap_data[1000:2000, 1000:2000]

304

305

# Memory-map for writing (modifies file directly)

306

mmap_write = tifffile.memmap('output.tif', mode='r+')

307

mmap_write[100:200, 100:200] = 255 # Modifies file directly

308

```

309

310

### Display Functions

311

312

Interactive display utilities for TIFF files in web browsers and other viewers.

313

314

```python { .api }

315

def imshow(

316

data,

317

*,

318

photometric=None,

319

planarconfig=None,

320

bitspersample=None,

321

nodata=0,

322

interpolation=None,

323

cmap=None,

324

vmin=None,

325

vmax=None,

326

figure=None,

327

subplot=None,

328

title=None,

329

window_title=None,

330

**kwargs

331

):

332

"""

333

Display TIFF file or image data in web browser or other viewer.

334

335

Parameters:

336

- data: str, PathLike, or array-like data to display

337

- **kwargs: additional arguments for display formatting

338

339

Returns:

340

- None (opens external viewer)

341

"""

342

```

343

344

#### Usage Examples

345

346

```python

347

# Display TIFF file in browser

348

tifffile.imshow('image.tif')

349

350

# Display NumPy array

351

data = np.random.randint(0, 256, (100, 100), dtype=np.uint8)

352

tifffile.imshow(data)

353

```

354

355

## Performance Considerations

356

357

### Large File Handling

358

359

- Use `aszarr=True` for extremely large files to avoid memory issues

360

- Specify `maxworkers` for parallel processing of multi-page files

361

- Use `selection` parameter to read only required data regions

362

- Consider `memmap()` for repeated access to large files

363

364

### Compression Trade-offs

365

366

- LZW: Good compression, fast decompression, widely supported

367

- DEFLATE: Better compression than LZW, slower processing

368

- JPEG: Excellent compression for photographic data, lossy

369

- ZSTD/LZMA: Modern algorithms with excellent compression ratios

370

371

### Memory Management

372

373

- Use appropriate `buffersize` for I/O operations

374

- Specify `out` parameter to reuse pre-allocated arrays

375

- Consider `chunkmode` settings for optimal memory usage

376

- Use `squeeze=False` to preserve array dimensions when needed

377

378

## Error Handling

379

380

Common exceptions and error conditions:

381

382

- **TiffFileError**: Invalid file format, corruption, or unsupported features

383

- **ValueError**: Invalid parameters or incompatible data types

384

- **IOError**: File access issues or insufficient disk space

385

- **MemoryError**: Insufficient memory for large file operations

386

387

```python

388

try:

389

image = tifffile.imread('corrupted.tif')

390

except tifffile.TiffFileError as e:

391

print(f"TIFF file error: {e}")

392

except IOError as e:

393

print(f"File access error: {e}")

394

```