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!
1 Answer 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())
answered Jul 6, 2020 at 6:34
spiridon_the_sun_rotator
1,0744 gold badges14 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
7 Comments
luw
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'.spiridon_the_sun_rotator
@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
luw
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
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().
Perry
This would be a better answer if you explained how the code you provided answers the question.
|
lang-py
cmap='gray'with your plot command.plt.plot(t, f(t), cmap="gray"), it reports error: 'Line2D' object has no property 'cmap' @MarkSetchell