Python scipy.signal.hann() Examples

The following are 12 code examples of scipy.signal.hann(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module scipy.signal , or try the search function .
Example #1
Source File: first_peaks_method.py    From Automated_Music_Transcription with MIT License 5 votes vote down vote up
def STFT(self, x, samplingFreq, framesz, hop):
        """
            Computes STFT for a given sound wave using Hanning window.
        """

        framesamp = int(framesz * samplingFreq)
        print 'FRAMESAMP: ' + str(framesamp)
        hopsamp = int(hop * samplingFreq)
        print 'HOP SAMP: ' + str(hopsamp)
        # Modification: using Hanning window instead of Hamming - by Pertusa
        w = signal.hann(framesamp)
        X = numpy.array([numpy.fft.fft(w * x[i:i + framesamp])
                         for i in range(0, len(x) - framesamp, hopsamp)])
        return X 
Example #2
Source File: least_squares_first_peaks_2.py    From Automated_Music_Transcription with MIT License 5 votes vote down vote up
def STFT(self, x, samplingFreq, framesz, hop):
        """
            Computes STFT for a given sound wave using Hanning window.
        """

        framesamp = int(framesz * samplingFreq)
        print 'FRAMESAMP: ' + str(framesamp)
        hopsamp = int(hop * samplingFreq)
        print 'HOP SAMP: ' + str(hopsamp)
        # Modification: using Hanning window instead of Hamming - by Pertusa
        w = signal.hann(framesamp)
        X = numpy.array([numpy.fft.fft(w * x[i:i + framesamp])
                         for i in range(0, len(x) - framesamp, hopsamp)])
        return X 
Example #3
Source File: scale_filter.py    From pyECO with MIT License 5 votes vote down vote up
def __init__(self, target_sz, ):
        init_target_sz = target_sz
        num_scales = config.number_of_scales_filter
        scale_step = config.scale_step_filter
        scale_sigma = config.number_of_interp_scales * config.scale_sigma_factor

        scale_exp = np.arange(-np.floor(num_scales - 1)/2,
                              np.ceil(num_scales-1)/2+1,
                              dtype=np.float32) * config.number_of_interp_scales / num_scales
        scale_exp_shift = np.roll(scale_exp, (0, -int(np.floor((num_scales-1)/2))))

        interp_scale_exp = np.arange(-np.floor((config.number_of_interp_scales-1)/2),
                                     np.ceil((config.number_of_interp_scales-1)/2)+1,
                                     dtype=np.float32)
        interp_scale_exp_shift = np.roll(interp_scale_exp, [0, -int(np.floor(config.number_of_interp_scales-1)/2)])

        self.scale_size_factors = scale_step ** scale_exp
        self.interp_scale_factors = scale_step ** interp_scale_exp_shift

        ys = np.exp(-0.5 * (scale_exp_shift ** 2) / (scale_sigma ** 2))
        self.yf = np.real(fft(ys))[np.newaxis, :]
        self.window = signal.hann(ys.shape[0])[np.newaxis, :].astype(np.float32)

        # make sure the scale model is not to large, to save computation time
        if config.scale_model_factor**2 * np.prod(init_target_sz) > config.scale_model_max_area:
            scale_model_factor = np.sqrt(config.scale_model_max_area / np.prod(init_target_sz))
        else:
            scale_model_factor = config.scale_model_factor

        # set the scale model size
        self.scale_model_sz = np.maximum(np.floor(init_target_sz * scale_model_factor), np.array([8, 8]))
        self.max_scale_dim = config.s_num_compressed_dim == 'MAX'
        if self.max_scale_dim:
            self.s_num_compressed_dim = len(self.scale_size_factors)

        self.num_scales = num_scales
        self.scale_step = scale_step
        self.scale_factors = np.array([1]) 
Example #4
Source File: spectral.py    From auDeep with GNU General Public License v3.0 5 votes vote down vote up
def power_spectrum(signal: np.ndarray,
                   fs: int,
                   window_width: int,
                   window_overlap: int) -> (np.ndarray, np.ndarray, np.ndarray):
    """
    Computes the power spectrum of the specified signal.
    
    A periodic Hann window with the specified width and overlap is used.
    
    Parameters
    ----------
    signal: numpy.ndarray
        The input signal
    fs: int
        Sampling frequency of the input signal
    window_width: int
        Width of the Hann windows in samples
    window_overlap: int
        Overlap between Hann windows in samples

    Returns
    -------
    f: numpy.ndarray
        Array of frequency values for the first axis of the returned spectrogram
    t: numpy.ndarray
        Array of time values for the second axis of the returned spectrogram
    sxx: numpy.ndarray
        Power spectrogram of the input signal with axes [frequency, time]
    """
    f, t, sxx = spectrogram(x=signal,
                            fs=fs,
                            window=hann(window_width, sym=False),
                            noverlap=window_overlap,
                            mode="magnitude")

    return f, t, (1.0 / window_width) * (sxx ** 2) 
Example #5
Source File: utils.py    From time-domain-neural-audio-style-transfer with Apache License 2.0 5 votes vote down vote up
def chop(signal, hop_size=256, frame_size=512):
    n_hops = len(signal) // hop_size
    frames = []
    hann_win = hann(frame_size)
    for hop_i in range(n_hops):
        frame = signal[(hop_i * hop_size):(hop_i * hop_size + frame_size)]
        frame = np.pad(frame, (0, frame_size - len(frame)), 'constant')
        frame *= hann_win
        frames.append(frame)
    frames = np.array(frames)
    return frames 
Example #6
Source File: timedomain.py    From time-domain-neural-audio-style-transfer with Apache License 2.0 5 votes vote down vote up
def chop(signal, hop_size=256, frame_size=512):
    n_hops = len(signal) // hop_size
    s = []
    hann_win = hann(frame_size)
    for hop_i in range(n_hops):
        frame = signal[(hop_i * hop_size):(hop_i * hop_size + frame_size)]
        frame = np.pad(frame, (0, frame_size - len(frame)), 'constant')
        frame *= hann_win
        s.append(frame)
    s = np.array(s)
    return s 
Example #7
Source File: scale_filter.py    From pyCFTrackers with MIT License 5 votes vote down vote up
def __init__(self, target_sz,config):
        init_target_sz = target_sz
        self.config=config
        num_scales = self.config.number_of_scales_filter
        scale_step = self.config.scale_step_filter
        scale_sigma = self.config.number_of_interp_scales * self.config.scale_sigma_factor

        scale_exp = np.arange(-np.floor(num_scales - 1)/2,
                              np.ceil(num_scales-1)/2+1,
                              dtype=np.float32) * self.config.number_of_interp_scales / num_scales
        scale_exp_shift = np.roll(scale_exp, (0, -int(np.floor((num_scales-1)/2))))

        interp_scale_exp = np.arange(-np.floor((self.config.number_of_interp_scales - 1) / 2),
                                     np.ceil((self.config.number_of_interp_scales - 1) / 2) + 1,
                                     dtype=np.float32)
        interp_scale_exp_shift = np.roll(interp_scale_exp, [0, -int(np.floor(self.config.number_of_interp_scales - 1) / 2)])

        self.scale_size_factors = scale_step ** scale_exp
        self.interp_scale_factors = scale_step ** interp_scale_exp_shift

        ys = np.exp(-0.5 * (scale_exp_shift ** 2) / (scale_sigma ** 2))
        self.yf = np.real(fft(ys))[np.newaxis, :]
        self.window = signal.hann(ys.shape[0])[np.newaxis, :].astype(np.float32)

        # make sure the scale model is not to large, to save computation time
        if self.config.scale_model_factor**2 * np.prod(init_target_sz) > self.config.scale_model_max_area:
            scale_model_factor = np.sqrt(self.config.scale_model_max_area / np.prod(init_target_sz))
        else:
            scale_model_factor = self.config.scale_model_factor

        # set the scale model size
        self.scale_model_sz = np.maximum(np.floor(init_target_sz * scale_model_factor), np.array([8, 8]))
        self.max_scale_dim = self.config.s_num_compressed_dim == 'MAX'
        if self.max_scale_dim:
            self.s_num_compressed_dim = len(self.scale_size_factors)

        self.num_scales = num_scales
        self.scale_step = scale_step
        self.scale_factors = np.array([1]) 
Example #8
Source File: transforms.py    From seizure-detection with MIT License 5 votes vote down vote up
def apply(self, data):
        axis = data.ndim - 1
        out = resample(data, self.f, axis=axis, window=hann(M=data.shape[axis]))
        return out 
Example #9
Source File: utils.py    From setk with Apache License 2.0 5 votes vote down vote up
def inverse_stft(stft_mat,
                 frame_len=1024,
                 frame_hop=256,
                 center=False,
                 window="hann",
                 transpose=True,
                 norm=None,
                 power=None,
                 nsamps=None):
    """
    iSTFT wrapper, using librosa
    """
    if transpose:
        stft_mat = np.transpose(stft_mat)
    if window == "sqrthann":
        window = ss.hann(frame_len, sym=False)**0.5
    # orignal istft accept stft result(matrix, shape as FxT)
    samps = librosa.istft(stft_mat,
                          frame_hop,
                          win_length=frame_len,
                          window=window,
                          center=center,
                          length=nsamps)
    # keep same amplitude
    if norm:
        samps_norm = np.linalg.norm(samps, np.inf)
        samps = samps * norm / (samps_norm + EPSILON)
    # keep same power
    if power:
        samps_pow = np.linalg.norm(samps, 2)**2 / samps.size
        samps = samps * np.sqrt(power / samps_pow)
    return samps 
Example #10
Source File: utils.py    From setk with Apache License 2.0 5 votes vote down vote up
def griffin_lim(mag,
                frame_len=1024,
                frame_hop=256,
                round_power_of_two=True,
                window="hann",
                center=True,
                transpose=True,
                norm=None,
                epoches=30):
    """
    Griffin Lim Algothrim
    """
    # TxF -> FxT
    if transpose:
        mag = np.transpose(mag)
    n_fft = nextpow2(frame_len) if round_power_of_two else frame_len
    stft_kwargs = {
        "hop_length": frame_hop,
        "win_length": frame_len,
        "window": window,
        "center": center
    }
    phase = np.exp(2j * np.pi * np.random.rand(*mag.shape))
    samps = librosa.istft(mag * phase, **stft_kwargs)
    for _ in range(epoches):
        stft_mat = librosa.stft(samps, n_fft=n_fft, **stft_kwargs)
        phase = np.exp(1j * np.angle(stft_mat))
        samps = librosa.istft(mag * phase, **stft_kwargs)
    if norm:
        samps_norm = np.linalg.norm(samps, np.inf)
        samps = samps * norm / (samps_norm + EPSILON)
    return samps 
Example #11
Source File: spectrogram.py    From Speaker-Recognition with MIT License 4 votes vote down vote up
def stft(signal, fs, nfft, overlap):

    #plotting time domain signal
    plt.figure(1)
    t = np.arange(0,len(signal)/fs, 1/fs)
    plt.plot(t,signal)
    plt.axis(xmax = 1)
    plt.xlabel('Time in seconds')
    plt.ylabel('Amplitude')
    plt.title('Speech signal')
    
    if not np.log2(nfft).is_integer():
        nfft = nearestPow2(nfft)
    slength = len(signal)
    hop_size = np.int32(overlap * nfft)
    nFrames = int(np.round(len(signal)/(nfft-hop_size)))
    #zero padding to make signal length long enough to have nFrames
    signal = np.append(signal, np.zeros(nfft))
    STFT = np.empty((nfft, nFrames))
    segment = np.zeros(nfft)
    start = 0
    
    for n in range(nFrames):
        segment = signal[start:start+nfft] * hann(nfft) 
        padded_seg = np.append(segment,np.zeros(nfft))
        spec = fftshift(fft(padded_seg))
        spec = spec[len(spec)/2:]
        spec = abs(spec)/max(abs(spec))
        powerspec = 20*np.log10(spec)
        STFT[:,n] = powerspec
        start = start + nfft - hop_size 
        
    #plot spectrogram
    plt.figure(2)
    freq = (fs/(2*nfft)) * np.arange(0,nfft,1)
    time = np.arange(0,nFrames)*(slength/(fs*nFrames))
    plt.imshow(STFT, extent = [0,max(time),0,max(freq)],origin='lower', cmap='jet', interpolation='nearest', aspect='auto')
    plt.ylabel('Frequency in Hz')
    plt.xlabel('Time in seconds')
    plt.axis([0,max(time),0,np.max(freq)])
    plt.title('Spectrogram of speech')
    plt.show()
    return (STFT, time, freq) 
Example #12
Source File: utils.py    From setk with Apache License 2.0 4 votes vote down vote up
def forward_stft(samps,
                 frame_len=1024,
                 frame_hop=256,
                 round_power_of_two=True,
                 center=False,
                 window="hann",
                 apply_abs=False,
                 apply_log=False,
                 apply_pow=False,
                 transpose=True):
    """
    STFT wrapper, using librosa
    """
    if apply_log and not apply_abs:
        warnings.warn("Ignore apply_abs=False because apply_log=True")
        apply_abs = True
    if samps.ndim != 1:
        raise RuntimeError("Invalid shape, librosa.stft accepts mono input")
    # pad fft size to power of two or left it same as frame length
    n_fft = nextpow2(frame_len) if round_power_of_two else frame_len
    if window == "sqrthann":
        window = ss.hann(frame_len, sym=False)**0.5
    # orignal stft accept samps(vector) and return matrix shape as F x T
    # NOTE for librosa.stft:
    # 1) win_length <= n_fft
    # 2) if win_length is None, win_length = n_fft
    # 3) if win_length < n_fft, pad window to n_fft
    stft_mat = librosa.stft(samps,
                            n_fft,
                            frame_hop,
                            win_length=frame_len,
                            window=window,
                            center=center)
    # stft_mat: F x T or N x F x T
    if apply_abs:
        stft_mat = cmat_abs(stft_mat)
    if apply_pow:
        stft_mat = np.power(stft_mat, 2)
    if apply_log:
        stft_mat = np.log(np.maximum(stft_mat, EPSILON))
    if transpose:
        stft_mat = np.transpose(stft_mat)
    return stft_mat


# accept F x T or T x F (tranpose=True)