0

I use pyplot to get the image. It seems like the default is color image, but I want to get the gray scale. I use the code below, however, I need to firstly save the color image before I get the gray scale image. Is there any way to show and save the gray scale image directly?

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

#downsampling
a = sound
R = 2
a=a.reshape(-1,R).mean(axis=1)

Pxx, freqs, bins, im = plt.specgram(a, NFFT=1024, Fs=44100/2, 
noverlap=900) #Fs be downsampling 
plt.savefig('sp_xyz.png')
image = Image.open('sp_xyz.png').convert("L")
arr = np.asarray(image)
plt.imshow(arr, cmap='gray_r')
Pelican
  • 43
  • 7
  • Why do you first save a matplotlib figure and then open it again? What is the figure you are saving with `plt.savefig`? Or rather what is it that you start with? (It's not shown in the code). – ImportanceOfBeingErnest Aug 10 '17 at 23:28
  • @ImportanceOfBeingErnest I edited it. It's a spectrogram. I don't want to save the color figure but I don't know how to get a gray scale figure without saving it and reading it again. – Pelican Aug 11 '17 at 05:09

1 Answers1

1

The question How can I convert an RGB image into grayscale in Python? shows different approaches on how to convert a numpy array to grayscale, either by direct manipulation of the array, or via PIL.

However in the case from the question here, you do not need to convert anything, since the spectrogram alread is an array with a single channel (hence a grayscale image).

It now depends on what you want to do. If you want to save the resulting array (Pxx) as an image, you may use

plt.imsave('sp_xyz.png', Pxx, cmap="gray")

If you want to save the spectrogram plotted into axes but with a gray colormap,

Pxx, freqs, bins, im = plt.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900, cmap="gray")
plt.savefig('sp_xyz.png')
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Thanks for your response! I don't know why the first one doesn't work, but the second one works pretty well. I use plt.axis('off') to make the axes disappear instead. – Pelican Aug 11 '17 at 20:47