CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-tifffile

Read and write TIFF files for scientific and bioimaging applications with comprehensive format support

Overview
Eval results
Files

cli-tools.mddocs/

Command-line Tools

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.

Capabilities

Main CLI Interface

Primary command-line interface for displaying TIFF file information and metadata.

def main():
    """
    Main command-line interface for tifffile operations.

    Usage:
    python -m tifffile [options] file [file ...]

    Options:
    --verbose, -v     : Verbose output
    --info, -i        : Show detailed file information  
    --tags, -t        : Show all TIFF tags
    --series, -s      : Show image series information
    --pages, -p       : Show page-level information
    --metadata, -m    : Show format-specific metadata
    --validate        : Validate TIFF file structure
    --photometric     : Show photometric interpretation
    --compression     : Show compression information
    --shape           : Show image dimensions only
    --dtype           : Show data type only

    Returns:
    - int: Exit code (0 for success)
    """

Usage Examples

# Basic file information
python -m tifffile image.tif

# Detailed information with all metadata
python -m tifffile --verbose --metadata image.tif

# Show only shape and data type
python -m tifffile --shape --dtype image.tif

# Validate multiple files
python -m tifffile --validate *.tif

# Show TIFF tags for debugging
python -m tifffile --tags corrupted.tif

# Analyze image series in OME-TIFF
python -m tifffile --series multi_series.ome.tif

TIFF Comment Tool

Utility for reading and modifying ImageDescription tags in TIFF files.

def tiffcomment(filename, comment=None):
    """
    Read or write TIFF ImageDescription tag.

    Parameters:
    - filename: str or PathLike, path to TIFF file
    - comment: str or bytes, new comment to write (None to read)

    Returns:
    - str: Current ImageDescription content when reading
    - None: When writing comment

    Command-line usage:
    tiffcomment file.tif                    # Read current comment
    tiffcomment --set "New comment" file.tif # Write new comment
    """

Usage Examples

# Read current ImageDescription
tiffcomment image.tif

# Set new ImageDescription
tiffcomment --set "Scientific data from experiment 2023-12" image.tif

# Clear ImageDescription
tiffcomment --set "" image.tif

# Read from multiple files
for file in *.tif; do
    echo "$file: $(tiffcomment "$file")"
done

Programmatic Usage

# Read current description
current_desc = tifffile.tiffcomment('image.tif')
print(f"Current description: {current_desc}")

# Write new description
tifffile.tiffcomment('image.tif', 'Updated description')

# Batch update descriptions
import glob
for filename in glob.glob('*.tif'):
    tifffile.tiffcomment(filename, f'Processed on {datetime.now()}')

LSM to BIN Converter

Convert Zeiss LSM files to binary format for specialized analysis tools.

def lsm2bin(filename, output=None):
    """
    Convert TZCYX LSM file to series of BIN files.

    Parameters:
    - filename: str or PathLike, path to LSM file
    - output: str or PathLike, output filename template (optional)

    Command-line usage:
    lsm2bin input.lsm [output_template]

    The output template can include format specifiers:
    - {t}: time point index
    - {z}: z-slice index  
    - {c}: channel index

    Returns:
    - None (creates binary files on disk)
    """

Usage Examples

# Convert LSM to BIN files with default naming
lsm2bin timeseries.lsm

# Convert with custom output template
lsm2bin timeseries.lsm "output_t{t:03d}_z{z:02d}_c{c:02d}.bin"

# Convert multiple LSM files
for lsm in *.lsm; do
    lsm2bin "$lsm" "${lsm%.lsm}_t{t:03d}.bin"
done

Programmatic Usage

# Convert LSM file
tifffile.lsm2bin('timeseries.lsm')

# Convert with custom output naming
tifffile.lsm2bin('data.lsm', 'processed_{t:03d}_{c:02d}.bin')

# Batch conversion
import glob
for lsm_file in glob.glob('*.lsm'):
    output_template = lsm_file.replace('.lsm', '_t{t:03d}.bin')
    tifffile.lsm2bin(lsm_file, output_template)

TIFF to FSSpec Converter

Create fsspec ReferenceFileSystem files for cloud-native access to TIFF data.

