Search code examples
pythontiffscikit-image

How to combine .tif stacks in python?


I'm trying to combine multiple .tif stacks (that already consist of 40 images each) into a single tiff stack. I would prefer to do this using python. What I tried so far is (Keep in mind I don't have a lot of experience writing code, so sorry if I'm missing something obvious):

import numpy as np
from skimage import io

im1 = io.imread('filename1.ome.tif')
for i in range(2,10):
    im = io.imread('filename'+str(i)+'.ome.tif')
    im1 = np.concatenate((im1,im))

io.imsave('filescombined.ome.tif', im1)

This does leave me with a .tif file, and according to:

print(im1.shape)

It is the correct shape, and from using im1.dtype I get that both are uint16. However, I can not open the resulting image in ImageJ (or any other viewer I've tried). The problem doesn't seem to come from data being lost with io.imread or io.imsave, because if I do:

image = io.imread('filename1.ome.tif')
io.imsave('testing.ome.tif', image)

The result can be opened. So I guess the problem has to stem from np.concatenate, but I have no idea what exactly the problem is, let alone how to fix it.

If you have any ideas on how to fix it, that would be very much appreciated!


Solution

  • Try the external.tifffile module of scikit image. It does not seem to encounter the problem you describe.

    The following works for me on Windows 7 and Python 3.5. It correctly saves a stack of 180 images each 100x100 pixels that can be imported straight into ImageJ

    from skimage.external import tifffile as tif
    import numpy as np
    
    stack1 = np.random.randint(255, size=(20, 100, 100))
    
    for i in range(2,10):
        stack = np.random.randint(255, size=(20, 100, 100))
        stack1 = np.concatenate((stack1,stack))
    
    tif.imsave('stack1.tif', stack1.astype('uint16'), bigtiff=True)
    

    When you drag and drop the file into ImageJ the Bio-Formats Import Option will pop up (see below). Just select the View Stack as "Standard ImageJ" and data will be loaded.Screenshot of the ImageJ Bio-Format Import Option popup window