Python numpy.hamming() Examples

The following are 30 code examples for showing how to use numpy.hamming(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: mist-rnns   Author: rdipietro   File: timitphonemerec.py    License: Apache License 2.0 7 votes vote down vote up
def _mfcc_and_labels(audio, labels):
  """ Convert to MFCC features and corresponding (interpolated) labels.

  Returns:
    A tuple, `(mfcc_features, mfcc_labels)`. A 1-D float array and a 1-D int
      array, both with the same shape.
  """
  mfcc_sample_rate = 100.0
  winfunc = lambda x: np.hamming(x)
  mfcc_features = python_speech_features.mfcc(audio, samplerate=timit.SAMPLE_RATE, winlen=0.025,
                                              winstep=1.0/mfcc_sample_rate, lowfreq=85.0,
                                              highfreq=timit.SAMPLE_RATE/2, winfunc=winfunc)
  t_audio = np.linspace(0.0, audio.shape[0] * 1.0 / timit.SAMPLE_RATE, audio.size, endpoint=False)
  t_mfcc = np.linspace(0.0, mfcc_features.shape[0] * 1.0 / mfcc_sample_rate, mfcc_features.shape[0], endpoint=False)
  interp_func = scipy.interpolate.interp1d(t_audio, labels, kind='nearest')
  mfcc_labels = interp_func(t_mfcc)
  return mfcc_features, mfcc_labels 
Example 2
Project: spectrum   Author: cokelaer   File: window.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_window(self):
        """Plot the window in the time domain

        .. plot::
            :width: 80%
            :include-source:

            from spectrum.window import Window
            w = Window(64, name='hamming')
            w.plot_window()

        """
        from pylab import plot, xlim, grid, title, ylabel, axis
        x = linspace(0, 1, self.N)
        xlim(0, 1)
        plot(x, self.data)
        grid(True)
        title('%s Window (%s points)' % (self.name.capitalize(), self.N))
        ylabel('Amplitude')
        axis([0, 1, 0, 1.1]) 
Example 3
Project: spectrum   Author: cokelaer   File: window.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def window_hamming(N):
    r"""Hamming window

    :param N: window length


    The Hamming window is defined as

    .. math:: 0.54 -0.46 \cos\left(\frac{2\pi n}{N-1}\right)
               \qquad 0 \leq n \leq M-1

    .. plot::
        :width: 80%
        :include-source:

        from spectrum import window_visu
        window_visu(64, 'hamming')

    .. seealso:: numpy.hamming, :func:`create_window`, :class:`Window`.
    """
    from numpy import hamming
    return hamming(N) 
Example 4
Project: music_transcription_MAPS   Author: qiuqiangkong   File: prepare_data.py    License: MIT License 6 votes vote down vote up
def spectrogram(audio):
    """Calculate magnitude spectrogram of an audio sequence. 
    
    Args: 
      audio: 1darray, audio sequence. 
      
    Returns:
      x: ndarray, spectrogram (n_time, n_freq)
    """
    n_window = cfg.n_window
    n_overlap = cfg.n_overlap
    
    ham_win = np.hamming(n_window)
    [f, t, x] = signal.spectral.spectrogram(
                    audio, 
                    window=ham_win,
                    nperseg=n_window, 
                    noverlap=n_overlap, 
                    detrend=False, 
                    return_onesided=True, 
                    mode='magnitude') 
    x = x.T
    x = x.astype(np.float32)
    return x 
Example 5
Project: Ossian   Author: CSTR-Edinburgh   File: acoustic_feats.py    License: Apache License 2.0 6 votes vote down vote up
def _smooth(params, win, type="HAMMING"):
    

    win = int(win+0.5)
    if win >= len(params)-1:
        win = len(params)-1
    if win % 2 == 0:
        win+=1

    s = np.r_[params[win-1:0:-1],params,params[-1:-win:-1]]

    
    if type=="HAMMING":
        w = np.hamming(win)
        third = int(win/5)
        #w[:third] = 0
    else:
        w = np.ones(win)
        
        
    y = np.convolve(w/w.sum(),s,mode='valid')
    return y[(win/2):-(win/2)] 
Example 6
Project: deepspeech-german   Author: AASHISHAG   File: audio.py    License: Apache License 2.0 6 votes vote down vote up
def audiofile_to_input_vector(audio_filename, numcep, numcontext):
    r"""
    Given a WAV audio file at ``audio_filename``, calculates ``numcep`` MFCC features
    at every 0.01s time step with a window length of 0.025s. Appends ``numcontext``
    context frames to the left and right of each time step, and returns this data
    in a numpy array.
    """
    # Load wav files
    fs, audio = wav.read(audio_filename)

    # Get mfcc coefficients
    features = mfcc(audio, samplerate=fs, numcep=numcep, winlen=0.032, winstep=0.02, winfunc=np.hamming)

    # Add empty initial and final contexts
    empty_context = np.zeros((numcontext, numcep), dtype=features.dtype)
    features = np.concatenate((empty_context, features, empty_context))

    return features 
Example 7
Project: iqtool   Author: jgibbard   File: iqplot.py    License: The Unlicense 6 votes vote down vote up
def plotSpectrogram(data, fftWindow, fftSize, Fs):

    if fftSize == None:
        N = len(data)
    else:
        N = fftSize    
    
    if Fs == None:
        Fs = 2
    
    if fftWindow == "rectangular":
        plt.specgram(data, NFFT=N, Fs=Fs, 
        window=lambda data: data*np.ones(len(data)),  noverlap=int(N/10))
    elif fftWindow == "bartlett":
        plt.specgram(data, NFFT=N, Fs=Fs, 
        window=lambda data: data*np.bartlett(len(data)),  noverlap=int(N/10))
    elif args.fftWindow == "blackman":
        plt.specgram(data, NFFT=N, Fs=Fs, 
        window=lambda data: data*np.blackman(len(data)),  noverlap=int(N/10))
    elif fftWindow == "hamming":
        plt.specgram(data, NFFT=N, Fs=Fs, 
        window=lambda data: data*np.hamming(len(data)),  noverlap=int(N/10))
    elif fftWindow == "hanning":
         plt.specgram(data, NFFT=N, Fs=Fs, 
         window=lambda data: data*np.hanning(len(data)),  noverlap=int(N/10))

    plt.show() 
Example 8
Project: pyAudioAnalysis   Author: tyiannak   File: ShortTermFeatures.py    License: Apache License 2.0 6 votes vote down vote up
def phormants(x, sampling_rate):
    N = len(x)
    w = np.hamming(N)

    # Apply window and high pass filter.
    x1 = x * w
    x1 = lfilter([1], [1., 0.63], x1)

    # Get LPC.
    ncoeff = 2 + sampling_rate / 1000
    A, e, k = lpc(x1, ncoeff)
    # A, e, k = lpc(x1, 8)

    # Get roots.
    rts = np.roots(A)
    rts = [r for r in rts if np.imag(r) >= 0]

    # Get angles.
    angz = np.arctan2(np.imag(rts), np.real(rts))

    # Get frequencies.
    frqs = sorted(angz * (sampling_rate / (2 * math.pi)))

    return frqs 
Example 9
Project: AMFM_decompy   Author: bjbschmitt   File: pyQHM.py    License: MIT License 6 votes vote down vote up
def __init__(self, window_duration, fs):
        self.dur = window_duration         # in seconds
        self.length = int(self.dur*fs+1)
        if not self.length %2:
            self.length -= 1
        self.data = np.hamming(self.length)
        self.data2 = self.data**2
        self.N = int(self.dur*fs/2)
        self.half_len_vec = np.arange(self.N+1)
        self.len_vec = np.arange(-self.N, self.N+1)

        self.a0 = 0.54**2 + (0.46**2)/2
        self.a1 = 0.54*0.46
        self.a2 = (0.46**2)/4

        self.R0_diag = R_eq(0, g0, self)
        self.R2_diag = sum(self.data2*(self.len_vec**2)) 
Example 10
Project: python_kaldi_features   Author: ZitengWang   File: base.py    License: MIT License 6 votes vote down vote up
def logfbank(signal,samplerate=16000,winlen=0.025,winstep=0.01,
          nfilt=40,nfft=512,lowfreq=64,highfreq=None,dither=1.0,remove_dc_offset=True,preemph=0.97,wintype='hamming'):
    """Compute log Mel-filterbank energy features from an audio signal.

    :param signal: the audio signal from which to compute features. Should be an N*1 array
    :param samplerate: the samplerate of the signal we are working with.
    :param winlen: the length of the analysis window in seconds. Default is 0.025s (25 milliseconds)
    :param winstep: the step between successive windows in seconds. Default is 0.01s (10 milliseconds)
    :param nfilt: the number of filters in the filterbank, default 26.
    :param nfft: the FFT size. Default is 512.
    :param lowfreq: lowest band edge of mel filters. In Hz, default is 0.
    :param highfreq: highest band edge of mel filters. In Hz, default is samplerate/2
    :param preemph: apply preemphasis filter with preemph as coefficient. 0 is no filter. Default is 0.97.
    :returns: A numpy array of size (NUMFRAMES by nfilt) containing features. Each row holds 1 feature vector.
    """
    feat,energy = fbank(signal,samplerate,winlen,winstep,nfilt,nfft,lowfreq,highfreq,dither, remove_dc_offset,preemph,wintype)
    return numpy.log(feat) 
Example 11
Project: pykaldi2   Author: jzlianglu   File: freq_analysis.py    License: MIT License 6 votes vote down vote up
def __init__(self, config=None, fs=16000, fft_size=512, frame_len=400, frame_shift=160, window='hamming', do_dither=True, dc_removal=False, use_gpu=False):
        self.fs = fs
        self.fft_size = fft_size
        self.frame_len = frame_len
        self.frame_shift = frame_shift
        self.window = window
        self.do_dither = do_dither
        self.dc_removal = dc_removal
        self.use_gpu = use_gpu

        if config is not None:
            for attr in config:
                setattr(self, attr, config[attr])

        self.n_bin = self.fft_size/2+1
        self.frame_overlap = self.frame_len - self.frame_shift 
Example 12
Project: pykaldi2   Author: jzlianglu   File: sr_dataset.py    License: MIT License 6 votes vote down vote up
def _logfbank_extractor(self, wav):
        # typical log fbank extraction for 16kHz speech data
        preemphasis = 0.96

        t1 = np.sum(self._window, 0)
        t1[t1 == 0] = -1
        inv = np.diag(1 / t1)
        mel = self._window.dot(inv).T

        wav = wav[1:] - preemphasis * wav[:-1]
        S = stft(wav, n_fft=512, hop_length=160, win_length=400, window=np.hamming(400), center=False).T

        spec_mag = np.abs(S)
        spec_power = spec_mag ** 2
        fbank_power = spec_power.T.dot(mel * 32768 ** 2) + 1
        log_fbank = np.log(fbank_power)

        return log_fbank 
Example 13
Project: rapidtide   Author: bbfrederick   File: helper_classes.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 Fs=0.0,
                 corrorigin=0,
                 lagmininpts=0,
                 lagmaxinpts=0,
                 ncprefilter=None,
                 reftc=None,
                 detrendorder=1,
                 windowfunc='hamming',
                 corrweighting='none'):
        self.Fs = Fs
        self.corrorigin = corrorigin
        self.lagmininpts = lagmininpts
        self.lagmaxinpts = lagmaxinpts
        self.ncprefilter = ncprefilter
        self.reftc = reftc
        self.detrendorder = detrendorder
        self.windowfunc = windowfunc
        if self.windowfunc is not None:
            self.usewindowfunc = True
        else:
            self.usewindowfunc = False
        self.corrweighting = corrweighting
        if self.reftc is not None:
            self.setreftc(self.reftc) 
