Introduction to Matplotlib for image data
This second part introduces matplotlib, a Python library for plotting numpy arrays as images.
%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
arr = np.arange(100).reshape(10,10)
print(arr)
plt.imshow(arr)
from check_answer import check_answer
answ = np.arange(?).reshape(?)
plt.imshow(answ)
check_answer("2.1", answ.sum())
arr = np.arange(100).reshape(10,10)
arr[:, :5] = 1
plt.imshow(arr)
Note: We have selected all the values
:
in the first axis (vertical) and the first 5 values :5
on the second axis (horizontal)
answ = np.arange(100).reshape(10,10)
answ[?] = 1
plt.imshow(answ)
check_answer("2.2", answ.sum())
answ = np.arange(100).reshape(10,10)
answ = ?
plt.imshow(answ)
check_answer("2.3", answ.sum())
We can use the Pyplot library to load an image using the matplotlib function imread
. The image that we get is a 3-dimensional numpy array. By convention the first dimension corresponds to the vertical axis, the second to the horizontal axis and the third are the Red, Green and Blue channels of the image.
im = np.copy(plt.imread('data/black_mountain_fire.jpg'))
im.shape
answ = im.?
check_answer("2.4", answ)
plt.imshow(im)
answ = im[?]
plt.imshow(answ)
check_answer("2.5", answ.mean())
answ = im[?]
plt.imshow(answ)
im[0,0]
The first value corresponds to the red component, the second to the green and the third to the blue. uint8
can contain values in the range [0-255]
so the pixel is mostly blue, which makes sense for a pixel representing the sky.
Now let's modify the image. What happens if we set all the values representing the green channel to the maximum value?
# We first make a copy to avoid modifying the original image.
im2 = np.copy(im)
im2[:,:,1] = 255
plt.imshow(im2)
Exercise 2.7: Could you create an artistic representation of the previous image saturating different parts of the image with different colours? We want the top-left quadrant with the red channel saturated, the top-right with the green channel satured, the bottom-left with the blue channel saturated and the bottom-right as it is.
im2 = np.copy(im)
im2[?] = 255
im2[?] = 255
im2[?] = 255
plt.imshow(im2)