gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:16:54 25 4
gpt4 key购买 nike

我正在尝试使用 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()

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

我在这里做错了什么?

最佳答案

以下代码将从文件 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'

关于python - 使用 matplotlib 将图像显示为灰度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3823752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com