Example 14
Project: wavelet_prosody_toolkit   Author: asuni   File: smooth_and_interp.py    License: MIT License 6 votes vote down vote up
def smooth(params, win, type="HAMMING"):

    """
    gaussian type smoothing, convolution with hamming window
    """
    win = int(win+0.5)
    if win >= len(params)-1:
        win = len(params)-1

    if win % 2 == 0:
        win += 1

    s = np.r_[params[win-1:0:-1], params, params[-1:-win:-1]]

    if type == "HAMMING":
        w = np.hamming(win)
        # third = int(win/3)
        # w[:third] = 0
    else:
        w = np.ones(win)

    y = np.convolve(w/w.sum(), s, mode='valid')
    return y[int(win/2):-int(win/2)] 
Example 15
Project: pydiogment   Author: SuperKogito   File: auga.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fade_in_and_out(infile):
    """
    Add a fade in and out effect to the audio file.

    Args:
        - infile (str) : input filename/path.
    """
    # read input file
    fs, sig = read_file(filename=infile)
    window = np.hamming(len(sig))

    # construct file names
    output_file_path = os.path.dirname(infile)
    name_attribute = "_augmented_fade_in_out.wav"

    # fade in and out
    window = np.hamming(len(sig))
    augmented_sig = window * sig
    augmented_sig /= np.mean(np.abs(augmented_sig))

    # export data to file
    write_file(output_file_path=output_file_path,
               input_file_name=infile,
               name_attribute=name_attribute,
               sig=augmented_sig,
               fs=fs) 
