Invertible STFT and ISTFT in Python

后端 未结 10 2054
自闭症患者
自闭症患者 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:19

    Neither of the above answers worked well OOTB for me. So I modified Steve Tjoa's.

    import scipy, pylab
    import numpy as np
    
    def stft(x, fs, framesz, hop):
        """
         x - signal
         fs - sample rate
         framesz - frame size
         hop - hop size (frame size = overlap + hop size)
        """
        framesamp = int(framesz*fs)
        hopsamp = int(hop*fs)
        w = scipy.hamming(framesamp)
        X = scipy.array([scipy.fft(w*x[i:i+framesamp]) 
                         for i in range(0, len(x)-framesamp, hopsamp)])
        return X
    
    def istft(X, fs, T, hop):
        """ T - signal length """
        length = T*fs
        x = scipy.zeros(T*fs)
        framesamp = X.shape[1]
        hopsamp = int(hop*fs)
        for n,i in enumerate(range(0, len(x)-framesamp, hopsamp)):
            x[i:i+framesamp] += scipy.real(scipy.ifft(X[n]))
        # calculate the inverse envelope to scale results at the ends.
        env = scipy.zeros(T*fs)
        w = scipy.hamming(framesamp)
        for i in range(0, len(x)-framesamp, hopsamp):
            env[i:i+framesamp] += w
        env[-(length%hopsamp):] += w[-(length%hopsamp):]
        env = np.maximum(env, .01)
        return x/env # right side is still a little messed up...
    

提交回复
热议问题