Image visualization

The last possible visualization that we explore using matplotlib has to do with images. Resorting to plt.imgshow is useful when you are working with image data. Let's take as an example the Olivetti dataset, an open source set of images of 40 people who provided 10 images of themselves at different times (and with different expressions, a fact that makes it more challenging for testing face recognition algorithms). The images from this dataset are provided as feature vectors of pixel intensities. Therefore, it is important to reshape the vectors in order to make them resemble a matrix of pixels. Setting the interpolation to 'nearest' helps to smooth the picture:

In: from sklearn.datasets import fetch_olivetti_faces
import numpy as np
import matplotlib.pyplot as plt
dataset = fetch_olivetti_faces(shuffle=True, random_state=5)
photo = 1
for k in range(6):
plt.subplot(2, 3, k+1)
plt.imshow(dataset.data[k].reshape(64, 64),
cmap=plt.cm.gray,
interpolation='nearest')
plt.title('subject '+str(dataset.target[k]))
plt.axis('off')
plt.show()

A complete panel of images will be plotted:

We can also visualize handwritten digits or letters. In our example, we will plot the first nine digits from the scikit-learn handwritten digit dataset and set the extent of both the axes (by using the extent parameter and providing a list of minimum and maximum values) to align the grid to the pixels:

In: from sklearn.datasets import load_digits
digits = load_digits()
for number in range(1,10):
fig = plt.subplot(3, 3, number)
fig.imshow(digits.images[number],
cmap='binary',
interpolation='none',
extent=[0,8,0,8])
fig.set_xticks(np.arange(0, 9, 1))
fig.set_yticks(np.arange(0, 9, 1))
fig.grid()
plt.show()

A simple close-up on a single number can be obtained by printing only one image:

In: plt.imshow(digits.images[0],
cmap='binary',
interpolation='none',
extent=[0,8,0,8])
# Extent defines the images max and min
# of the horizontal and vertical values
plt.grid()

The resulting image clearly highlights how pixels constitute the image and their gray levels:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset