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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26929052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:11:00  来源:igfitidea点击:

how to save an array as a grayscale image with matplotlib/numpy?

pythonarraysimagenumpymatplotlib

提问by Mathieu Paurisse

I am trying to save a numpy array of dimensions 128x128 pixels into a grayscale image. I simply thought that the pyplot.imsave function would do the job but it's not, it somehow converts my array into an RGB image. I tried to force the colormap to Gray during conversion but eventhough the saved image appears in grayscale, it still has a 128x128x4 dimension. Here is a code sample I wrote to show the behaviour :

我正在尝试将尺寸为 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

In both cases the results of the "print" function are (128,128,4).

在这两种情况下,“打印”函数的结果都是 (128,128,4)。

Can anyone explain why the imsave function is creating those dimensions eventhough my input array is of a luminance type? And of course, does anyone have a solution to save the array into a standard grayscale format?

谁能解释为什么 imsave 函数会创建这些维度,即使我的输入数组是亮度类型?当然,有没有人有将数组保存为标准灰度格式的解决方案?

Thanks!

谢谢!

采纳答案by eickenberg

With PILit should work like this

有了PIL它应该像这样工作

import Image

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

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

回答by roy650

I didn't want to use PIL in my code and as noted in the question I ran into the same problem with pyplot, where even in grayscale, the file is saved in MxNx3 matrix.

我不想在我的代码中使用 PIL,并且如问题中所述,我遇到了与 pyplot 相同的问题,即使在灰度中,文件也保存在 MxNx3 矩阵中。

Since the actual image on disk wasn't important to me, I ended up writing the matrix as is and reading it back "as-is" using numpy's save and load methods:

由于磁盘上的实际图像对我来说并不重要,我最终按原样编写矩阵并使用 numpy 的保存和加载方法“原样”读取它:

np.save("filename", image_matrix)

And:

和:

np.load("filename.npy")