Example 16
Project: speech_separation   Author: bill9800   File: simple_model.py    License: MIT License 5 votes vote down vote up
def window_fft(data,fft_size,step_size):
    window = np.hamming(fft_size)
    number_windows = (data.shape[0]-fft_size)//step_size
    output = np.ndarray((number_windows,fft_size),dtype=data.dtype)

    for i in range(number_windows):
        head = int(i*step_size)
        tail = int(head+fft_size)
        output[i] = data[head:tail]*window

    F = np.fft.rfft(output,axis=-1)
    return F 
Example 17
Project: speech_separation   Author: bill9800   File: simple_model.py    License: MIT License 5 votes vote down vote up
def rev_window_fft(F,fft_size,step_size):
    data = np.fft.irfft(F,axis=-1)
    window = np.hamming(fft_size)
    number_windows = F.shape[0]

    T = np.zeros((number_windows*step_size+fft_size))
    for i in range(number_windows):
        head = int(i*step_size)
        tail = int(head+fft_size)
        T[head:tail] = T[head:tail]+data[i,:]*window
    return T

# mel2freq_matrix generation 
Example 18
Project: Python-GUI-examples   Author: swharden   File: SWHear.py    License: MIT License 5 votes vote down vote up
def getFFT(data,rate):
    """Given some data and rate, returns FFTfreq and FFT (half)."""
    data=data*np.hamming(len(data))
    fft=np.fft.fft(data)
    fft=np.abs(fft)
    #fft=10*np.log10(fft)
    freq=np.fft.fftfreq(len(fft),1.0/rate)
    return freq[:int(len(freq)/2)],fft[:int(len(fft)/2)] 
