Search code examples
pythonimagetiff

Write a tiff stack with python and keep file name


I have a folder with 5 tiff images that I want to put together in one stack file.

img01.tiff, img20.tiff, img25.tif, img30.tif, img50.tif

Afte processing I would like to convert that stack into single images, and conserve the file name.

To stack I do:

import tifffile as tiff
import os
from natsort import natsorted

path='img_folder'
output_filename='stack.tiff'
with tiff.TiffWriter(output_filename, bigtiff=True) as tif_writer:
    for idx, filename in enumerate(natsorted(os.listdir(path))):
        print(filename)
        img=tiff.imread(os.path.join(path,filename),name=filename)
        tif_writer.save(img)

I tried writing on the description parameter or metadata (Info as well as Labels) but it did not work:

tif_writer.save(img, photometric='minisblack', metadata={'Info': filename}, description=filename)

In any case the file name information is lost or I don't now how to access it.

Any help would be much appreciated!


Solution

  • From the source,

    [description & metadata are] saved with the first page of a series only.

    EDIT: I updated this example to include the two options suggested by @cgohlke

    Option 1: Write separate series

    By default using TiffWriter.write or TiffWriter.save sequentially like this will create a separate series in the resulting image and save the description to the first page in each series.

    import numpy as np
    import tifffile
    
    with tifffile.TiffWriter('temp.tif') as tif:
      for i in range(4):
        filename = f"image_{i}"
        img = np.random.randint(0, 1023, (256, 256), 'uint16')
        tif.save(img, photometric='minisblack', description=filename)
    
    
    with tifffile.TiffFile('temp.tif') as tif:
      for series in tif.series:
        first_page = series[0]
        print(first_page.description)
      
      # tif.asarray returns the first series by default, 
      # so `key` is needed to create the stack from multiple series.
      stack = tif.asarray(key=slice(None))
      print(stack.shape)
    
    # image_0
    # image_1
    # image_2
    # image_3
    # (4, 256, 256)
    

    Option 2: Write one series

    By setting metadata=None, you can write individual pages to the same series and iterate over the pages to get the descriptions.

    import numpy as np
    import tifffile
    
    with tifffile.TiffWriter('temp.tif') as tif:
      for i in range(4):
        filename = f"image_{i}"
        img = np.random.randint(0, 1023, (256, 256), 'uint16')
        tif.save(img, photometric='minisblack', description=filename, metadata=None)
    
    
    with tifffile.TiffFile('temp.tif') as tif:
      for page in tif.pages:
        print(page.description)
    
      stack = tif.asarray() # no need for `key` because pages in same series
      print(stack.shape)
    
    # image_0
    # image_1
    # image_2
    # image_3
    # (4, 256, 256)