def tiff2fsspec(filename, url, **kwargs):
    """
    Write fsspec ReferenceFileSystem JSON for TIFF file.

    Parameters:
    - filename: str or PathLike, path to local TIFF file
    - url: str, remote URL base path (without filename)
    - out: str, output JSON filename (optional)
    - series: int, image series index (optional)
    - level: int, pyramid level index (optional) 
    - key: int, page index (optional)
    - chunkmode: str, chunking strategy (optional)

    Command-line usage:
    tiff2fsspec local_file.tif https://server.com/path/ [options]

    Options:
    --out FILE          : Output JSON filename
    --series N          : Series index
    --level N           : Pyramid level index  
    --key N             : Page index
    --chunkmode MODE    : Chunking mode (page, tile, etc.)

    Returns:
    - dict: ReferenceFileSystem specification
    """

Usage Examples

# Create reference for cloud-hosted file
tiff2fsspec ./local_copy.tif https://data.server.com/images/

# Create reference with custom output name
tiff2fsspec ./data.tif https://cloud.example.com/data/ --out data_reference.json

# Create reference for specific series
tiff2fsspec ./multi_series.ome.tif https://server.com/ome/ --series 1

# Create reference for pyramid level
tiff2fsspec ./pyramid.tif https://server.com/pyramids/ --level 2

# Create reference with page-based chunking
tiff2fsspec ./large.tif https://server.com/big/ --chunkmode page

Programmatic Usage

# Create fsspec reference
reference = tifffile.tiff2fsspec(
    'local_file.tif',
    'https://data.server.com/images/',
    out='reference.json'
)

# Use the reference with fsspec
import fsspec
import zarr

# Open remote file via reference
fs = fsspec.filesystem('reference', fo=reference)
store = fs.get_mapper('')
z_array = zarr.open(store)

# Access remote data
data_chunk = z_array[1000:2000, 1000:2000]

File Validation Tool

Enhanced TIFF validation using JHOVE-compatible rules.

def validate_jhove(filename, **kwargs):
    """
    Validate TIFF file using JHOVE-compatible validation rules.

    Parameters:
    - filename: str or PathLike, path to TIFF file
    - **kwargs: validation options

    Returns:
    - dict: Validation results with 'valid' boolean and 'issues' list
    """

Usage Examples

# Validate single file
result = tifffile.validate_jhove('image.tif')
if result['valid']:
    print("File is valid")
else:
    print("Issues found:")
    for issue in result['issues']:
        print(f"  - {issue}")

# Batch validation
import glob
for filename in glob.glob('*.tif'):
    result = tifffile.validate_jhove(filename)
    status = "VALID" if result['valid'] else "INVALID"
    print(f"{filename}: {status}")
    
    if not result['valid']:
        for issue in result['issues']:
            print(f"  - {issue}")

Advanced Command-Line Usage

Scripting Integration

#!/bin/bash
# Batch processing script using tifffile CLI tools

# Process all TIFF files in directory
for tiff_file in *.tif; do
    echo "Processing $tiff_file..."
    
    # Get basic info
    python -m tifffile --shape --dtype "$tiff_file"
    
    # Validate file
    if python -m tifffile --validate "$tiff_file" > /dev/null 2>&1; then
        echo "  ✓ Valid TIFF file"
        
        # Add processing timestamp to description
        current_date=$(date '+%Y-%m-%d %H:%M:%S')
        tiffcomment --set "Processed on $current_date" "$tiff_file"
        
    else
        echo "  ✗ Invalid TIFF file"
    fi
done

Metadata Extraction Pipeline

#!/bin/bash
# Extract metadata from scientific TIFF files

output_file="metadata_report.txt"
echo "TIFF Metadata Report - $(date)" > "$output_file"
echo "=================================" >> "$output_file"

for tiff_file in *.tif *.ome.tif; do
    if [[ -f "$tiff_file" ]]; then
        echo "" >> "$output_file"
        echo "File: $tiff_file" >> "$output_file"
        echo "-------------------" >> "$output_file"
        
        # Basic information
        python -m tifffile --info "$tiff_file" >> "$output_file"
        
        # Metadata
        python -m tifffile --metadata "$tiff_file" >> "$output_file"
        
        # Current description
        desc=$(tiffcomment "$tiff_file" 2>/dev/null || echo "No description")
        echo "Description: $desc" >> "$output_file"
    fi
