Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with TIFFs (import, export) in Python using numpy

I need a python method to open and import TIFF images into numpy arrays so I can analyze and modify the pixel data and then save them as TIFFs again. (They are basically light intensity maps in greyscale, representing the respective values per pixel)

I couldn't find any documentation on PIL methods concerning TIFF. I tried to figure it out, but only got "bad mode" or "file type not supported" errors.

What do I need to use here?

like image 671
Jakob Avatar asked Sep 27 '11 13:09

Jakob


People also ask

How do I read a TIFF metadata?

In the Windows operating system, this can be done as follows, open the "Explorer" application, find your TIFF document, right-click on the file, select the "Properties" option, you will see the document properties window TIFF and its metadata.


2 Answers

First, I downloaded a test TIFF image from this page called a_image.tif. Then I opened with PIL like this:

>>> from PIL import Image >>> im = Image.open('a_image.tif') >>> im.show() 

This showed the rainbow image. To convert to a numpy array, it's as simple as:

>>> import numpy >>> imarray = numpy.array(im) 

We can see that the size of the image and the shape of the array match up:

>>> imarray.shape (44, 330) >>> im.size (330, 44) 

And the array contains uint8 values:

>>> imarray array([[  0,   1,   2, ..., 244, 245, 246],        [  0,   1,   2, ..., 244, 245, 246],        [  0,   1,   2, ..., 244, 245, 246],        ...,         [  0,   1,   2, ..., 244, 245, 246],        [  0,   1,   2, ..., 244, 245, 246],        [  0,   1,   2, ..., 244, 245, 246]], dtype=uint8) 

Once you're done modifying the array, you can turn it back into a PIL image like this:

>>> Image.fromarray(imarray) <Image.Image image mode=L size=330x44 at 0x2786518> 
like image 73
jterrace Avatar answered Sep 28 '22 07:09

jterrace


I use matplotlib for reading TIFF files:

import matplotlib.pyplot as plt I = plt.imread(tiff_file) 

and I will be of type ndarray.

According to the documentation though it is actually PIL that works behind the scenes when handling TIFFs as matplotlib only reads PNGs natively, but this has been working fine for me.

There's also a plt.imsave function for saving.

like image 33
Michael Brennan Avatar answered Sep 28 '22 09:09

Michael Brennan