0

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!

luw
  • 207
  • 3
  • 14

1 Answers1

1

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())
  • Where should I use ```cmap='gray'```? When I try ```plt.plot(t, f(t), cmap="gray")```, it reports error: 'Line2D' object has no property 'cmap'. – luw Jul 06 '20 at 06:45
  • @luw, sorry I didn't not initially caught, what you wanted. The issue seems more complicated. I have come up to a mad solution, but working – spiridon_the_sun_rotator Jul 06 '20 at 07:19
  • Hi, what I want to have is to store a grayscale plot as numpy array with shape height * width * 1. I have tried your code, but when I save it ```plt.savefig('filename')``` and use cv2.imread to read it, it turns out that the saved array still has shape (288, 432, 3). – luw Jul 06 '20 at 07:33
  • I understand your idea now, directly using a 0-1 np array to represent the plot, it's a good idea, although the plot might not be as accurate as plt.plot(). – luw Jul 06 '20 at 07:53
  • @luw, sorry, I have corrected the answer, saving it not with plt but np as **.npy** binary file. It would be manifestly one-channel. – spiridon_the_sun_rotator Jul 06 '20 at 11:26
  • 1
    This would be a better answer if you explained how the code you provided answers the question. – pppery Jul 06 '20 at 19:26
  • @pppery you're right, I've come with silghtly a better solution, and added explaining comments – spiridon_the_sun_rotator Jul 07 '20 at 06:50