Example 19
Project: eht-imaging   Author: achael   File: starwarps.py    License: GNU General Public License v3.0 5 votes vote down vote up
def gaussImgCovariance(im, pixelStdev=1.0, powerDropoff=1.0, filter='none', kernsig=3.0): 
    
    eps = 0.001  
    
    init_x, init_y, flowbasis_x, flowbasis_y, initTheta = affineMotionBasis(im)
    ufull, vfull = genFreqComp(im)
    shiftMtx = genPhaseShiftMtx(ufull, vfull, init_x, init_y, flowbasis_x, flowbasis_y, initTheta, im.psize, im.pulse) 
    uvdist = np.reshape( np.sqrt(ufull**2 + vfull**2), (ufull.shape[0]) ) + eps
    uvdist = uvdist / np.min(uvdist)
    uvdist[0] = 'Inf'
    
    if filter == 'hamming':
        hammingwindow = np.dot(np.reshape(np.hamming(im.xdim), (im.xdim,1)), np.reshape(np.hamming(im.ydim) , (1, im.ydim)) )
        shiftMtx = np.dot(shiftMtx, np.diag(np.reshape(hammingwindow, (im.xdim*im.ydim))) ) 
    if filter == 'gaussian':
        gausswindow = gkern(kernlen=im.xdim, nsig=kernsig)
        shiftMtx = np.dot(shiftMtx, np.diag(np.reshape(gausswindow, (im.xdim*im.ydim))) )
    
    shiftMtx_exp = realimagStack(shiftMtx)    
    uvdist_exp = np.concatenate( (uvdist, uvdist), axis=0)
    
    imCov = np.dot( np.transpose(shiftMtx_exp) , np.dot( np.diag( 1/(uvdist_exp**powerDropoff) ), shiftMtx_exp ) )
    imCov = pixelStdev**2 * (imCov/imCov[0,0]); 
    return imCov

