0
# Command-line Tools
1
2
Command-line interfaces for TIFF file inspection, metadata manipulation, format conversion, and fsspec integration for cloud-native workflows. These tools provide convenient access to tifffile functionality from the command line and scripting environments.
3
4
## Capabilities
5
6
### Main CLI Interface
7
8
Primary command-line interface for displaying TIFF file information and metadata.
9
10
```python { .api }
11
def main():
12
"""
13
Main command-line interface for tifffile operations.
14
15
Usage:
16
python -m tifffile [options] file [file ...]
17
18
Options:
19
--verbose, -v : Verbose output
20
--info, -i : Show detailed file information
21
--tags, -t : Show all TIFF tags
22
--series, -s : Show image series information
23
--pages, -p : Show page-level information
24
--metadata, -m : Show format-specific metadata
25
--validate : Validate TIFF file structure
26
--photometric : Show photometric interpretation
27
--compression : Show compression information
28
--shape : Show image dimensions only
29
--dtype : Show data type only
30
31
Returns:
32
- int: Exit code (0 for success)
33
"""
34
```
35
36
#### Usage Examples
37
38
```bash
39
# Basic file information
40
python -m tifffile image.tif
41
42
# Detailed information with all metadata
43
python -m tifffile --verbose --metadata image.tif
44
45
# Show only shape and data type
46
python -m tifffile --shape --dtype image.tif
47
48
# Validate multiple files
49
python -m tifffile --validate *.tif
50
51
# Show TIFF tags for debugging
52
python -m tifffile --tags corrupted.tif
53
54
# Analyze image series in OME-TIFF
55
python -m tifffile --series multi_series.ome.tif
56
```
57
58
### TIFF Comment Tool
59
60
Utility for reading and modifying ImageDescription tags in TIFF files.
61
62
```python { .api }
63
def tiffcomment(filename, comment=None):
64
"""
65
Read or write TIFF ImageDescription tag.
66
67
Parameters:
68
- filename: str or PathLike, path to TIFF file
69
- comment: str or bytes, new comment to write (None to read)
70
71
Returns:
72
- str: Current ImageDescription content when reading
73
- None: When writing comment
74
75
Command-line usage:
76
tiffcomment file.tif # Read current comment
77
tiffcomment --set "New comment" file.tif # Write new comment
78
"""
79
```
80
81
#### Usage Examples
82
83
```bash
84
# Read current ImageDescription
85
tiffcomment image.tif
86
87
# Set new ImageDescription
88
tiffcomment --set "Scientific data from experiment 2023-12" image.tif
89
90
# Clear ImageDescription
91
tiffcomment --set "" image.tif
92
93
# Read from multiple files
94
for file in *.tif; do
95
echo "$file: $(tiffcomment "$file")"
96
done
97
```
98
99
#### Programmatic Usage
100
101
```python
102
# Read current description
103
current_desc = tifffile.tiffcomment('image.tif')
104
print(f"Current description: {current_desc}")
105
106
# Write new description
107
tifffile.tiffcomment('image.tif', 'Updated description')
108
109
# Batch update descriptions
110
import glob
111
for filename in glob.glob('*.tif'):
112
tifffile.tiffcomment(filename, f'Processed on {datetime.now()}')
113
```
114
115
### LSM to BIN Converter
116
117
Convert Zeiss LSM files to binary format for specialized analysis tools.
118
119
```python { .api }
120
def lsm2bin(filename, output=None):
121
"""
122
Convert TZCYX LSM file to series of BIN files.
123
124
Parameters:
125
- filename: str or PathLike, path to LSM file
126
- output: str or PathLike, output filename template (optional)
127
128
Command-line usage:
129
lsm2bin input.lsm [output_template]
130
131
The output template can include format specifiers:
132
- {t}: time point index
133
- {z}: z-slice index
134
- {c}: channel index
135
136
Returns:
137
- None (creates binary files on disk)
138
"""
139
```
140
141
#### Usage Examples
142
143
```bash
144
# Convert LSM to BIN files with default naming
145
lsm2bin timeseries.lsm
146
147
# Convert with custom output template
148
lsm2bin timeseries.lsm "output_t{t:03d}_z{z:02d}_c{c:02d}.bin"
149
150
# Convert multiple LSM files
151
for lsm in *.lsm; do
152
lsm2bin "$lsm" "${lsm%.lsm}_t{t:03d}.bin"
153
done
154
```
155
156
#### Programmatic Usage
157
158
```python
159
# Convert LSM file
160
tifffile.lsm2bin('timeseries.lsm')
161
162
# Convert with custom output naming
163
tifffile.lsm2bin('data.lsm', 'processed_{t:03d}_{c:02d}.bin')
164
165
# Batch conversion
166
import glob
167
for lsm_file in glob.glob('*.lsm'):
168
output_template = lsm_file.replace('.lsm', '_t{t:03d}.bin')
169
tifffile.lsm2bin(lsm_file, output_template)
170
```
171
172
### TIFF to FSSpec Converter
173
174
Create fsspec ReferenceFileSystem files for cloud-native access to TIFF data.
175
176
```python { .api }
177
def tiff2fsspec(filename, url, **kwargs):
178
"""
179
Write fsspec ReferenceFileSystem JSON for TIFF file.
180
181
Parameters:
182
- filename: str or PathLike, path to local TIFF file
183
- url: str, remote URL base path (without filename)
184
- out: str, output JSON filename (optional)
185
- series: int, image series index (optional)
186
- level: int, pyramid level index (optional)
187
- key: int, page index (optional)
188
- chunkmode: str, chunking strategy (optional)
189
190
Command-line usage:
191
tiff2fsspec local_file.tif https://server.com/path/ [options]
192
193
Options:
194
--out FILE : Output JSON filename
195
--series N : Series index
196
--level N : Pyramid level index
197
--key N : Page index
198
--chunkmode MODE : Chunking mode (page, tile, etc.)
199
200
Returns:
201
- dict: ReferenceFileSystem specification
202
"""
203
```
204
205
#### Usage Examples
206
207
```bash
208
# Create reference for cloud-hosted file
209
tiff2fsspec ./local_copy.tif https://data.server.com/images/
210
211
# Create reference with custom output name
212
tiff2fsspec ./data.tif https://cloud.example.com/data/ --out data_reference.json
213
214
# Create reference for specific series
215
tiff2fsspec ./multi_series.ome.tif https://server.com/ome/ --series 1
216
217
# Create reference for pyramid level
218
tiff2fsspec ./pyramid.tif https://server.com/pyramids/ --level 2
219
220
# Create reference with page-based chunking
221
tiff2fsspec ./large.tif https://server.com/big/ --chunkmode page
222
```
223
224
#### Programmatic Usage
225
226
```python
227
# Create fsspec reference
228
reference = tifffile.tiff2fsspec(
229
'local_file.tif',
230
'https://data.server.com/images/',
231
out='reference.json'
232
)
233
234
# Use the reference with fsspec
235
import fsspec
236
import zarr
237
238
# Open remote file via reference
239
fs = fsspec.filesystem('reference', fo=reference)
240
store = fs.get_mapper('')
241
z_array = zarr.open(store)
242
243
# Access remote data
244
data_chunk = z_array[1000:2000, 1000:2000]
245
```
246
247
### File Validation Tool
248
249
Enhanced TIFF validation using JHOVE-compatible rules.
250
251
```python { .api }
252
def validate_jhove(filename, **kwargs):
253
"""
254
Validate TIFF file using JHOVE-compatible validation rules.
255
256
Parameters:
257
- filename: str or PathLike, path to TIFF file
258
- **kwargs: validation options
259
260
Returns:
261
- dict: Validation results with 'valid' boolean and 'issues' list
262
"""
263
```
264
265
#### Usage Examples
266
267
```python
268
# Validate single file
269
result = tifffile.validate_jhove('image.tif')
270
if result['valid']:
271
print("File is valid")
272
else:
273
print("Issues found:")
274
for issue in result['issues']:
275
print(f" - {issue}")
276
277
# Batch validation
278
import glob
279
for filename in glob.glob('*.tif'):
280
result = tifffile.validate_jhove(filename)
281
status = "VALID" if result['valid'] else "INVALID"
282
print(f"{filename}: {status}")
283
284
if not result['valid']:
285
for issue in result['issues']:
286
print(f" - {issue}")
287
```
288
289
## Advanced Command-Line Usage
290
291
### Scripting Integration
292
293
```bash
294
#!/bin/bash
295
# Batch processing script using tifffile CLI tools
296
297
# Process all TIFF files in directory
298
for tiff_file in *.tif; do
299
echo "Processing $tiff_file..."
300
301
# Get basic info
302
python -m tifffile --shape --dtype "$tiff_file"
303
304
# Validate file
305
if python -m tifffile --validate "$tiff_file" > /dev/null 2>&1; then
306
echo " ✓ Valid TIFF file"
307
308
# Add processing timestamp to description
309
current_date=$(date '+%Y-%m-%d %H:%M:%S')
310
tiffcomment --set "Processed on $current_date" "$tiff_file"
311
312
else
313
echo " ✗ Invalid TIFF file"
314
fi
315
done
316
```
317
318
### Metadata Extraction Pipeline
319
320
```bash
321
#!/bin/bash
322
# Extract metadata from scientific TIFF files
323
324
output_file="metadata_report.txt"
325
echo "TIFF Metadata Report - $(date)" > "$output_file"
326
echo "=================================" >> "$output_file"
327
328
for tiff_file in *.tif *.ome.tif; do
329
if [[ -f "$tiff_file" ]]; then
330
echo "" >> "$output_file"
331
echo "File: $tiff_file" >> "$output_file"
332
echo "-------------------" >> "$output_file"
333
334
# Basic information
335
python -m tifffile --info "$tiff_file" >> "$output_file"
336
337
# Metadata
338
python -m tifffile --metadata "$tiff_file" >> "$output_file"
339
340
# Current description
341
desc=$(tiffcomment "$tiff_file" 2>/dev/null || echo "No description")
342
echo "Description: $desc" >> "$output_file"
343
fi
344
done
345
346
echo "Metadata report saved to $output_file"
347
```
348
349
### Cloud Migration Script
350
351
```bash
352
#!/bin/bash
353
# Create fsspec references for cloud migration
354
355
cloud_base_url="https://storage.example.com/tiff-data/"
356
reference_dir="./references"
357
358
mkdir -p "$reference_dir"
359
360
for tiff_file in *.tif; do
361
if [[ -f "$tiff_file" ]]; then
362
echo "Creating reference for $tiff_file..."
363
364
# Create fsspec reference
365
reference_file="$reference_dir/${tiff_file%.tif}.json"
366
tiff2fsspec "$tiff_file" "$cloud_base_url" --out "$reference_file"
367
368
# Validate the reference was created
369
if [[ -f "$reference_file" ]]; then
370
echo " ✓ Reference created: $reference_file"
371
else
372
echo " ✗ Failed to create reference"
373
fi
374
fi
375
done
376
```
377
378
### Format Conversion Pipeline
379
380
```bash
381
#!/bin/bash
382
# Convert various formats to standardized TIFF
383
384
input_dir="./input"
385
output_dir="./converted"
386
temp_dir="./temp"
387
388
mkdir -p "$output_dir" "$temp_dir"
389
390
# Convert LSM files to TIFF via BIN intermediate
391
for lsm_file in "$input_dir"/*.lsm; do
392
if [[ -f "$lsm_file" ]]; then
393
basename=$(basename "$lsm_file" .lsm)
394
echo "Converting $basename.lsm..."
395
396
# Convert to BIN files
397
lsm2bin "$lsm_file" "$temp_dir/${basename}_t{t:03d}.bin"
398
399
# Process BIN files back to TIFF (would need custom script)
400
# This is where you'd add your BIN to TIFF conversion logic
401
402
echo " ✓ Converted $basename"
403
fi
404
done
405
406
# Clean up temporary files
407
rm -rf "$temp_dir"
408
```
409
410
## Performance Monitoring
411
412
### Benchmarking Script
413
414
```bash
415
#!/bin/bash
416
# Benchmark TIFF operations
417
418
test_file="test_image.tif"
419
results_file="benchmark_results.txt"
420
421
echo "TIFF Performance Benchmark - $(date)" > "$results_file"
422
echo "====================================" >> "$results_file"
423
424
# Test file info extraction
425
echo "Testing file info extraction..." | tee -a "$results_file"
426
time_output=$(time python -m tifffile --info "$test_file" 2>&1)
427
echo "$time_output" >> "$results_file"
428
429
# Test metadata extraction
430
echo "Testing metadata extraction..." | tee -a "$results_file"
431
time_output=$(time python -m tifffile --metadata "$test_file" 2>&1)
432
echo "$time_output" >> "$results_file"
433
434
# Test validation
435
echo "Testing validation..." | tee -a "$results_file"
436
time_output=$(time python -m tifffile --validate "$test_file" 2>&1)
437
echo "$time_output" >> "$results_file"
438
439
echo "Benchmark completed. Results saved to $results_file"
440
```
441
442
## Error Handling and Troubleshooting
443
444
### Common Issues and Solutions
445
446
```bash
447
# Check if file is accessible
448
if ! python -m tifffile --validate "$tiff_file" 2>/dev/null; then
449
echo "File validation failed: $tiff_file"
450
451
# Try to get basic info for debugging
452
python -m tifffile --verbose "$tiff_file" 2>&1 | head -20
453
fi
454
455
# Handle missing files gracefully
456
for pattern in "*.tif" "*.ome.tif" "*.lsm"; do
457
files=($pattern)
458
if [[ -f "${files[0]}" ]]; then
459
for file in "${files[@]}"; do
460
echo "Processing $file"
461
# Process file...
462
done
463
else
464
echo "No files found matching pattern: $pattern"
465
fi
466
done
467
```
468
469
### Logging and Debugging
470
471
```bash
472
# Enable verbose logging
473
export TIFFFILE_LOG_LEVEL=DEBUG
474
475
# Run with detailed output
476
python -m tifffile --verbose --tags problematic.tif > debug_output.txt 2>&1
477
478
# Check specific metadata issues
479
if ! tiffcomment problematic.tif > /dev/null 2>&1; then
480
echo "ImageDescription tag may be corrupted"
481
python -m tifffile --tags problematic.tif | grep -i description
482
fi
483
```
484
485
These command-line tools provide comprehensive functionality for scientific imaging workflows, enabling efficient batch processing, validation, and format conversion operations in research and production environments.