本文整理汇总了Python中scipy.signal.hanning函数的典型用法代码示例。如果您正苦于以下问题:Python hanning函数的具体用法?Python hanning怎么用?Python hanning使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hanning函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, sawtooth_scale=1.0, triangle_scale=3.2, noise_scale=3.1, epsilon=1e-8):
# Until I can compute a legitimate prior, these will have to do.
self.sawtooth_scale = sawtooth_scale
self.triangle_scale = triangle_scale
self.noise_scale = noise_scale
self.noise_shape = signal.hanning(25) / np.sum(signal.hanning(25)) * self.noise_scale
self.epsilon = epsilon
self.meansq = self.epsilon
self.smoothing = 0.5
示例2: nlfer
def nlfer(signal, pitch, parameters):
#---------------------------------------------------------------
# Set parameters.
#---------------------------------------------------------------
N_f0_min = np.around((parameters['f0_min']*2/float(signal.new_fs))*pitch.nfft)
N_f0_max = np.around((parameters['f0_max']/float(signal.new_fs))*pitch.nfft)
window = hanning(pitch.frame_size+2)[1:-1]
data = np.zeros((signal.size)) #Needs other array, otherwise stride and
data[:] = signal.filtered #windowing will modify signal.filtered
#---------------------------------------------------------------
# Main routine.
#---------------------------------------------------------------
samples = np.arange(int(np.fix(float(pitch.frame_size)/2)),
signal.size-int(np.fix(float(pitch.frame_size)/2)),
pitch.frame_jump)
data_matrix = np.empty((len(samples), pitch.frame_size))
data_matrix[:, :] = stride_matrix(data, len(samples),
pitch.frame_size, pitch.frame_jump)
data_matrix *= window
specData = np.fft.rfft(data_matrix, pitch.nfft)
frame_energy = np.abs(specData[:, N_f0_min-1:N_f0_max]).sum(axis=1)
pitch.set_energy(frame_energy, parameters['nlfer_thresh1'])
pitch.set_frames_pos(samples)
示例3: test_window_derivative
def test_window_derivative(self):
"""Test if the derivative of a window function is calculated
properly."""
window = hanning(210)
derivative = derive_window(window)
ix_win_maxima = np.argmax(window)
self.assertAlmostEqual(derivative[ix_win_maxima], 0.0, places=3)
示例4: stochasticModel
def stochasticModel(x, w, N, stocf):
# x: input array sound, w: analysis window, N: FFT size,
# stocf: decimation factor of mag spectrum for stochastic analysis
# y: output sound
hN = N / 2 # size of positive spectrum
hM = (w.size) / 2 # half analysis window size
pin = hM # initialize sound pointer in middle of analysis window
fftbuffer = np.zeros(N) # initialize buffer for FFT
yw = np.zeros(w.size) # initialize output sound frame
w = w / sum(w) # normalize analysis window
ws = hanning(w.size) * 2 # synthesis window
# -----analysis-----
xw = x[pin - hM : pin + hM] * w # window the input sound
X = fft(xw) # compute FFT
mX = 20 * np.log10(abs(X[:hN])) # magnitude spectrum of positive frequencies
mXenv = resample(np.maximum(-200, mX), mX.size * stocf) # decimate the mag spectrum
pX = np.angle(X[:hN])
# -----synthesis-----
mY = resample(mXenv, hN) # interpolate to original size
pY = 2 * np.pi * np.random.rand(hN) # generate phase random values
Y = np.zeros(N, dtype=complex)
Y[:hN] = 10 ** (mY / 20) * np.exp(1j * pY) # generate positive freq.
Y[hN + 1 :] = 10 ** (mY[:0:-1] / 20) * np.exp(-1j * pY[:0:-1]) # generate negative freq.
fftbuffer = np.real(ifft(Y)) # inverse FFT
y = ws * fftbuffer * N / 2 # overlap-add
return mX, pX, mY, pY, y
示例5: main
def main(fn,start,end):
fn = Path(fn).expanduser()
#rx_array is loading the last 45% of the waveform from the file
rx_array = load_bin(fn, start, end)
#peak_array holds the indexes of each peak in the waveform
#peak_distance is the smallest distance between each peak
peak_array,peak_distance = get_peaks(rx_array)
l = peak_distance-1
print('using window: ',l,'\n')
#remove first peak
peak_array= peak_array[1:]
Npulse=len(peak_array)-1
print(Npulse,'pulses detected')
wind = signal.hanning(l)
Ntone = 2
Nblockest = 160
fs = 4e6 # [Hz]
data = np.empty([Npulse,l])
#set each row of data to window * (first l samples after each peak)
for i in range(Npulse):
data[i,:] = wind * rx_array[peak_array[i]:peak_array[i]+l]
fb_est, sigma = esprit(data, Ntone, Nblockest, fs)
print ('fb_est',fb_est)
print ('sigma: ', sigma)
drange = (3e8*fb_est) / (2e6/.1)
print ('range: ',drange,'\n')
示例6: stft
def stft(x, fs, framesz, hop):
framesamp = int(framesz*fs)
hopsamp = int(hop*fs)
w = hanning(framesamp)
X = np.array([np.fft.fft(w*x[i:i+framesamp])
for i in range(0, len(x)-framesamp, hopsamp)])
return X
示例7: enframe
def enframe(self, datas, fs, frame_len, frame_inc, win):
'''
' datas: 语音数据
' fs: 采样频率
' frame_len: 帧长,单位秒
' frame_inc: 帧移,单位秒
' win: 窗函数
'''
datas_len = len(datas) # 数据总长度
frame_len = int(round(frame_len * fs)) # 帧长,数据个数
nstep = frame_len - int(round(frame_inc * fs)) # 帧移动步长,数据个数
if datas_len < frame_len: # 若信号长度小于帧长,则帧数定义为1
nf = 1
else:
nf = int(np.ceil((1.0*datas_len-frame_len)/nstep)) + 1
pad_len = int((nf-1)*nstep + frame_len) # 所有帧总数据长度
# 多余的数据使用0填充
new_datas = np.concatenate((datas, np.zeros(pad_len - datas_len)))
indices = np.tile(np.arange(0,frame_len),(nf,1))+np.tile(np.arange(0,nf*nstep,nstep),(frame_len,1)).T
indices = np.array(indices, dtype = np.int32) # 否则会报类型错误
frames = new_datas[indices] #得到帧信号
# 加窗
if win == 'hamming':
win = signal.hamming(frame_len)
elif win == 'hanning':
win = signal.hanning(frame_len)
else:
win = signal.boxcar(frame_len)
return frames * np.tile(win, (nf, 1))
示例8: phase_vocoder
def phase_vocoder(mono, sr, N=2048, tscale= 1.0):
L,H = len(mono),N/4
# signal blocks for processing and output
phi = np.zeros(N)
out = np.zeros(N, dtype=complex)
sigout = np.zeros(L/tscale+N)
# max input amp, window
amp = max(mono)
win = sps.hanning(N)
p = 0
pp = 0
while p < L-(N+H):
if p%1024==0: print '.',
# take the spectra of two consecutive windows
p1 = int(p)
spec1 = np.fft.fft(win*mono[p1:p1+N])
spec2 = np.fft.fft(win*mono[p1+H:p1+N+H])
# take their phase difference and integrate
phi += (np.angle(spec2) - np.angle(spec1))
# bring the phase back to between pi and -pi
for i in phi:
while i > np.pi: i -= 2*np.pi
while i <= -np.pi: i += 2*np.pi
out.real, out.imag = np.cos(phi), np.sin(phi)
# inverse FFT and overlap-add
sigout[pp:pp+N] += (win*np.fft.ifft(abs(spec2)*out)).real
pp += H
p += H*tscale
print('')
return np.array(amp*sigout/max(sigout), dtype='int16')
示例9: peak_freq
def peak_freq(data, window=256, fs=400, overlap=0., ignore_dropped=False,
frequencies=[6, 20]):
nChan, nSamples = data.shape
noverlap = int(overlap * window)
windowVals = hanning(window)
# get the corresponding indices for custom frequencies
freqs = np.fft.fftfreq(window, d=1./fs)[:window/2]
idx_freqs = []
idx_freqs.append((freqs < frequencies[0]) | (freqs > frequencies[1]))
ind = list(xrange(0, nSamples - window + 1, window-noverlap))
numSlices = len(ind)
slices = range(numSlices)
Slices = []
for iSlice in slices:
thisSlice = data[:, ind[iSlice]:ind[iSlice] + window]
if np.sum(np.sum(thisSlice**2, axis=0)>0):
freqs, thisfft = welch(thisSlice, fs=400, nfft=window/2)
Slices.append(thisfft.T)
if len(Slices) > 0:
Slices = np.array(Slices)
a = find_peak(Slices, freqs, order=5, max_peak=3)
else:
a = np.nan
return a
示例10: stochasticModel
def stochasticModel(x, H, stocf):
# stochastic analysis/synthesis of a sound, one frame at a time
# x: input array sound, H: hop size,
# stocf: decimation factor of mag spectrum for stochastic analysis
# returns y: output sound
N = H*2 # FFT size
w = hanning(N) # analysis/synthesis window
x = np.append(np.zeros(H),x) # add zeros at beginning to center first window at sample 0
x = np.append(x,np.zeros(H)) # add zeros at the end to analyze last sample
pin = 0 # initialize sound pointer in middle of analysis window
pend = x.size-N # last sample to start a frame
y = np.zeros(x.size) # initialize output array
while pin<=pend:
#-----analysis-----
xw = x[pin:pin+N]*w # window the input sound
X = fft(xw) # compute FFT
mX = 20 * np.log10(abs(X[:H])) # magnitude spectrum of positive frequencies
mYst = resample(np.maximum(-200, mX), mX.size*stocf) # decimate the mag spectrum
#-----synthesis-----
mY = resample(mYst, H) # interpolate to original size
pY = 2*np.pi*np.random.rand(H) # generate phase random values
Y = np.zeros(N, dtype = complex)
Y[:H] = 10**(mY/20) * np.exp(1j*pY) # generate positive freq.
Y[H+1:] = 10**(mY[:0:-1]/20) * np.exp(-1j*pY[:0:-1]) # generate negative freq.
fftbuffer = np.real(ifft(Y)) # inverse FFT
y[pin:pin+N] += w*fftbuffer # overlap-add
pin += H
y = np.delete(y, range(H)) # delete half of first window which was added
y = np.delete(y, range(y.size-H, y.size)) # delete half of last window which was added # advance sound pointer
return y
示例11: finalize
def finalize(self):
discard = self.get_current_value('discard')
smoothing_window = self.get_current_value('smoothing_window')
exp_mic_gain = dbi(self.get_current_value('exp_mic_gain'))
waveform_averages = self.get_current_value('waveform_averages')
results = self.iface.process(waveform_averages=waveform_averages,
input_gains=exp_mic_gain, discard=discard)
exp_mic_waveform = results['mic_waveforms'].mean(axis=0)[0]
exp_mic_psd = db(results['tf'])[0]
if smoothing_window > 0:
w = signal.hanning(smoothing_window)
w /= w.sum()
exp_mic_psd = np.convolve(exp_mic_psd, w, mode='same')
speaker_spl = self.calibration.get_spl(results['mic_frequency'],
results['tf'][0])
results['exp_mic_waveform'] = exp_mic_waveform
results['exp_mic_psd'] = exp_mic_psd
results['frequency'] = results['mic_frequency']
results['speaker_spl'] = speaker_spl
self.model.update_plots(results, freq_lb=500, freq_ub=50e3)
self.results = results
self.result_settings = dict(self.model.paradigm.items())
self.complete = True
示例12: stochasticModelSynth
def stochasticModelSynth(stocEnv, H, N):
"""
Stochastic synthesis of a sound
stocEnv: stochastic envelope; H: hop size; N: fft size
returns y: output sound
"""
if not(UF.isPower2(N)): # raise error if N not a power of two
raise ValueError("N is not a power of two")
hN = N/2+1 # positive size of fft
No2 = N/2 # half of N
L = stocEnv[:,0].size # number of frames
ysize = H*(L+3) # output sound size
y = np.zeros(ysize) # initialize output array
ws = 2*hanning(N) # synthesis window
pout = 0 # output sound pointer
for l in range(L):
mY = resample(stocEnv[l,:], hN) # interpolate to original size
pY = 2*np.pi*np.random.rand(hN) # generate phase random values
Y = np.zeros(N, dtype = complex) # initialize synthesis spectrum
Y[:hN] = 10**(mY/20) * np.exp(1j*pY) # generate positive freq.
Y[hN:] = 10**(mY[-2:0:-1]/20) * np.exp(-1j*pY[-2:0:-1]) # generate negative freq.
fftbuffer = np.real(ifft(Y)) # inverse FFT
y[pout:pout+N] += ws*fftbuffer # overlap-add
pout += H
y = np.delete(y, range(No2)) # delete half of first window
y = np.delete(y, range(y.size-No2, y.size)) # delete half of the last window
return y
示例13: slidingFFT
def slidingFFT(data, window=256, fs=400, overlap=0., ignore_dropped=False,
frequencies=None, aggregate=True, phase=False):
nChan, nSamples = data.shape
noverlap = int(overlap * window)
windowVals = hanning(window)
# get the corresponding indices for custom frequencies
freqs = np.fft.fftfreq(window, d=1./fs)[:window/2]
idx_freqs = []
if frequencies is not None:
for fr in frequencies:
tmp = (freqs >= fr[0]) & (freqs < fr[1])
idx_freqs.append(np.where(tmp)[0])
numFreqs = len(idx_freqs)
else:
numFreqs = len(freqs)
# get the indices of dropped data
if ignore_dropped:
dropped = (np.sum(data**2, 0) == 0)
ind = list(xrange(0, nSamples - window + 1, window-noverlap))
numSlices = len(ind)
slices = range(numSlices)
Slices = np.zeros((numSlices, numFreqs, nChan), dtype=np.complex_)
for iSlice in slices:
sl = slice(ind[iSlice], ind[iSlice] + window)
if ignore_dropped:
if np.sum(dropped[sl]) > 0:
continue
thisSlice = data[:, sl]
thisSlice = windowVals*thisSlice
thisfft = np.fft.fft(thisSlice).T
if frequencies is None:
Slices[iSlice] = thisfft[1:(window/2 + 1)]
else:
for fr, idx in enumerate(idx_freqs):
Slices[iSlice, fr, :] = thisfft[idx].mean(0)
Slices = Slices.transpose(0, 2, 1)
if aggregate:
Slices = np.concatenate(Slices.transpose(1, 2, 0), axis=0)
else:
Slices = Slices.transpose(2, 1, 0)
if phase:
Slices = np.arctan2(np.imag(Slices), np.real(Slices))
else:
Slices = np.abs(Slices)
return Slices
示例14: smooth
def smooth(self, n=4):
win = signal.hanning(n, sym=True)
win /= np.sum(win)
K = self.data
nt, M, N = K.shape
for t in range(nt):
for i in range(M):
K[t, i, :] = np.convolve(K[t, i, :], win, mode='same')
for j in range(N):
K[t, :, j] = np.convolve(K[t, :, j], win, mode='same')
示例15: autocorrelation
def autocorrelation(block):
w = hanning(len(block))
if len(block.shape)==1:
b = block*w
res = correlate(b, b, mode='full')
v = res[res.shape[0]/2:]
return v/max(v)
elif len(block.shape)==2:
res = array([correlate(block[:,i]*w, block[:,i]*w, mode='full')
for i in range(block.shape[1])])
v = res[:,res.shape[1]/2:]
return v/max(v)