0

Code:

from PIL import Image
import numpy as np

img = Image.open('test.tif')     
imarray = np.zeros(shape = (34,23,18))

for i in range(34):          # there are 34 images in the .tif file
    for j in range(18):          # each slice has size 18x23
        for k in range(23):
            try:
                img.seek(i)
                imarray[i,k,j] = img.getpixel((k,j))
            except EOFError:
                break

The purpose of this code is to accept .tif greyscale stacks. I want to be able to work with them as numpy arrays, so storing the original pixel values is essential.

This code successfully copies each slice to the np.array "imarray." However, it changes the values. For example, I printed all of the "img.getpixel" values for a given slice, and the values (type int) ranged between 2000 and 65500. However, the values in imarray (type float64) did not exceed 2800. I tried casting, ie:

imarray[0,j,i] = np.float64(img.getpixel((j,i)))

But it did not help. How can I revise this code to avoid my input data (img.getpixels) changing? If there are better alternatives to this approach, I'm happy to hear

oofin
  • 160
  • 1
  • 2
  • 12
  • 2
    did you mean to put imarray[i,k,j] = np.float64(img.getpixel((j,i))) ? – eigenjohnson Jul 07 '18 at 17:54
  • Ah yes, thanks for catching that. I was testing the first slice and forgot to update the code - i'll edit now – oofin Jul 07 '18 at 17:58
  • It's not immediately obvious to me what your problem is, but do you explicitly want to convert to an array of floats, or keep the values as ints? If the latter, you can just make an integer array instead. – Iguananaut Jul 07 '18 at 21:20
  • see also https://stackoverflow.com/a/47836289/982257 for a more efficient way to do this. – Iguananaut Jul 07 '18 at 21:29
  • 1
    Possible duplicate of [Load a tiff stack in a numpy array with python](https://stackoverflow.com/questions/37722139/load-a-tiff-stack-in-a-numpy-array-with-python) – Iguananaut Jul 07 '18 at 21:29

0 Answers0