本文整理汇总了Python中scipy.signal.hann函数的典型用法代码示例。如果您正苦于以下问题:Python hann函数的具体用法?Python hann怎么用?Python hann使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hann函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, path_to_file, scalar=1, windowed=True):
self.path = path_to_file
i = cv2.imread(self.path, cv2.IMREAD_UNCHANGED)
if i is None:
raise Exception
if scalar != 1:
i = cv2.resize(i, (0, 0), fx=scalar, fy=scalar)
self.image = i.astype(float) / 255.0
else:
self.image = i.astype(float) / 255.0
self.height, self.width, self.planes = np.shape(self.image)
if self.planes < 4:
z = np.ones((self.height, self.width, 4))
z[:, :, 0:self.planes] = self.image
self.image = z
self.height, self.width, self.planes = np.shape(self.image)
if windowed:
win = np.vstack(hann(self.height)) * hann(self.width)
for i in range(self.planes):
self.image[:, :, i] *= win
self.image[:, :, 0:3] *= 1. / linalg.norm(self.image[:, :, 0:3]) # normalize
示例2: cross_corr_stack_self
def cross_corr_stack_self(stack, adj_ref = False, verbose = True, pivot_slice = 0):
'''
Align a stack to itself. If adj_ref is True, then align each slice to the neighboring slice preceeding it.
Added: subpixel precision
'''
nz, ny, nx = stack.shape
hy = ny//2
hx = nx//2
shift_coord = np.zeros([nz, 2])
hann_w = signal.hann(nx)
hann_h = signal.hann(ny)
hfilter = np.outer(hann_h, hann_w)
bpf = np.fft.fftshift(bpd(ny,nx))
container_1 = pyfftw_container(ny, nx)
container_2 = pyfftw_container(ny, nx)
container_invx = pyfftw_container(ny, nx, bwd = True)
if np.isscalar(pivot_slice):
ref_frame = stack[pivot_slice]
else:
ref_frame = pivot_slice
for ii in range(nz):
shy, shx = cross_corr_shift_frame(ref_frame, stack[ii], container_1, container_2, container_invx, filter_freq = 'han', filter_pattern = hfilter )[:2]
if verbose:
print("slice ", ii+1, '-->', shy, shx)
shift_coord[ii] = np.array([-shy, -shx])
# then we have to shift im 2 by (-shy, -shx)
if adj_ref:
# if the stack is aligned in the adjacent mode, them each slice should be updated in place; otherwise we can just return the shift coordinates.
shifted_frame = interpolation.shift(stack[ii+1],shift = [-shy, -shx])
ref_frame = shifted_frame
stack[ii+1] = shifted_frame
return shift_coord # Hmmmm, this is much nicer.
示例3: basefreq
def basefreq(audiofile):
"""
This function reads in the audio file and does the hann windowed fft of
the right input. It then smooths the output using a gaussian filter and
then finds the peaks. It returns the peaks in the right audio channel since
testing showed there was no significant difference in the two.
"""
#read the data into an ndarray using scikits-audiolab
data, rate, enc = al.aiffread(audiofile)
#split the left and right channel
datar = data[:,1]
datal = data[:,0]
#take the fft of both of the channels with the hann window applied
#the hann window reduces spectral leakage in the FFT
dftr = abs(fft.fft(datar*signal.hann(len(datar))))
dftl = abs(fft.fft(datal*signal.hann(len(datal))))
#compute the frequencies in the FFT
freq = float(rate)/float(len(datar))
freqs = np.arange(len(dftr)/2+99)*freq
dftr = dftr[0:np.size(dftr)/2]
dftl = dftl[0:np.size(dftr)/2]
#smooth the fft with a gaussian
c = signal.gaussian(100,20)
dftr = signal.convolve(dftr,c)
dftl = signal.convolve(dftl,c)
#find the significant peaks in each channel
peaksr = findpeaks(dftr,freqs)
peaksl = findpeaks(dftl,freqs)
#plot the output fft for testing
#plt.plot(freqs,dftr)
#plt.show()
#print peaksr
return peaksr
示例4: _get_window
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
示例5: window
def window(f,start,stop,type='blackman'):
"""
runs the data through a hamming window.
@param f: The data matrix
@param start: The start index of the hamming window.
@param stop: The end index of the hamming window.
"""
h=numpy.zeros(f.shape,dtype=float)
if len(h.shape)==1:
if type=='hamming':
h[start:stop]=signal.hamming(stop-start)
elif type=='blackman':
h[start:stop]=signal.blackman(stop-start)
elif type=='hann':
h[start:stop]=signal.hann(stop-start)
elif type=='blackmanharris':
h[start:stop]=signal.blackmanharris(stop-start)
elif type=='rectangular' or type=='rect' or type=='boxcar':
h[start:stop]=signal.boxcar(stop-start)
else:
if type=='hamming':
h[:,start:stop]=signal.hamming(stop-start)
elif type=='blackman':
h[:,start:stop]=signal.blackman(stop-start)
elif type=='hann':
h[:,start:stop]=signal.hann(stop-start)
elif type=='blackmanharris':
h[:,start:stop]=signal.blackmanharris(stop-start)
elif type=='rectangular' or type=='rect' or type=='boxcar':
h[:,start:stop]=signal.boxcar(stop-start)
return numpy.multiply(f,h)
示例6: eliminate_stim_artifact
def eliminate_stim_artifact(raw, events, event_id, tmin=-0.005,
tmax=0.01, mode='linear'):
"""Eliminates stimulations artifacts from raw data
The raw object will be modified in place (no copy)
Parameters
----------
raw : Raw object
raw data object.
events : array, shape (n_events, 3)
The list of events.
event_id : int
The id of the events generating the stimulation artifacts.
tmin : float
Start time of the interpolation window in seconds.
tmax : float
End time of the interpolation window in seconds.
mode : 'linear' | 'window'
way to fill the artifacted time interval.
'linear' does linear interpolation
'window' applies a (1 - hanning) window.
Returns
-------
raw: Raw object
raw data object.
"""
if not raw._preloaded:
raise RuntimeError('Modifying data of Raw is only supported '
'when preloading is used. Use preload=True '
'(or string) in the constructor.')
events_sel = (events[:, 2] == event_id)
event_start = events[events_sel, 0]
s_start = int(np.ceil(raw.info['sfreq'] * tmin))
s_end = int(np.ceil(raw.info['sfreq'] * tmax))
picks = pick_types(raw.info, meg=True, eeg=True, eog=True, ecg=True,
emg=True, ref_meg=True, misc=True, chpi=True,
exclude='bads', stim=False, resp=False)
if mode == 'window':
window = 1 - np.r_[signal.hann(4)[:2],
np.ones(np.abs(s_end - s_start) - 4),
signal.hann(4)[-2:]].T
for k in range(len(event_start)):
first_samp = int(event_start[k]) - raw.first_samp + s_start
last_samp = int(event_start[k]) - raw.first_samp + s_end
data, _ = raw[picks, first_samp:last_samp]
if mode == 'linear':
x = np.array([first_samp, last_samp])
f = interpolate.interp1d(x, data[:, (0, -1)])
xnew = np.arange(first_samp, last_samp)
interp_data = f(xnew)
raw[picks, first_samp:last_samp] = interp_data
elif mode == 'window':
raw[picks, first_samp:last_samp] = data * window[np.newaxis, :]
return raw
示例7: test_basic
def test_basic(self):
assert_allclose(signal.hann(6, sym=False),
[0, 0.25, 0.75, 1.0, 0.75, 0.25])
assert_allclose(signal.hann(6, True),
[0, 0.3454915028125263, 0.9045084971874737,
0.9045084971874737, 0.3454915028125263, 0])
assert_allclose(signal.hann(7),
[0, 0.25, 0.75, 1.0, 0.75, 0.25, 0])
示例8: eliminate_stim_artifact
def eliminate_stim_artifact(raw, events, event_id, tmin=-0.005, tmax=0.01, mode="linear"):
"""Eliminates stimulations artifacts from raw data
The raw object will be modified in place (no copy)
Parameters
----------
raw: Raw object
raw data object
events: array, shape (n_events, 3)
The list of events
event_id: int
The id of the events generating the stimulation artifacts.
tmin : float
Start time before event in seconds
tmax : float
End time after event in seconds
mode : 'linear' | 'window'
way to fill the artifacted time interval
'linear' does linear interpolation
'window' applies a (1 - hanning) window
Returns
-------
raw: Raw object
raw data object
"""
if not raw._preloaded:
raise RuntimeError(
"Modifying data of Raw is only supported "
"when preloading is used. Use preload=True "
"(or string) in the constructor."
)
events_sel = events[:, 2] == event_id
event_start = events[events_sel, 0]
s_start = np.ceil(raw.info["sfreq"] * np.abs(tmin))
s_end = np.ceil(raw.info["sfreq"] * tmax)
picks = pick_types(raw.info, meg=True, eeg=True)
if mode == "window":
window = 1 - np.r_[signal.hann(4)[:2], np.ones(s_end + s_start - 4), signal.hann(4)[-2:]].T
for k in range(len(event_start)):
first_samp = event_start[k] - raw.first_samp - s_start
last_samp = event_start[k] - raw.first_samp + s_end
data, _ = raw[picks, first_samp:last_samp]
if mode == "linear":
x = np.array([first_samp, last_samp])
f = interpolate.interp1d(x, data[:, (0, -1)])
xnew = np.arange(first_samp, last_samp)
interp_data = f(xnew)
raw[picks, first_samp:last_samp] = interp_data
elif mode == "window":
raw[picks, first_samp:last_samp] = data * window[np.newaxis, :]
return raw
示例9: test_basic
def test_basic(self):
assert_allclose(signal.hann(6, sym=False),
[0, 0.25, 0.75, 1.0, 0.75, 0.25])
assert_allclose(signal.hann(7, sym=False),
[0, 0.1882550990706332, 0.6112604669781572,
0.9504844339512095, 0.9504844339512095,
0.6112604669781572, 0.1882550990706332])
assert_allclose(signal.hann(6, True),
[0, 0.3454915028125263, 0.9045084971874737,
0.9045084971874737, 0.3454915028125263, 0])
assert_allclose(signal.hann(7),
[0, 0.25, 0.75, 1.0, 0.75, 0.25, 0])
示例10: _window_evoked
def _window_evoked(evoked, size):
"""Window evoked (size in seconds)"""
if isinstance(size, (float, int)):
lsize = rsize = float(size)
else:
lsize, rsize = size
evoked = deepcopy(evoked)
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
示例11: __init__
def __init__(self,
X_mean=None,
X_std=None,
shuffle=0,
seq_len=8000,
use_window=0,
use_spec=0,
frame_size=200,
file_name='accent_tbptt',
batch_size=64,
range_start=0,
range_end=None,
**kwargs):
self.X_mean = X_mean
self.X_std = X_std
self.shuffle = shuffle
self.seq_len = seq_len
self.use_window = use_window
self.use_spec = use_spec
self.frame_size = frame_size
self.file_name = file_name
if self.use_window:
if self.use_spec:
if not is_power2(self.frame_size):
raise ValueError("Provide a number which is power of 2,\
for fast speed of DFT.")
if np.mod(self.frame_size, 2)==0:
self.overlap = self.frame_size / 2
else:
self.overlap = (self.frame_size - 1) / 2
self.window = signal.hann(self.frame_size)[None, :].astype(theano.config.floatX)
self.batch_size = batch_size
self.range_start = range_start
self.range_end = range_end
super(Accent_h5, self).__init__(**kwargs)
示例12: data_w_hann
def data_w_hann(dt,frame=256):
temp = []
_t = sig.hann(frame)
fx = frame*0.5
#temp = [sum(np.array(dt[x*fx:x*fx+frame]*_t)**2) for x in range(int(len(dt)/fx -1))]
temp = [np.log(sum(np.abs(dt[x*fx:x*fx+frame]*_t))) for x in range(int(len(dt)/fx -1))]
return temp
示例13: apodization
def apodization(mzs,intensities,w_size=10):
import scipy.signal as signal
win = signal.hann(w_size)
win = signal.slepian(w_size,0.3)
intensities = signal.fftconvolve(intensities, win, mode='same') / sum(win)
intensities[intensities<1e-6]=0
return intensities
示例14: CalculateSpectrumBlock
def CalculateSpectrumBlock(self, region):
'''Return the power spectrum of a region based on a Welch-Bartlett method.
The block used in each FFT is half the length of the total window.
The step size is half the size of the FFT window.
Average over A-lines.
This function assumes the size of the region is divisible by 4.
It uses a zoomed in FFT to compute the power spectrum. The zoomed in FFT is given by the
chirpz transform.
'''
from scipy.signal import hann,convolve
import numpy
from chirpz import chirpz
points = region.shape[0]
points -= points%4
points /= 2
#######SAMPLE REGION#############
maxDataWindow = region[0:2*points, :]
#compute 3 fourier transforms and average them
#Cutting off the zero-value end points of the hann window
#so it matches Matlab's definition of the function
windowFunc = hann(points+2)[1:-1].reshape(points,1)
fftSample = numpy.zeros(points)
for f in range(3):
dataWindow = maxDataWindow[(points/2)*f:(points/2)*f + points, :]*windowFunc
for l in range(dataWindow.shape[1]):
fftSample += abs(chirpz(dataWindow[:,l], self.cztA, self.cztW, points))**2
return fftSample
示例15: plot
def plot(self):
self.amostrasporseg=15*5 #samples/sec
frequenciasinal=5 #Hz
omega= frequenciasinal
self.z=2*np.pi*np.arange(0,2*np.pi,1/self.amostrasporseg)
y=np.sin(self.z*omega)
k=y*signal.hann(len(y))
ylinha= 20*np.log10(abs(np.fft.fft(k,2048)))
ylinha=np.tile(ylinha,3)
zlinha=np.linspace(-2,4,len(ylinha))
self.figure.subplots_adjust(bottom=.75)
gs = gridspec.GridSpec(5, 1,height_ratios=[0.2,1,0.25,1,0.2])
ax =self.figure.add_subplot(gs[1])
self.plot2,=plt.plot(zlinha,ylinha)
plt.title('Espectro do sinal')
plt.xlabel(r'$\omega$')
plt.ylabel(r'|X($\omega$)|')
plt.xticks((-2,-1,0,1,2,3,4),[r'$-2\pi$',r'$-\pi$','0',r'$\pi$',r'$2\pi$',r'$3\pi$',r'$4\pi$'])
#ax.set_xticks([-0.0442,0.0442], minor=True)
ax.xaxis.grid(True,which='major',linewidth=0.75,color='k',linestyle='--')
self.beta=self.figure.add_subplot(gs[3])
self.plot3,=plt.plot(self.z,y,label='Amostragem Correta')
plt.plot(self.z,y,'o',label='Amostragem Fixa')
plt.legend(loc='upper right')
self.beta.set_xlabel(r't')
self.beta.set_ylabel(r'x(t)')
self.beta.set_xlim([0,2*np.pi])
self.figure.tight_layout()