Invertible STFT and ISTFT in Python

后端 未结 10 2013
自闭症患者
自闭症患者 2020-12-02 07:57

Is there any general-purpose form of short-time Fourier transform with corresponding inverse transform built into SciPy or NumPy or whatever?

There\'s the pyplot

10条回答
  •  醉梦人生
    2020-12-02 08:25

    A fixed version of basj's answer.

    import scipy, numpy as np
    import matplotlib.pyplot as plt
    
    def stft(x, fftsize=1024, overlap=4):
        hop=fftsize//overlap
        w = scipy.hanning(fftsize+1)[:-1]      # better reconstruction with this trick +1)[:-1]  
        return np.vstack([np.fft.rfft(w*x[i:i+fftsize]) for i in range(0, len(x)-fftsize, hop)])
    
    def istft(X, overlap=4):   
        fftsize=(X.shape[1]-1)*2
        hop=fftsize//overlap
        w=scipy.hanning(fftsize+1)[:-1]
        rcs=int(np.ceil(float(X.shape[0])/float(overlap)))*fftsize
        print(rcs)
        x=np.zeros(rcs)
        wsum=np.zeros(rcs)
        for n,i in zip(X,range(0,len(X)*hop,hop)): 
            l=len(x[i:i+fftsize])
            x[i:i+fftsize] += np.fft.irfft(n).real[:l]   # overlap-add
            wsum[i:i+fftsize] += w[:l]
        pos = wsum != 0
        x[pos] /= wsum[pos]
        return x
    
    a=np.random.random((65536))
    b=istft(stft(a))
    plt.plot(range(len(a)),a,range(len(b)),b)
    plt.show()
    

提交回复
热议问题