如何使用matplotlib/numpy将数组保存为灰度图像?

2024-04-19 12:44:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将一个尺寸为128x128像素的numpy数组保存为灰度图像。 我只是简单地认为pyplot.imsave函数可以完成这项工作,但事实并非如此,它以某种方式将我的数组转换为RGB图像。 我试图在转换过程中将颜色映射强制为灰色,但即使保存的图像以灰度显示,它仍具有128x128x4的维度。 下面是我编写的一个代码示例,用于显示行为:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mplimg
from matplotlib import cm

x_tot = 10e-3
nx = 128

x = np.arange(-x_tot/2, x_tot/2, x_tot/nx)

[X, Y] = np.meshgrid(x,x)
R = np.sqrt(X**2 + Y**2)

diam = 5e-3
I = np.exp(-2*(2*R/diam)**4)

plt.figure()
plt.imshow(I, extent = [-x_tot/2, x_tot/2, -x_tot/2, x_tot/2])

print I.shape

plt.imsave('image.png', I)
I2 = plt.imread('image.png')
print I2.shape

mplimg.imsave('image2.png',np.uint8(I), cmap = cm.gray)
testImg = plt.imread('image2.png')
print testImg.shape

在这两种情况下,“打印”功能的结果都是(128128,4)。

有人能解释为什么imsave函数会在我的输入数组是亮度类型的情况下创建这些维度吗? 当然,有没有办法把数组保存成标准的灰度格式?

谢谢!


Tags: 图像imageimportnumpypngmatplotlibasnp
2条回答

我不想在我的代码中使用PIL,正如在问题中提到的,我遇到了pyplot的相同问题,即使是灰度的,文件也保存在MxNx3 matrix中。

因为磁盘上的实际图像对我来说并不重要,所以我最终还是按原样编写了矩阵,并按原样使用numpy的保存和加载方法将其读取回来:

np.save("filename", image_matrix)

以及:

np.load("filename.npy")

使用PIL它应该像这样工作

import Image

I8 = (((I - I.min()) / (I.max() - I.min())) * 255.9).astype(np.uint8)

img = Image.fromarray(I8)
img.save("file.png")

相关问题 更多 >