###################################### BASIS ######################################## 
Example 20
Project: Speech_Signal_Processing_and_Classification   Author: gionanide   File: lpc.py    License: MIT License 5 votes vote down vote up
def hamming(frames,frameSize):
	# Windowing with Hamming
	#Hamming implementation : W[n] = 0.54 - 0.46 * numpy.cos((2 * numpy.pi * n) / (frameSize - 1))  
	# y[n] = s[n] (signal in a specific sample) * w[n] (the window function Hamming) 
	frames*=np.hamming(frameSize)
	'''plt.figure(figsize=(10, 6)) 
	plt.subplot(facecolor='darkslategray')
	plt.title('Hamming window')
	plt.ylim(-40000, 40000)
	plt.ylabel('Amplitude', fontsize=16)
	plt.xlabel('Time(ms)', fontsize=8)
	plt.plot(frames,'C1')
	plt.show()'''
	return frames 
Example 21
Project: Speech_Signal_Processing_and_Classification   Author: gionanide   File: lpc.py    License: MIT License 5 votes vote down vote up
def myLPC():
	folder = raw_input('Give the name of the folder that you want to read data: ')
	amount = raw_input('Give the number of samples in the specific folder: ')
	for x in range(1,int(amount)+1):
		wav = '/'+folder+'/'+str(x)+'.wav'
		print wav
		emphasizedSignal,signal,rate = preEmphasis(wav)
		#visualize(rate,signal)
		frames , frameSize = framing(rate,signal)
		hammingFrames = hamming(frames,frameSize)
		correlateFrames = autocorrelation(hammingFrames)
		merged=correlateFrames[0]
		for x in range(1,len(correlateFrames)-1):
			merged = np.append(merged,correlateFrames[x])
		lev_Dur = levinsonDurbin(merged) 
Example 22
Project: Speech_Signal_Processing_and_Classification   Author: gionanide   File: mgca.py    License: MIT License 5 votes vote down vote up
def mgca_feature_extraction(wav):
	#I pre-emphasized the signal with a low pass filter
	emphasizedSignal,signal,rate = preEmphasis(wav)
	
	
	#and now I have the signal windowed
	emphasizedSignal*=np.hamming(len(emphasizedSignal))
	
	mgca_features = mgcep(emphasizedSignal,order=12)

	writeFeatures(mgca_features,wav) 
Example 23
Project: seq2seq   Author: alex-berard   File: base.py    License: Apache License 2.0 5 votes vote down vote up
def mfcc(signal,samplerate=16000,winlen=0.025,winstep=0.01,numcep=13,
         nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97,ceplifter=22,appendEnergy=True,
         winfunc=lambda x:numpy.ones((x,))):
    """Compute MFCC features from an audio signal.

    :param signal: the audio signal from which to compute features. Should be an N*1 array
    :param samplerate: the samplerate of the signal we are working with.
    :param winlen: the length of the analysis window in seconds. Default is 0.025s (25 milliseconds)
    :param winstep: the step between successive windows in seconds. Default is 0.01s (10 milliseconds)
    :param numcep: the number of cepstrum to return, default 13
    :param nfilt: the number of filters in the filterbank, default 26.
    :param nfft: the FFT size. Default is 512.
    :param lowfreq: lowest band edge of mel filters. In Hz, default is 0.
    :param highfreq: highest band edge of mel filters. In Hz, default is samplerate/2
    :param preemph: apply preemphasis filter with preemph as coefficient. 0 is no filter. Default is 0.97.
    :param ceplifter: apply a lifter to final cepstral coefficients. 0 is no lifter. Default is 22.
    :param appendEnergy: if this is true, the zeroth cepstral coefficient is replaced with the log of the total frame energy.
    :param winfunc: the analysis window to apply to each frame. By default no window is applied. You can use numpy window functions here e.g. winfunc=numpy.hamming
    :returns: A numpy array of size (NUMFRAMES by numcep) containing features. Each row holds 1 feature vector.
    """
    feat,energy = fbank(signal,samplerate,winlen,winstep,nfilt,nfft,lowfreq,highfreq,preemph,winfunc)
    feat = numpy.log(feat)
    feat = dct(feat, type=2, axis=1, norm='ortho')[:,:numcep]
    feat = lifter(feat,ceplifter)
    if appendEnergy: feat[:,0] = numpy.log(energy) # replace first cepstral coefficient with log of frame energy
    return feat 
