Load a tiff stack in a numpy array with python

风流意气都作罢 提交于 2019-12-03 06:48:22

I am not sure if there is a way to get PIL to open multiple slices of a tiff stack.

If you are not bound to using PIL, however, an alternative is scikit-image, which opens multiple slices from a tiff stack by default. Here is some sample code of how to load a tiff stack into a Numpy array using scikit-image:

>>> from skimage import io
>>> im = io.imread('an_image.tif')
>>> print im.shape
(2, 64, 64)

Note that the imread function loads the image directly into a Numpy array. Also, the dimensions of the resulting array are ordered (z, y, x) where z represents the depth, y represents the height, and x represents the width. Thus, to get a single slice from the stack all you have to do is:

>>> print im[1].shape
(64, 64)

PIL has a function seek to move to different slices of a tiff stack.

from PIL import Image as pilimage

file_path=(D:\luca\test\test.tif)
print("The selected stack is a .tif")
dataset = pilimage(file_path)
w,h = dataset.size
tifarray = np.zeros((w,h,dataset.n_frames))
for i in range(dataset.n_frames):
   dataset.seek(i)
   tiffarray[:,:,i] = np.array(dataset)
expim = tiffarray.astype(np.double);
print(expim.shape)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!