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!

asked Jul 6, 2020 at 6:12
5
  • What do you mean by channel? Commented Jul 6, 2020 at 6:14
  • It's colorful. So I think it has RGB channels. @Bill Commented Jul 6, 2020 at 6:16
  • Try cmap='gray' with your plot command. Commented Jul 6, 2020 at 6:28
  • Possible duplicate. Commented Jul 6, 2020 at 6:30
  • When I try plt.plot(t, f(t), cmap="gray"), it reports error: 'Line2D' object has no property 'cmap' @MarkSetchell Commented Jul 6, 2020 at 6:43

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

7 Comments

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, 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
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).
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().
This would be a better answer if you explained how the code you provided answers the question.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.