使用matplotlib将图像显示为灰度 [英] Display image as grayscale using matplotlib
问题描述
我正在尝试使用 matplotlib.pyplot.imshow()显示灰度图像.我的问题是灰度图像显示为颜色图.我需要灰度,因为我想在颜色上绘制图像.
I'm trying to display a grayscale image using matplotlib.pyplot.imshow(). My problem is that the grayscale image is displayed as a colormap. I need the grayscale because I want to draw on top of the image with color.
我读入图像并使用 PIL的Image.open().convert("L")
image = Image.open(file).convert("L")
然后我将图像转换为矩阵,以便可以使用
Then I convert the image to a matrix so that I can easily do some image processing using
matrix = scipy.misc.fromimage(image, 0)
但是,当我这样做
figure()
matplotlib.pyplot.imshow(matrix)
show()
它使用彩色地图(即不是灰度)显示图像.
it displays the image using a colormap (i.e. it's not grayscale).
我在做什么错了?
推荐答案
以下代码将从文件image.png
中加载图像并将其显示为灰度.
The following code will load an image from a file image.png
and will display it as grayscale.
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'
.
If you want to display the inverse grayscale, switch the cmap to cmap='gray_r'
.
这篇关于使用matplotlib将图像显示为灰度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!