def dft_np(signal, hop_size=256, fft_size=512):
n_hops = len(signal) // hop_size
s = []
hann_win = hann(fft_size)
for hop_i in range(n_hops):
frame = signal[(hop_i * hop_size):(hop_i * hop_size + fft_size)]
frame = np.pad(frame, (0, fft_size - len(frame)), 'constant')
frame *= hann_win
s.append(frame)
s = np.array(s)
N = s.shape[-1]
k = np.reshape(np.linspace(0.0, 2 * np.pi / N * (N // 2), N // 2), [1, N // 2])
x = np.reshape(np.linspace(0.0, N - 1, N), [N, 1])
freqs = np.dot(x, k)
reals = np.dot(s, np.cos(freqs)) * (2.0 / N)
imags = np.dot(s, np.sin(freqs)) * (2.0 / N)
return reals, imags
python类hann()的实例源码
mxne_inverse.py 文件源码
项目:decoding_challenge_cortana_2016_3rd
作者: kingjr
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def _window_evoked(evoked, size):
"""Window evoked (size in seconds)"""
if isinstance(size, (float, int)):
lsize = rsize = float(size)
else:
lsize, rsize = size
evoked = evoked.copy()
sfreq = float(evoked.info['sfreq'])
lsize = int(lsize * sfreq)
rsize = int(rsize * sfreq)
lhann = signal.hann(lsize * 2)
rhann = signal.hann(rsize * 2)
window = np.r_[lhann[:lsize],
np.ones(len(evoked.times) - lsize - rsize),
rhann[-rsize:]]
evoked.data *= window[None, :]
return evoked
preprocessing.py 文件源码
项目:Epileptic-Seizure-Prediction
作者: cedricsimar
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def hanning(self, sig):
"""
Apply a Hanning window to the signal and return it
"""
han_window = signal.hann(len(sig))
return(sig*han_window)
def apply(self, data):
axis = data.ndim - 1
out = resample(data, self.f, axis=axis, window=hann(M=data.shape[axis]))
return out
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)
def get_ft_windows():
""" Retrieve the available windows to be applied on signal data before FT.
@return: dict with keys being the window name and items being again a dict
containing the actual function and the normalization factor to
calculate correctly the amplitude spectrum in the Fourier Transform
To find out the amplitude normalization factor check either the scipy
implementation on
https://github.com/scipy/scipy/blob/v0.15.1/scipy/signal/windows.py#L336
or just perform a sum of the window (oscillating parts of the window should
be averaged out and constant offset factor will remain):
MM=1000000 # choose a big number
print(sum(signal.hanning(MM))/MM)
"""
win = {'none': {'func': np.ones, 'ampl_norm': 1.0},
'hamming': {'func': signal.hamming, 'ampl_norm': 1.0/0.54},
'hann': {'func': signal.hann, 'ampl_norm': 1.0/0.5},
'blackman': {'func': signal.blackman, 'ampl_norm': 1.0/0.42},
'triang': {'func': signal.triang, 'ampl_norm': 1.0/0.5},
'flattop': {'func': signal.flattop, 'ampl_norm': 1.0/0.2156},
'bartlett': {'func': signal.bartlett, 'ampl_norm': 1.0/0.5},
'parzen': {'func': signal.parzen, 'ampl_norm': 1.0/0.375},
'bohman': {'func': signal.bohman, 'ampl_norm': 1.0/0.4052847},
'blackmanharris': {'func': signal.blackmanharris, 'ampl_norm': 1.0/0.35875},
'nuttall': {'func': signal.nuttall, 'ampl_norm': 1.0/0.3635819},
'barthann': {'func': signal.barthann, 'ampl_norm': 1.0/0.5}}
return win
def _get_window(start, end):
"""Return window which has length as much as parameter start - end"""
from scipy.signal import hann
window = 1 - np.r_[hann(4)[:2],
np.ones(np.abs(end - start) - 4),
hann(4)[-2:]].T
return window
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)