done

echo "Metadata report saved to $output_file"

Cloud Migration Script

#!/bin/bash
# Create fsspec references for cloud migration

cloud_base_url="https://storage.example.com/tiff-data/"
reference_dir="./references"

mkdir -p "$reference_dir"

for tiff_file in *.tif; do
    if [[ -f "$tiff_file" ]]; then
        echo "Creating reference for $tiff_file..."
        
        # Create fsspec reference
        reference_file="$reference_dir/${tiff_file%.tif}.json"
        tiff2fsspec "$tiff_file" "$cloud_base_url" --out "$reference_file"
        
        # Validate the reference was created
        if [[ -f "$reference_file" ]]; then
            echo "  ✓ Reference created: $reference_file"
        else
            echo "  ✗ Failed to create reference"
        fi
    fi
done

Format Conversion Pipeline

#!/bin/bash
# Convert various formats to standardized TIFF

input_dir="./input"
output_dir="./converted"
temp_dir="./temp"

mkdir -p "$output_dir" "$temp_dir"

# Convert LSM files to TIFF via BIN intermediate
for lsm_file in "$input_dir"/*.lsm; do
    if [[ -f "$lsm_file" ]]; then
        basename=$(basename "$lsm_file" .lsm)
        echo "Converting $basename.lsm..."
        
        # Convert to BIN files
        lsm2bin "$lsm_file" "$temp_dir/${basename}_t{t:03d}.bin"
        
        # Process BIN files back to TIFF (would need custom script)
        # This is where you'd add your BIN to TIFF conversion logic
        
        echo "  ✓ Converted $basename"
    fi
done

# Clean up temporary files
rm -rf "$temp_dir"

Performance Monitoring

Benchmarking Script

#!/bin/bash
# Benchmark TIFF operations

test_file="test_image.tif"
results_file="benchmark_results.txt"

echo "TIFF Performance Benchmark - $(date)" > "$results_file"
echo "====================================" >> "$results_file"

# Test file info extraction
echo "Testing file info extraction..." | tee -a "$results_file"
time_output=$(time python -m tifffile --info "$test_file" 2>&1)
echo "$time_output" >> "$results_file"

# Test metadata extraction
echo "Testing metadata extraction..." | tee -a "$results_file"
time_output=$(time python -m tifffile --metadata "$test_file" 2>&1)
echo "$time_output" >> "$results_file"

# Test validation
echo "Testing validation..." | tee -a "$results_file"
time_output=$(time python -m tifffile --validate "$test_file" 2>&1)
echo "$time_output" >> "$results_file"

echo "Benchmark completed. Results saved to $results_file"

Error Handling and Troubleshooting

Common Issues and Solutions

# Check if file is accessible
if ! python -m tifffile --validate "$tiff_file" 2>/dev/null; then
    echo "File validation failed: $tiff_file"
    
    # Try to get basic info for debugging
    python -m tifffile --verbose "$tiff_file" 2>&1 | head -20
fi

# Handle missing files gracefully
for pattern in "*.tif" "*.ome.tif" "*.lsm"; do
    files=($pattern)
    if [[ -f "${files[0]}" ]]; then
        for file in "${files[@]}"; do
            echo "Processing $file"
            # Process file...
        done
    else
        echo "No files found matching pattern: $pattern"
    fi
done

Logging and Debugging

# Enable verbose logging
export TIFFFILE_LOG_LEVEL=DEBUG

# Run with detailed output
python -m tifffile --verbose --tags problematic.tif > debug_output.txt 2>&1

# Check specific metadata issues
if ! tiffcomment problematic.tif > /dev/null 2>&1; then
    echo "ImageDescription tag may be corrupted"
    python -m tifffile --tags problematic.tif | grep -i description
fi

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.

Install with Tessl CLI

npx tessl i tessl/pypi-tifffile

docs

cli-tools.md

constants-enums.md

core-io.md

file-classes.md

index.md

metadata-tags.md

utilities.md

zarr-integration.md

tile.json