Example 24
Project: seq2seq   Author: alex-berard   File: base.py    License: Apache License 2.0 5 votes vote down vote up
def fbank(signal,samplerate=16000,winlen=0.025,winstep=0.01,
          nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97,
          winfunc=lambda x:numpy.ones((x,))):
    """Compute Mel-filterbank energy features from an audio signal.

    :param signal: the audio signal from which to compute features. Should be an N*1 array
    :param samplerate: the samplerate of the signal we are working with.
    :param winlen: the length of the analysis window in seconds. Default is 0.025s (25 milliseconds)
    :param winstep: the step between successive windows in seconds. Default is 0.01s (10 milliseconds)
    :param nfilt: the number of filters in the filterbank, default 26.
    :param nfft: the FFT size. Default is 512.
    :param lowfreq: lowest band edge of mel filters. In Hz, default is 0.
    :param highfreq: highest band edge of mel filters. In Hz, default is samplerate/2
    :param preemph: apply preemphasis filter with preemph as coefficient. 0 is no filter. Default is 0.97.
    :param winfunc: the analysis window to apply to each frame. By default no window is applied. You can use numpy window functions here e.g. winfunc=numpy.hamming
    :returns: 2 values. The first is a numpy array of size (NUMFRAMES by nfilt) containing features. Each row holds 1 feature vector. The
        second return value is the energy in each frame (total energy, unwindowed)
    """
    highfreq= highfreq or samplerate/2
    signal = sigproc.preemphasis(signal,preemph)
    frames = sigproc.framesig(signal, winlen*samplerate, winstep*samplerate, winfunc)
    pspec = sigproc.powspec(frames,nfft)
    energy = numpy.sum(pspec,1) # this stores the total energy in each frame
    energy = numpy.where(energy == 0,numpy.finfo(float).eps,energy) # if energy is zero, we get problems with log

    fb = get_filterbanks(nfilt,nfft,samplerate,lowfreq,highfreq)
    feat = numpy.dot(pspec,fb.T) # compute the filterbank energies
    feat = numpy.where(feat == 0,numpy.finfo(float).eps,feat) # if feat is zero, we get problems with log

    return feat,energy 
Example 25
Project: seq2seq   Author: alex-berard   File: base.py    License: Apache License 2.0 5 votes vote down vote up
def ssc(signal,samplerate=16000,winlen=0.025,winstep=0.01,
        nfilt=26,nfft=512,lowfreq=0,highfreq=None,preemph=0.97,
        winfunc=lambda x:numpy.ones((x,))):
    """Compute Spectral Subband Centroid features from an audio signal.

    :param signal: the audio signal from which to compute features. Should be an N*1 array
    :param samplerate: the samplerate of the signal we are working with.
    :param winlen: the length of the analysis window in seconds. Default is 0.025s (25 milliseconds)
    :param winstep: the step between successive windows in seconds. Default is 0.01s (10 milliseconds)
    :param nfilt: the number of filters in the filterbank, default 26.
    :param nfft: the FFT size. Default is 512.
    :param lowfreq: lowest band edge of mel filters. In Hz, default is 0.
    :param highfreq: highest band edge of mel filters. In Hz, default is samplerate/2
    :param preemph: apply preemphasis filter with preemph as coefficient. 0 is no filter. Default is 0.97.
    :param winfunc: the analysis window to apply to each frame. By default no window is applied. You can use numpy window functions here e.g. winfunc=numpy.hamming
    :returns: A numpy array of size (NUMFRAMES by nfilt) containing features. Each row holds 1 feature vector.
    """
    highfreq= highfreq or samplerate/2
    signal = sigproc.preemphasis(signal,preemph)
    frames = sigproc.framesig(signal, winlen*samplerate, winstep*samplerate, winfunc)
    pspec = sigproc.powspec(frames,nfft)
    pspec = numpy.where(pspec == 0,numpy.finfo(float).eps,pspec) # if things are all zeros we get problems

    fb = get_filterbanks(nfilt,nfft,samplerate,lowfreq,highfreq)
    feat = numpy.dot(pspec,fb.T) # compute the filterbank energies
    R = numpy.tile(numpy.linspace(1,samplerate/2,numpy.size(pspec,1)),(numpy.size(pspec,0),1))

    return numpy.dot(pspec*R,fb.T) / feat 
