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

file-classes.mddocs/

0

# TIFF File Classes

1

2

Object-oriented interfaces for detailed TIFF file manipulation, providing granular control over reading and writing operations. These classes offer comprehensive access to TIFF file structure, metadata, and advanced features beyond the simple imread/imwrite functions.

3

4

## Capabilities

5

6

### TiffFile Class

7

8

Primary class for reading TIFF files with comprehensive metadata access and flexible data extraction options.

9

10

```python { .api }

11

class TiffFile:

12

def __init__(

13

self,

14

file,

15

*,

16

mode='r',

17

name=None,

18

offset=None,

19

size=None,

20

omexml=None,

21

**is_flags

22

):

23

"""

24

Initialize TIFF file reader.

25

26

Parameters:

27

- file: str, PathLike, or file handle to TIFF file

28

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

29

- name: str, name within container file

30

- offset: int, byte offset in file

31

- size: int, number of bytes to read

32

- omexml: str, override OME-XML metadata

33

- **is_flags: format detection flags (is_ome, is_imagej, etc.)

34

"""

35

36

def asarray(

37

self,

38

key=None,

39

series=None,

40

level=None,

41

squeeze=None,

42

out=None,

43

maxworkers=None,

44

**kwargs

45

):

46

"""

47

Return image data as NumPy array.

48

49

Parameters:

50

- key: int, slice, or sequence of page indices

51

- series: int, series index for multi-series files

52

- level: int, pyramid level for multi-resolution files

53

- squeeze: bool, remove singleton dimensions

54

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

55

- maxworkers: int, number of worker threads

56

57

Returns:

58

- np.ndarray: Image data array

59

"""

60

61

def aszarr(

62

self,

63

key=None,

64

series=None,

65

level=None,

66

chunkmode=None,

67

fillvalue=None,

68

zattrs=None,

69

**kwargs

70

):

71

"""

72

Return image data as Zarr store.

73

74

Parameters:

75

- key: int, slice, or sequence of page indices

76

- series: int, series index

77

- level: int, pyramid level

78

- chunkmode: CHUNKMODE enum, chunking strategy

79

- fillvalue: numeric, fill value for missing data

80

- zattrs: dict, additional Zarr attributes

81

82

Returns:

83

- ZarrTiffStore: Zarr store interface

84

"""

85

86

def close(self):

87

"""Close the TIFF file."""

88

89

# Properties

90

@property

91

def pages(self):

92

"""TiffPages: Sequence of pages in file."""

93

94

@property

95

def series(self):

96

"""list: Image series in file."""

97

98

@property

99

def byteorder(self):

100

"""str: Byte order of file ('<', '>')."""

101

102

@property

103

def flags(self):

104

"""dict: File format detection flags."""

105

106

@property

107

def filename(self):

108

"""str: Name of the file."""

109

110

# Metadata properties

111

@property

112

def ome_metadata(self):

113

"""dict: OME-XML metadata."""

114

115

@property

116

def imagej_metadata(self):

117

"""dict: ImageJ metadata."""

118

119

@property

120

def lsm_metadata(self):

121

"""dict: LSM metadata."""

122

123

@property

124

def stk_metadata(self):

125

"""dict: MetaMorph STK metadata."""

126

127

@property

128

def gdal_metadata(self):

129

"""dict: GDAL metadata."""

130

131

@property

132

def shaped_metadata(self):

133

"""tuple: Shaped array metadata."""

134

```

135

136

#### Usage Examples

137

138

