简体   繁体   中英

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?

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.)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM