Reputation: 217
I am using matplotlib to plot function graphs, say, a sine function:
t = np.arange(0., 5., 0.2)
plt.plot(t, np.sin(t))
but it has 3 channels. How should I make a gray image (with only one channel) and save it as a numpy array with shape height * width * 1. Thank you!
Upvotes: 0
Views: 495
Reputation: 1054
With the use of skimage library there is possible pipeline (it is still rather heavyweight, but now the quality of the image would be much better).
#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())
Upvotes: 1