7

Suppose that we have an RGB image that we have converted it to a Numpy array with the following code:

import numpy as np
from PIL import Image

img = Image.open('Peppers.tif')
arr = np.array(img) # 256x256x3 array

If we are interested in visualizing only the red channel, i.e. arr[:,:,0], how can we plot this 2D Numpy array?

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
A.M.
  • 1,757
  • 5
  • 22
  • 41

1 Answers1

8

You can use matplotlib's imshow():

import matplotlib.pyplot as plt
imgplot = plt.imshow(arr[:, :, 0])

see more examples here, for interpolation, colorbars, etc.

For example to change the colormap, you can do imgplot.set_cmap('hot'). Setting interpolation to 'nearest' is useful too, if you don't really want interpolation: see the differences

t = np.array([[0, 1, 2], [1, 2, 3], [3, 2, 1]])
import matplotlib.pyplot as plt
plt.imshow(t)
plt.show()
plt.imshow(t, interpolation='nearest')
plt.show()

results in enter image description here

and

enter image description here

P. Camilleri
  • 12,664
  • 7
  • 41
  • 76
  • Thanks. Do you know if there is anyway to fix the colormap for different channels like red, gree, blue? – A.M. Sep 01 '15 at 20:36
  • 2
    Also, you can use `img = plt.imread('Peppers.tif')` to read the image directly as a numpy array. – kikocorreoso Sep 01 '15 at 20:38