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

标签 python numpy matplotlib scipy

我正在尝试对图像运行 DCT 变换。我尝试使用以下代码将图像设为灰度图像:

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

但是我收到了图像,但它的颜色 channel 没有改变。我是否做错了什么或者我应该改变什么?

最佳答案

数组 im可能是一个 3-D 数组,形状为 (m, n, 3)(m, n, 4) 。检查im.shape .

来自 imshow 文档字符串:“如果 X 是 3-D,则忽略 cmap

要使用颜色图,您必须将二维数组传递给 imshow 。例如,您可以绘制颜色 channel 之一,例如 im[:,:,0] ,或绘制三个 channel 的平均值,im.mean(axis=2) 。 (但如果 im 的形状为 (m, n, 4) ,您可能不希望在平均值中包含 alpha channel 。)

关于python - 为什么 plt.imshow(im, cmap ='gray' ) 不显示灰度图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46739739/

相关文章:

python - 如何将 sklearn fit_transform 与 Pandas 一起使用并返回数据帧而不是 numpy 数组?

Python - 绘制大量线条

python - Matplotlib - 如何用海岸线和国家叠加等高线图

python - PyGame:每次移动鼠标时计时器都会重置

python - requests.post() 的 CSRF 验证失败

python - Django 模板中的编码问题

python - 高效/优雅地将方法应用于对象的 numpy ndarray 或从中获取属性

python - 使用 NumPy 查找条件为 True 的范围

python - 如何在不改变绘图的情况下更改 matplotlib 中的图形 Canvas 大小?

python - "Play"未定义 - Pylance (reportUndefinedVariable)