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]:
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]:
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]:
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]:
In [8]:
imsave('squirrelama.png', clustered, cmap=cmap)