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

5
  • 2
    did you mean to put imarray[i,k,j] = np.float64(img.getpixel((j,i))) ? Commented Jul 7, 2018 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 Commented Jul 7, 2018 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. Commented Jul 7, 2018 at 21:20
  • see also stackoverflow.com/a/47836289/982257 for a more efficient way to do this. Commented Jul 7, 2018 at 21:29
  • 1
    Possible duplicate of Load a tiff stack in a numpy array with python Commented Jul 7, 2018 at 21:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.