我正在尝试将一个尺寸为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函数会在我的输入数组是亮度类型的情况下创建这些维度吗?
当然,有没有办法把数组保存成标准的灰度格式?
谢谢!