Chapter 4, example 5

Here we show a few examples of image processing routines with Matplotlib, SciPy and PIL.

We first download a PNG image, and we open it with Matplotlib.


In [1]:
import urllib2
png = urllib2.urlopen('http://ipython.rossant.net/squirrel.png')
im = imread(png)
im.shape


Out[1]:
(300, 300, 3)

We convert it into a PIL image.


In [2]:
from PIL import Image
img = Image.fromarray((im*255).astype('uint8'))

We can show the image in the notebook thanks to Matplotlib.


In [3]:
imshow(im)


Out[3]:
<matplotlib.image.AxesImage at 0x59ae230>

A colored image contains three channels: red, green and blue.


In [4]:
figure(figsize=(10,6))
cmaps = ['Reds', 'Greens', 'Blues']
for i in xrange(3):
    subplot(1, 3, i + 1)
    imshow(im[:,:,i], cmap=get_cmap(cmaps[i]))


PIL implements several basic image processing routines.


In [5]:
imshow(array(img.rotate(45.)))


Out[5]:
<matplotlib.image.AxesImage at 0x6159130>

Here, we show a more advanced image processing algorithm: color quantization. We use SciPy to cluster the pixels into a few groups of colors.


In [6]:
from scipy.cluster.vq import *
M = im[:,:,0].ravel()
# centroids contains four color clusters in the image
centroids, _ = kmeans(M, 4)
# we associate each pixel to one of the four colors (qnt is in array of integer indices)
qnt, _ = vq(M, centroids)
# finally we obtain the quantized image through fancy indexing
clustered = centroids[reshape(qnt, (300, 300))]

We can plot the obtained grayscale image with a custom color map.


In [7]:
cmap = matplotlib.colors.ListedColormap([(0,.2,.3), (.85,.1,.13), (.44,.6,.6), (1.,.9,.65)])
imshow(clustered, cmap=cmap)


Out[7]:
<matplotlib.image.AxesImage at 0x5dfb870>

In [8]:
imsave('squirrelama.png', clustered, cmap=cmap)