使用 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") 转换为灰度
I read in the image and convert to grayscale using PIL's 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屋!