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

发布于 2021-01-29 16:08:53

我正在尝试将尺寸为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函数仍会创建这些尺寸?当然,有人可以将阵列保存为标准灰度格式吗?

谢谢!

关注者
0
被浏览
155
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    PIL它应该像这样工作

    import Image
    
    I8 = (((I - I.min()) / (I.max() - I.min())) * 255.9).astype(np.uint8)
    
    img = Image.fromarray(I8)
    img.save("file.png")
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看