简体   繁体   English

为什么plt.imshow(im,cmap ='gray')不显示灰度图像?

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

I am attempting to run a DCT transform on an image. 我正在尝试在图像上运行DCT转换。 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) . 数组im可能是形状为(m, n, 3)(m, n, 4)的3-D数组。 Check im.shape . 检查im.shape

From the imshow docstring: " cmap is ignored if X is 3-D" . imshow文档字符串中: “如果X为3-D,则忽略cmap

To use a colormap, you'll have to pass a 2-D array to imshow . 要使用颜色图,您必须将2-D数组传递给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) . 例如,您可以绘制颜色通道之一,例如im[:,:,0] ,或绘制三个通道的平均值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.) (但是,如果im形状为(m, n, 4) ,则您可能不想在平均值中包含alpha通道。)

Add the mode in scipy.misc.imread like this: 像这样在scipy.misc.imread中添加mode

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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