如何绘制灰度图像并保存?

How to plot a gray image and save it?

我正在使用 matplotlib 绘制函数图,比如正弦函数:

t = np.arange(0., 5., 0.2)
plt.plot(t, np.sin(t))

但它有 3 个频道。我应该如何制作一张灰色图像(只有一个通道)并将其保存为形状为高度 * 宽度 * 1 的 numpy 数组。谢谢!

使用skimage library有可能的管道(它仍然是相当重量级的,但现在图像的质量会好得多)。

#import the required libraries and functions
import os
from skimage.io import imread
from skimage.color import rgb2gray, rgba2rgb

#create an image
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
plt.plot(x, y)

#save and image as a .png picture and then load 
plt.savefig('img.png')
img = imread('img.png')
#we do not need the colored picture, so remove it
os.remove('img.png')

#the loaded picture is initially rgba, convert it to the grayscale image
img = rgb2gray(rgba2rgb(img))
#if you want a flat array saved as binary, ravel() it and use np.save
np.save('test.npy', img.ravel())