```python

139

# Basic file reading with metadata access

140

with tifffile.TiffFile('image.tif') as tif:

141

print(f"Pages: {len(tif.pages)}")

142

print(f"Shape: {tif.pages[0].shape}")

143

print(f"Description: {tif.pages[0].description}")

144

data = tif.asarray()

145

146

# Access specific series in multi-series file

147

with tifffile.TiffFile('multi_series.ome.tif') as tif:

148

print(f"Number of series: {len(tif.series)}")

149

series0 = tif.asarray(series=0)

150

series1 = tif.asarray(series=1)

151

152

# Read pyramid levels

153

with tifffile.TiffFile('pyramid.tif') as tif:

154

full_res = tif.asarray(level=0)

155

thumbnail = tif.asarray(level=2)

156

157

# Access as Zarr store for large files

158

with tifffile.TiffFile('large.tif') as tif:

159

zarr_store = tif.aszarr()

160

chunk = zarr_store[1000:2000, 1000:2000]

161

162

# Examine metadata

163

with tifffile.TiffFile('ome.tif') as tif:

164

if tif.ome_metadata:

165

print("OME metadata:", tif.ome_metadata)

166

if tif.imagej_metadata:

167

print("ImageJ metadata:", tif.imagej_metadata)

168

```

169

170

### TiffWriter Class

171

172

Comprehensive class for writing TIFF files with detailed control over format, compression, and metadata.

173

174

```python { .api }

175

class TiffWriter:

176

def __init__(

177

self,

178

file,

179

*,

180

mode='w',

181

bigtiff=None,

182

byteorder=None,

183

append=False,

184

imagej=False,

185

ome=None,

186

shaped=None

187

):

188

"""

189

Initialize TIFF file writer.

190

191

Parameters:

192

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

193

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

194

- bigtiff: bool, create BigTIFF format

195

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

196

- append: bool, append to existing file

197

- imagej: bool, create ImageJ-compatible format

198

- ome: bool, create OME-TIFF format

199

- shaped: bool, create shaped array format

200

"""

201

202

def write(

203

self,

204

data,

205

*,

206

shape=None,

207

dtype=None,

208

photometric=None,

209

planarconfig=None,

210

extrasamples=None,

211

tile=None,

212

compression=None,

213

compressionargs=None,

214

predictor=None,

215

description=None,

216

datetime=None,

217

resolution=None,

218

metadata=None,

219

extratags=None,

220

contiguous=False,

221

**kwargs

222

):

223

"""

224

Write image data to TIFF file.

225

226

Parameters:

227

- data: array-like, image data to write

228

- shape: tuple, explicit data shape

229

- dtype: dtype, data type

230

- photometric: PHOTOMETRIC enum, color interpretation

231

- planarconfig: PLANARCONFIG enum, sample organization

232

- extrasamples: sequence, extra sample interpretation

233

- tile: tuple, tile dimensions

234

- compression: COMPRESSION enum, compression algorithm

235

- compressionargs: dict, compression parameters

236

- predictor: PREDICTOR enum, predictor scheme

237

- description: str, ImageDescription tag

238

- datetime: datetime or str, timestamp

239

- resolution: tuple, X/Y resolution

240

- metadata: dict, additional metadata

241

- extratags: sequence, custom tags

242

- contiguous: bool, write contiguous data

243

244

Returns:

245

- int: Number of bytes written

246

"""

247

248

def close(self):

249

"""Close the TIFF file and finalize writing."""

250

251

def overwrite_description(self, description):

252

"""

253

Overwrite ImageDescription tag of last written page.

254

255

Parameters:

256

- description: str, new description text

257

"""

258

```

259

260

#### Usage Examples

261

262

```python

263

# Sequential writing with compression

264

with tifffile.TiffWriter('output.tif', bigtiff=True) as writer:

265

for i in range(10):

266

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

267

writer.write(

268

data,

269

compression='lzw',

270

description=f'Frame {i}'

271

)

272

273

# Write ImageJ hyperstack

274

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

275

with tifffile.TiffWriter('stack.tif', imagej=True) as writer:

276

writer.write(

277

stack,

278

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

279

)

280

281

# Write OME-TIFF with metadata

282

with tifffile.TiffWriter('ome.tif', ome=True) as writer:

283

writer.write(

284

data,

285

metadata={

286

'axes': 'YX',

287

'PhysicalSizeX': 0.1,

288

'PhysicalSizeY': 0.1

289

}

290

)

291

292

# Write with custom tags

293

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

294

with tifffile.TiffWriter('custom.tif') as writer:

295

writer.write(data, extratags=custom_tags)

296

```

