我正在尝试将尺寸为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
在这两种情况下,“打印”功能的结果均为(128,128,4)。
谁能解释为什么即使我的输入数组是亮度类型,imsave函数仍会创建这些尺寸?当然,有人可以将阵列保存为标准灰度格式吗?
谢谢!
用PIL
它应该像这样工作
import Image
I8 = (((I - I.min()) / (I.max() - I.min())) * 255.9).astype(np.uint8)
img = Image.fromarray(I8)
img.save("file.png")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句