pythonstacktiff

Save TIFF stack with different metadata


I have multiple photos from microscope in the form of numpy arrays and I want to store them in a single multistack TIFF file. They represent the same XY point but in different heights. I want that each slide has its own metadata where it stores information specific to that photo. This is what I have been trying using the tifffile library):

metadata = {'x': 10.5, 'y': 7.5}
with tifffile.TiffWriter(filename, bigtiff=False, imagej=False) as tif_writer:
     for z_slice in xyz_stack:
         metadata["z"] = z_slice.z
         tif_writer.write(z_slice.numpy_array, description=json.dumps(metadata))

But this doesn't work, as it puts the same description to all slices. How can I achieve this?

Thanks! :)


Solution

  • For images from microscopy, consider writing OME-TIFF files. This example writes a Z stack with metadata specifying the position of each plane:

    import numpy
    from tifffile import TiffWriter
    
    data = numpy.random.randint(0, 1023, (8, 256, 256), 'uint16')
    pixelsize = 0.29  # micrometer
    zpositions = [0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7]
    metadata = {
        'axes': 'ZYX',
        'SignificantBits': 10,
        'PhysicalSizeX': pixelsize,
        'PhysicalSizeXUnit': 'µm',
        'PhysicalSizeY': pixelsize,
        'PhysicalSizeYUnit': 'µm',
        'Plane': {
            'PositionZ': zpositions,
            'PositionZUnit': ['µm'] * data.shape[0],
            'PositionY': [7.5] * data.shape[1],
            'PositionYUnit': ['µm'] * data.shape[1],
            'PositionX': [10.5] * data.shape[2],
            'PositionXUnit': ['µm'] * data.shape[2],
        },
    }
    
    with TiffWriter('temp.ome.tif', bigtiff=False, ome=True) as tif:
        tif.write(
            data,
            photometric='minisblack',
            # tile=(128, 128),
            # compression='adobe_deflate',
            resolutionunit='CENTIMETER',
            resolution=(1e4 / pixelsize, 1e4 / pixelsize),
            metadata=metadata,
        )