297

298

### TiffPage Class

299

300

Represents individual TIFF Image File Directory (IFD) with detailed access to page-specific data and metadata.

301

302

```python { .api }

303

class TiffPage:

304

def asarray(

305

self,

306

squeeze=True,

307

colormapped=True,

308

rgbonly=True,

309

alpha=None,

310

out=None,

311

maxworkers=None,

312

**kwargs

313

):

314

"""

315

Return page image data as NumPy array.

316

317

Parameters:

318

- squeeze: bool, remove singleton dimensions

319

- colormapped: bool, apply colormap if present

320

- rgbonly: bool, return only RGB channels

321

- alpha: str, alpha channel handling ('ignore', 'premultiply')

322

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

323

- maxworkers: int, number of worker threads

324

325

Returns:

326

- np.ndarray: Image data

327

"""

328

329

def aszarr(self, **kwargs):

330

"""

331

Return page image data as Zarr store.

332

333

Returns:

334

- ZarrTiffStore: Zarr store interface

335

"""

336

337

# Properties

338

@property

339

def shape(self):

340

"""tuple: Shape of image data."""

341

342

@property

343

def dtype(self):

344

"""np.dtype: Data type of image."""

345

346

@property

347

def compression(self):

348

"""COMPRESSION: Compression scheme."""

349

350

@property

351

def photometric(self):

352

"""PHOTOMETRIC: Photometric interpretation."""

353

354

@property

355

def description(self):

356

"""str: ImageDescription tag content."""

357

358

@property

359

def datetime(self):

360

"""datetime: Image creation timestamp."""

361

362

@property

363

def resolution(self):

364

"""tuple: X and Y resolution."""

365

366

# Metadata tag properties

367

@property

368

def andor_tags(self):

369

"""dict: Andor metadata tags."""

370

371

@property

372

def epics_tags(self):

373

"""dict: EPICS area detector tags."""

374

375

@property

376

def geotiff_tags(self):

377

"""dict: GeoTIFF metadata tags."""

378

379

@property

380

def imagej_tags(self):

381

"""dict: ImageJ metadata tags."""

382

383

@property

384

def ome_tags(self):

385

"""dict: OME-TIFF metadata tags."""

386

```

387

388

### TiffPages Class

389

390

Sequence container for accessing multiple pages within a TIFF file.

391

392

```python { .api }

393

class TiffPages:

394

def __len__(self):

395

"""Return number of pages."""

396

397

def __getitem__(self, key):

398

"""Return page(s) by index."""

399

400

def __iter__(self):

401

"""Iterate over pages."""

402

403

@property

404

def first(self):

405

"""TiffPage: First page in sequence."""

406

407

@property

408

def last(self):

409

"""TiffPage: Last page in sequence."""

410

```

411

412

### TiffPageSeries Class

413

414

Represents a series of pages with compatible shape and data type, typically used for multi-dimensional datasets.

415

416

```python { .api }

417

class TiffPageSeries:

418

def asarray(self, **kwargs):

419

"""

420

Return series data as NumPy array.

421

422

Returns:

423

- np.ndarray: Combined data from all pages in series

424

"""

425

426

def aszarr(self, **kwargs):

427

"""

428

Return series data as Zarr store.

429

430

Returns:

431

- ZarrTiffStore: Zarr store interface

432

"""

433

434

@property

435

def shape(self):

436

"""tuple: Shape of combined series data."""

437

438

@property

439

def dtype(self):

440

"""np.dtype: Data type of series."""

441

442

@property

443

def axes(self):

444

"""str: Axes labels for dimensions."""

445

446

@property

447

def pages(self):

448

"""TiffPages: Pages included in series."""

449

```

450

451

### TiffSequence Class

452

453

Handle sequences of TIFF files as a single logical dataset.

454

455

