3

I have a series of tiff images to load in Python.

First I use:

im=Image.open(*)

It loads and displays properly.

>>> im
PIL.TiffImagePlugin.TiffImageFile image mode=I;16 size=1408x1044 at 0x116154050
>>> type(im)
instance
>>> im.size
(1408, 1044)

Then I use:

imarray=numpy.array(im)

where

>>> imarray.shape
()
>>> imarray.size
1
>>> type(imarray)
numpy.ndarray
>>>  imarray
array(PIL.TiffImagePlugin.TiffImageFile image mode=I;16 size=1408x1044 at 0x116154050, dtype=object)

I have read this previous post and followed the instructions there, but I can't get imarray.shape and im.size to match.

9
  • 2
    This might have to do with your version of PIL. Have you tried the solutions suggested here? Commented Mar 18, 2015 at 19:11
  • If you're planning on doing any type of image manipulation I would suggest using OpenCV. They have Python bindings and make your life a lot easier including automatically converting the images into numpy arrays. Commented Mar 18, 2015 at 19:15
  • @KronoS OpenCV is massive overkill for simple image I/O. Pillow or even matplotlib offer much more lightweight solutions. Commented Mar 18, 2015 at 19:20
  • @ali_m I agree however if the OP is looking to do manipulation of the images, that's where the heavyweight of OpenCV comes into great usefulness. Commented Mar 18, 2015 at 19:23
  • @KronoS We don't yet know what the OP wants to actually do with the images, so I wouldn't jump straight to recommending OpenCV at this stage Commented Mar 18, 2015 at 19:28

2 Answers 2

3

Here is a solution that copies the data into the numpy array.

    from PIL import Image
    import numpy as np
    import ubelt as ub

    # Grab some test data
    fpath = ub.grabdata('http://www.topcoder.com/contest/problem/UrbanMapper3D/JAX_Tile_043_DTM.tif')

    # Open the tiff image
    pil_img = Image.open(fpath)

    # Map PIL mode to numpy dtype (note this may need to be extended)
    dtype = {'F': np.float32, 'L': np.uint8}[pil_img.mode]

    # Load the data into a flat numpy array and reshape
    np_img = np.array(pil_img.getdata(), dtype=dtype)
    w, h = pil_img.size
    np_img.shape = (h, w, np_img.size // (w * h))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this helped a lot. Please take into consideration that the dtype conversion dict is only partial, and may raise a KeyError in special cases. For example, my image's "mode" was "I;16", which translates to np.uint16.
Yes, hence the "may need to be extended" comment.
3

For TIFF image, you can simply use imageio

im = imageio.imread('filename')

Sometimes you might further need

im = np.array(im)

Comments

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.