x是一个numpy.float32数组,其值为-200到0.这些是dB(分贝)值.
当我这样做(推荐here):
Image.fromarray(x, mode='F')
我得到一个灰度或有时几乎是黑色的图像.
如何将[-200,0]中的浮点映射到24位RGB字节数组(使用色彩映射),可以使用带有Image.fromarray(x,mode =’RGB’)的Python模块PIL读取?
编辑:
所需的.wav音频文件是here,我们要为其绘制spectrogram.
这是一些要测试的代码:
import scipy, numpy as np
import scipy.io.wavfile as wavfile
import numpy as np
from PIL import Image
def stft(x, fftsize=1024, overlap=4):
hop = fftsize / overlap
w = scipy.hanning(fftsize+1)[:-1]
return np.array([np.fft.rfft(w*x[i:i+fftsize]) for i in range(0, len(x)-fftsize, hop)])
def dB(ratio):
return 20 * np.log10(ratio+1e-10)
def magnitudedB(frame, fftsize=1024):
w = scipy.hanning(fftsize+1)[:-1]
ref = np.sum(w) / 2
return dB(np.abs(frame) / ref)
sr, x = wavfile.read('test.wav')
x = np.float32(x) / 2**15
s = magnitudedB(stft(x)).astype(np.float32).transpose()[::-1,]
print "Max %.1f dB, Min %.1f dB" % (np.max(s), np.min(s))
im = Image.fromarray(s+200, mode='F')
im.show()
笔记:
> colormap是灰度,如何获得另一个colormap?像this one
>我唯一的要求是输出图像可以读入Tkinter帧/画布(它适用于PIL的im = Image.fromarray(…),然后是ImageTk.PhotoImage(image = im))或wxPython帧/画布.