```python { .api }

456

class TiffSequence:

457

def __init__(

458

self,

459

files,

460

imread=None,

461

pattern=None,

462

axesorder=None,

463

categories=None,

464

**kwargs

465

):

466

"""

467

Initialize TIFF file sequence.

468

469

Parameters:

470

- files: sequence of file paths

471

- imread: callable, custom reading function

472

- pattern: str, glob pattern for file matching

473

- axesorder: sequence, axis reordering

474

- categories: dict, categorical data mappings

475

"""

476

477

def asarray(self, **kwargs):

478

"""

479

Return sequence data as NumPy array.

480

481

Returns:

482

- np.ndarray: Combined data from all files

483

"""

484

485

def aszarr(self, **kwargs):

486

"""

487

Return sequence data as Zarr store.

488

489

Returns:

490

- ZarrFileSequenceStore: Zarr store interface

491

"""

492

493

@property

494

def shape(self):

495

"""tuple: Shape of combined sequence data."""

496

497

@property

498

def axes(self):

499

"""str: Axes labels for dimensions."""

500

```

501

502

#### Usage Examples

503

504

```python

505

# Process file sequence

506

files = ['img001.tif', 'img002.tif', 'img003.tif']

507

sequence = tifffile.TiffSequence(files)

508

combined = sequence.asarray()

509

print(f"Combined shape: {combined.shape}")

510

511

# Use pattern matching

512

sequence = tifffile.TiffSequence('img*.tif', pattern='img*.tif')

513

zarr_store = sequence.aszarr()

514

```

515

516

### TiffReader Class

517

518

Legacy interface for reading TIFF files (maintained for compatibility).

519

520

```python { .api }

521

class TiffReader:

522

def __init__(self, file, **kwargs):

523

"""Initialize TIFF reader (legacy interface)."""

524

525

def close(self):

526

"""Close the file."""

527

```

528

529

### TiffFrame Class

530

531

Represents a frame within a TIFF file sequence or animation.

532

533

```python { .api }

534

class TiffFrame:

535

@property

536

def index(self):

537

"""int: Frame index in sequence."""

538

539

@property

540

def offset(self):

541

"""int: Byte offset in file."""

542

543

@property

544

def shape(self):

545

"""tuple: Frame dimensions."""

546

```

547

548

## Advanced Usage Patterns

549

550

### Multi-threaded Reading

551

552

```python

553

# Parallel page processing

554

with tifffile.TiffFile('large_stack.tif') as tif:

555

data = tif.asarray(maxworkers=4) # Use 4 threads

556

```

557

558

### Memory-efficient Processing

559

560

```python

561

# Process large files without loading into memory

562

with tifffile.TiffFile('huge.tif') as tif:

563

zarr_store = tif.aszarr()

564

565

# Process in chunks

566

for i in range(0, zarr_store.shape[0], 1000):

567

chunk = zarr_store[i:i+1000]

568

# Process chunk...

569

```

570

571

### Metadata Extraction

572

573

```python

574

# Extract comprehensive metadata

575

with tifffile.TiffFile('scientific.tif') as tif:

576

page = tif.pages[0]

577

578

metadata = {

579

'shape': page.shape,

580

'dtype': page.dtype,

581

'compression': page.compression.name,

582

'photometric': page.photometric.name,

583

'resolution': page.resolution,

584

'description': page.description

585

}

586

587

# Format-specific metadata

588

if tif.ome_metadata:

589

metadata['ome'] = tif.ome_metadata

590

if tif.imagej_metadata:

591

metadata['imagej'] = tif.imagej_metadata

592

```

593

594

## Error Handling

595

596

```python

597

try:

598

with tifffile.TiffFile('problematic.tif') as tif:

599

data = tif.asarray()

600

except tifffile.TiffFileError as e:

601

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

602

except ValueError as e:

603

print(f"Invalid parameters: {e}")

604

except MemoryError as e:

605

print(f"Insufficient memory: {e}")

606

# Try with Zarr instead

607

zarr_store = tif.aszarr()

608

```