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

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

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, its 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 youre 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>
``````

I use matplotlib for reading TIFF files:

``````import matplotlib.pyplot as plt
``````

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.

Theres also a `plt.imsave` function for saving.

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

You could also use GDAL to do this. I realize that it is a geospatial toolkit, but nothing requires you to have a cartographic product.

Link to precompiled GDAL binaries for windows (assuming windows here)
http://www.gisinternals.com/sdk/

To access the array:

``````from osgeo import gdal