本文整理汇总了Python中scipy.signal.hann函数的典型用法代码示例。如果您正苦于以下问题:Python hann函数的具体用法?Python hann怎么用?Python hann使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hann函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:gboyes,项目名称:photmo,代码行数:25,代码来源:material.py
示例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.
开发者ID:danustc,项目名称:Image_toolbox,代码行数:35,代码来源:correlation.py
示例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
开发者ID:crbates,项目名称:ay250,代码行数:33,代码来源:audio.py
示例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
开发者ID:mvdoc,项目名称:mne-python,代码行数:7,代码来源:stim.py
示例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)
开发者ID:heltPython,项目名称:medicalRadar,代码行数:32,代码来源:processing.py
示例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
开发者ID:Anevar,项目名称:mne-python,代码行数:59,代码来源:stim.py
示例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])
开发者ID:chris-b1,项目名称:scipy,代码行数:8,代码来源:test_windows.py
示例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
开发者ID:sudo-nim,项目名称:mne-python,代码行数:56,代码来源:stim.py
示例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])
开发者ID:arichar6,项目名称:scipy,代码行数:12,代码来源:test_windows.py
示例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
开发者ID:dengemann,项目名称:mne-python,代码行数:15,代码来源:mxne_inverse.py
示例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)
开发者ID:anirudh9119,项目名称:SpeechSyn,代码行数:35,代码来源:accent.py
示例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
开发者ID:twkun,项目名称:MEFE_Python,代码行数:7,代码来源:tools.py
示例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
开发者ID:andy-d-palmer,项目名称:pyMS,代码行数:7,代码来源:smoothing.py
示例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
开发者ID:rubert,项目名称:Linear-Array-Processing-Python,代码行数:32,代码来源:attenuation.py
示例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()
开发者ID:jlugao,项目名称:aliasing_demo,代码行数:31,代码来源:pds3.py
示例16: drop_regn
def drop_regn(tvec, y, drv_th, len_th = 3, smwd = 5):
dy = deriv(y)
win = signal.hann(smwd)
smdy = signal.convolve(dy, win, mode = 'same')/sum(win)
drop = []
for i,d in enumerate(smdy):
if d < drv_th:
drop.append(i)
dif_drop = deriv(drop)
regn = []
for i,dd in enumerate(dif_drop):
if dd == 1:
regn.append(drop[i])
else:
if len(regn) >= len_th - 1:
regn.append(drop[i])
break
else:
regn = []
if len(regn):
return tvec[regn[0]],tvec[regn[-1]]
else:
return None
开发者ID:aloejhb,项目名称:dsb_model,代码行数:26,代码来源:cc_strat.py
示例17: select_events
def select_events(nevents,nfeatures):
global groups
fftbins = 8192
featurewidth = 16
print "Selecting %d random spectral features.." % nfeatures
feature_bins = np.random.randint(featurewidth/2,(fftbins/8),nfeatures)
print "Selecting %d random audio events.." % nevents
events = np.random.randint(0,len(faudio)-grain_mid,nevents)
# Initialise features array with the first variable as index
features = np.zeros((nfeatures+1,nevents))
features[0] = np.arange(0,nevents)
print "Computing audio event spectrograms.."
# For each event..
for i in range(0,nevents):
# Calculate spectrogram for the event
_fftevent = faudio[events[i]:min(events[i]+grain_mid,len(faudio))]*sig.hann(grain_mid)
mags = abs(rfft(_fftevent,fftbins))
mags = 20*log10(mags) # dB
mags -= max(mags) # normalise to 0dB max
# Calculate each feature for this event
for j in range(0,nfeatures):
features[j+1][i] = abs(np.mean(abs(mags[(feature_bins[j]-featurewidth/2):(feature_bins[j]+featurewidth/2)])))
print "Clustering events with K-Means algorithm.."
groups = kmeans(np.transpose(features[1:,:]),tracks,minit='points',iter=30)[1]
return [events,groups]
开发者ID:alexobviously,项目名称:Dismantler,代码行数:25,代码来源:main.py
示例18: show_magnitued
def show_magnitued(file_name):
# read audio samples
input_data = read(file_name)
audio = input_data[1]
print(audio)
# apply a Hanning window
window = hann(1024)
audio = audio[0:1024] * window
# fft
mags = abs(rfft(audio))
# convert to dB
mags = 20 * scipy.log10(mags)
# normalise to 0 dB max
# mags -= max(mags)
file = open('tmp.txt', 'w')
for i in mags:
file.write(str(i) + '\n')
file.close()
# plot
plt.plot(mags)
# label the axes
plt.ylabel("Magnitude (dB)")
plt.xlabel("Frequency Bin")
# set the title
plt.title(file_name + " Spectrum")
plt.show()
开发者ID:sookool99,项目名称:MIREX_2015,代码行数:26,代码来源:audoPlotting.py
示例19: fft_transformation
def fft_transformation(data,scale):
#hanning window to smooth the edge
xs = np.multiply(data, signal.hann(DEFAULT_FFT_SIZE, sym=0))
#fft transfer
xf = np.abs(np.fft.rfft(xs))
#200HZ ~ 2000HZ, 56 * 32Hz(size) , scale: 44100/16384 = 2.7
xfp = 20*np.log10(np.clip(xf, 1e-20, 1e100))
sub_fin = 0L
sumdb=0
num=0
for n in xrange(1,FIN_BIT+1):
p1 = 0
p2 = 0
if len(table)< 32:
b0 = 700*(10**((n-1)*mel/2596)-1)
b1 = 700*(10**((n+1)*mel/2596)-1)
table.update({n:[b0,b1]})
else:
b0 = table[n][0]
b1 = table[n][1]
for i in xrange(int(b0),int((b1+1))):
fp = xfp[int(i/scale)]
p1 += fp*i
p2 += fp
num += 1
sumdb += p2
if (p1/p2-(b0+b1)/2)/(b1-b0) >= 0:
sub_fin = sub_fin | (1<<(n-1))
return sub_fin,sumdb/num
开发者ID:faygao52,项目名称:FITII,代码行数:31,代码来源:Auana.py
示例20: updatePic
def updatePic(i):
global data, wbuffer , line
stream.write(data)
data = wf.readframes(CHUNK)
data16=np.fromstring(data,dtype=np.int16)
wbuffer[:CHUNK]=wbuffer[CHUNK:]
wbuffer[CHUNK:]=data16
wbuffer=np.reshape(wbuffer, CHUNK*2)
wbuffer *= signal.hann(CHUNK*2, sym=0) #128
n=len(data16)
k=np.arange(n)
T=n/SAMPLE_RATE
frq=k/T
frq=frq[range(int(n/2))]
#import pdb ; pdb.set_trace()
fftdata=np.fft.fft(data16)
reduced=reduce_noise(fftdata)
dispfft=(fftdata/n)[range(int(n/2))]
dispfft_reduced=(reduced/n)[range(int(n/2))]
#ifftdata=np.fft.ifft(fftdata).real
ifftdata=np.fft.ifft(reduced).real
data=ifftdata.astype(np.int16).tostring()
line.set_data(frq,abs(dispfft)) # plotting the spectrum
line1.set_data(frq, abs(dispfft_reduced))
return line
开发者ID:jiangpen,项目名称:noiseReduction,代码行数:28,代码来源:fftplot.py
注:本文中的scipy.signal.hann函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论