I am creating tiff stacks of different sizes based on the example found here: http://www.bioimgtutorials.com/2016/08/03/creating-a-z-stack-in-python/
A sample of the tif files can be downloaded here: nucleus
I have a folder with 5 tiff files inside. I want to stack them to be able to open them in imageJ so that they look like this:
And this works with the following code:
from skimage import io
import numpy as np
import os
dir = 'C:/Users/Mich/Desktop/tiff stack/'
listfiles =[]
for img_files in os.listdir(dir):
if img_files.endswith(".tif") :
listfiles.append(img_files)
first_image = io.imread(dir+listfiles[0])
io.imshow(first_image)
first_image.shape
stack = np.zeros((5,first_image.shape[0],first_image.shape[1]),np.uint8)
for n in range(0,5):
stack[n,:,:]= io.imread(dir+listfiles[n])
path_results = 'C:/Users/Mich/Desktop/'
io.imsave(path_results+'Stack.tif' ,stack)
The problem comes when I just want to stack the 4 first ones or the 3 first ones.
Example with 4 tiff images:
stack=np.zeros((4,first_image.shape[0],first_image.shape[1]),np.uint8)
for n in range(0,4):
stack[n,:,:]= io.imread(dir+listfiles[n])
Then I obtain this kind of result:
and while trying to stack the 3 first images of the folder, they get combined!
stack=np.zeros((3,first_image.shape[0],first_image.shape[1]),np.uint8)
for n in range(0,3):
stack[n,:,:]= io.imread(dir+listfiles[n])
Where am I wrong in the code, so that it dosent just add the individual tiff in a multidimensional stack of the sizes 3, 4 or 5 ?
Specify the color space of the image data (photometric='minisblack'
), otherwise the tifffile plugin will guess it from the shape of the input array.
This is a shorter version using tifffile directly:
import glob
import tifffile
with tifffile.TiffWriter('Stack.tif') as stack:
for filename in glob.glob('nucleus/*.tif'):
stack.save(
tifffile.imread(filename),
photometric='minisblack',
contiguous=True
)