温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Display image as grayscale using matplotlib
matplotlib python grayscale

python - 使用matplotlib将图像显示为灰度

发布于 2020-03-27 11:23:53

我正在尝试使用matplotlib.pyplot.imshow()显示灰度图像我的问题是灰度图像显示为颜色图。我需要灰度,因为我想在图像上绘制颜色。

我读入图像并使用PIL的Image.open()。convert(“ L”)转换为灰度

image = Image.open(file).convert("L")

然后,我将图像转换为矩阵,以便可以轻松地使用

matrix = scipy.misc.fromimage(image, 0)

但是,当我这样做

figure()  
matplotlib.pyplot.imshow(matrix)  
show()

它使用颜色图(即不是灰度)显示图像。

我在这里做错了什么?

查看更多

查看更多

提问者
Ryan
被浏览
63
unutbu 2019-04-03 21:36

以下代码将从文件中加载图像image.png并将其显示为灰度。

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

fname = 'image.png'
image = Image.open(fname).convert("L")
arr = np.asarray(image)
plt.imshow(arr, cmap='gray', vmin=0, vmax=255)
plt.show()

如果要显示反灰度,请将cmap切换为cmap='gray_r'