DeJurnett Norrington
DeJurnett Norrington

Reputation: 41

Why does plt.imshow(im, cmap='gray') not show a grayscale image?

I am attempting to run a DCT transform on an image. I have tried to make my image a grayscale image with the following code:

import numpy as np
import matplotlib.pyplot as plt
import scipy

from numpy import pi
from numpy import sin
from numpy import zeros
from numpy import r_
from scipy import signal
from scipy import misc
import matplotlib.pylab as pylab

#matplotlib inline
pylab.rcParams['figure.figsize'] = (20.0, 7.0)

im = misc.imread("indoorPictureResize.jpg")

#show the image
f = plt.figure()
plt.imshow(im,cmap='gray')
plt.show()

However I receive the image but it's color channel has not changed. Have I done something wrong or is it something I should change?

Upvotes: 4

Views: 19602

Answers (2)

Warren Weckesser
Warren Weckesser

Reputation: 114811

The array im is probably a 3-D array, with shape (m, n, 3) or (m, n, 4). Check im.shape.

From the imshow docstring: "cmap is ignored if X is 3-D".

To use a colormap, you'll have to pass a 2-D array to imshow. You could, for example, plot one of the color channels such as im[:,:,0], or plot the average over the three channels, im.mean(axis=2). (But if im has shape (m, n, 4), you probably don't want to include the alpha channel in the mean.)

Upvotes: 6

Tiny.D
Tiny.D

Reputation: 6556

Add the mode in scipy.misc.imread like this:

import numpy as np
import matplotlib.pyplot as plt
import scipy

from numpy import pi
from numpy import sin
from numpy import zeros
from numpy import r_
from scipy import signal
from scipy import misc
import matplotlib.pylab as pylab

#matplotlib inline
pylab.rcParams['figure.figsize'] = (20.0, 7.0)

im = misc.imread("indoorPictureResize.jpg", mode="L")

#show the image
f = plt.figure()
plt.imshow(im,cmap='gray')
plt.show()

Upvotes: 0

Related Questions