Example 26
Project: ufora   Author: ufora   File: SharedStateMemory_test.py    License: Apache License 2.0 5 votes vote down vote up
def smoothArray(array, wlen=128):
    w = numpy.hamming(wlen)
    array = numpy.r_[array[wlen-1:0:-1], array, array[-1:-wlen:-1]]
    return numpy.convolve(array, w / w.sum(), mode="valid")[:len(array)] 
Example 27
Project: Lie_to_me   Author: Notabela   File: thinkdsp.py    License: MIT License 5 votes vote down vote up
def make_wave(self):
        """Inverts the spectrogram and returns a Wave.

        returns: Wave
        """
        res = []
        for t, spectrum in sorted(self.spec_map.items()):
            wave = spectrum.make_wave()
            n = len(wave)
            
            window = 1 / np.hamming(n)
            wave.window(window)

            i = wave.find_index(t)
            start = i - n // 2
            end = start + n
            res.append((start, end, wave))

        starts, ends, waves = zip(*res)
        low = min(starts)
        high = max(ends)

        ys = np.zeros(high-low, np.float)
        for start, end, wave in res:
            ys[start:end] = wave.ys

        # ts = np.arange(len(ys)) / self.framerate
        return Wave(ys, framerate=wave.framerate) 
Example 28
Project: Lie_to_me   Author: Notabela   File: thinkdsp.py    License: MIT License 5 votes vote down vote up
def hamming(self):
        """Apply a Hamming window to the wave.
        """
        self.ys *= np.hamming(len(self.ys)) 
Example 29
Project: Lie_to_me   Author: Notabela   File: thinkdsp.py    License: MIT License 5 votes vote down vote up
def make_spectrogram(self, seg_length, win_flag=True):
        """Computes the spectrogram of the wave.

        seg_length: number of samples in each segment
        win_flag: boolean, whether to apply hamming window to each segment

        returns: Spectrogram
        """
        if win_flag:
            window = np.hamming(seg_length)
        i, j = 0, seg_length
        step = seg_length // 2

        # map from time to Spectrum
        spec_map = {}

        while j < len(self.ys):
            segment = self.slice(i, j)
            if win_flag:
                segment.window(window)

            # the nominal time for this segment is the midpoint
            t = (segment.start + segment.end) / 2
            spec_map[t] = segment.make_spectrum()

            i += step
            j += step

        return Spectrogram(spec_map, seg_length) 
Example 30
Project: cupy   Author: cupy   File: window.py    License: MIT License 5 votes vote down vote up
def hamming(M):
    """Returns the Hamming window.

    The Hamming window is defined as

    .. math::
        w(n) = 0.54 - 0.46\\cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
        \\qquad 0 \\leq n \\leq M-1

    Args:
        M (:class:`~int`):
            Number of points in the output window. If zero or less, an empty
            array is returned.

    Returns:
        ~cupy.ndarray: Output ndarray.

    .. seealso:: :func:`numpy.hamming`
    """
    if M == 1:
        return cupy.ones(1, dtype=cupy.float64)
    if M <= 0:
        return cupy.array([])
    alpha = numpy.pi * 2 / (M - 1)
    out = cupy.empty(M, dtype=cupy.float64)
    return _hamming_kernel(alpha, out)