• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python scipy.fft函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中scipy.fft函数的典型用法代码示例。如果您正苦于以下问题:Python fft函数的具体用法?Python fft怎么用?Python fft使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了fft函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: getMSD

def getMSD(d1, d2):
    diff = 0
    d11 = []
    d22 = []
    
    index = 0
    for index in xrange(9):
        chunk = d1[index * 22050: index * 22050 + 22050]
        x = cp.fft(chunk)
        maximum1 = max(x)
        d11.append(maximum1)
         
    index = 0
    for index in xrange(9):
        chunk = d2[index * 22050: index * 22050 + 22050]
        x = cp.fft(chunk)
        maximum1 = max(x)
        d22.append(maximum1)
    
    currentMax1 = max(d11)
    currentMax2 = max(d22)
    
    for x in xrange(len(d11)):
#         diff += abs(d11[x]/currentMax1 - d22[x]/currentMax2) * abs(d11[x]/currentMax1 - d22[x]/currentMax2)
        diff += abs(d11[x] - d22[x]) * abs(d11[x] - d22[x])

    diff /= len(d11)
    
    return diff
开发者ID:areshero,项目名称:hahahha,代码行数:29,代码来源:audio.py


示例2: problem4

def problem4():
	# read in tada.wav
	rate, tada = wavfile.read('tada.wav')
	
	# upon inspection, we find that tada.wav is a stereo audio file. 
	# we create stereo white noise that lasts 10 seconds
	L_white = sp.int16(sp.random.randint(-32767,32767,rate*10))
	R_white = sp.int16(sp.random.randint(-32767,32767,rate*10))
	white = sp.zeros((len(L_white),2))
	white[:,0] = L_white
	white[:,1] = R_white
	
	# pad tada signal with zeros
	padded_tada = sp.zeros_like(white)
	padded_tada[:len(tada)] = tada
	ptada = padded_tada
	
	# fourier transforms
	ftada = sp.fft(ptada,axis=0)
	fwhite = sp.fft(white,axis=0)
	
	# inverse transform of convolution
	out = sp.ifft((ftada*fwhite),axis=0)
	
	# prepping output and writing file
	out = sp.real(out)
	scaled = sp.int16(out / sp.absolute(out).max() * 32767)
	wavfile.write('my_tada_conv.wav',rate,scaled)
开发者ID:tkchris93,项目名称:ACME,代码行数:28,代码来源:solutions.py


示例3: get_envelope

def get_envelope(R,dim=1):
    """
    Returns the complex version of the input signal R.
    @param R: The input data matrix.
    @param dim: The dimension along which the envelope is to be taken. default: dim=1
    """
    if dim==0:
        R=R.T
    if len(R.shape)==1:
        freqs=scipy.fft(R)
        length=len(R)/2
        freqs[length:]=0
        freqs[1:length]=2*freqs[1:length]
        ## freqs[1:length]=freqs[1:length]
        
        env=scipy.ifft(freqs)
    else:
        freqs=scipy.fft(R)
        length=R.shape[dim]/2
        #Something is fishy here:
        freqs[:,length:]=0
        freqs[:,1:length]=2*freqs[0,1:length]
        ## freqs[:,1:length]=freqs[0,1:length]
        
        env=scipy.ifft(freqs)
        if dim==0:
            return env.T

    return env
开发者ID:heltPython,项目名称:medicalRadar,代码行数:29,代码来源:processing.py


示例4: itakura_saito_spectrum_distance

def itakura_saito_spectrum_distance(s,shat,winfunc):
    size = min(len(s),len(shat))
    window = winfunc(size)
    s = s[0:size]
    shat = shat[0:size]
    s_amp = sp.absolute(sp.fft(s*window))
    shat_amp = sp.absolute(sp.fft(shat*window))
    return sp.mean(sp.log(s_amp / shat_amp) + (shat_amp/s_amp) - 1.0)
开发者ID:brabeeba,项目名称:Speaker-recognition-server,代码行数:8,代码来源:distance.py


示例5: log_spectrum_distance

def log_spectrum_distance(s,shat,winfunc):
    size = min(len(s),len(shat))
    window = winfunc(size)
    s = s[0:size]
    shat = shat[0:size]
    s_amp = sp.absolute(sp.fft(s*window))
    shat_amp = sp.absolute(sp.fft(shat*window))
    return sp.sqrt(sp.mean((sp.log10(s_amp / shat_amp)*10.0)**2.0))
开发者ID:brabeeba,项目名称:Speaker-recognition-server,代码行数:8,代码来源:distance.py


示例6: prob5

def prob5():
	rate, sig = wavfile.read('tada.wav')
	sig = sp.float32(sig)
	noise = sp.float32(sp.random.randint(-32767,32767,sig.shape))
	out = sp.ifft(sp.fft(sig)*sp.fft(noise))
	out = sp.real(out)
	out = sp.int16(out/sp.absolute(out).max() * 32767)
	wavfile.write('white-conv.wav',rate,out)
开发者ID:davidreber,项目名称:Labs,代码行数:8,代码来源:filter_conv_solutions.py


示例7: fourierTransform

    def fourierTransform(self, fromPos, toPos, only = []):
        self.checkToPos(toPos)
        if len(only) > 0:
            self.allFid[toPos] = np.array([fftshift(fft(self.allFid[fromPos][fidIndex])) for fidIndex in only])
        else:
            self.allFid[toPos] = np.array([fftshift(fft(fid)) for fid in self.allFid[fromPos]])

        self.frequency = np.linspace(-self.sweepWidthTD2/2,self.sweepWidthTD2/2,len(self.allFid[fromPos][0]))
开发者ID:bennomeier,项目名称:pyNMR,代码行数:8,代码来源:nmrDataMod.py


示例8: fftconv

def fftconv(x, y):
    """ Convolution of x and y using the FFT convolution theorem. """
    n = np.int(np.round(2 ** np.ceil(np.log2(len(x))))) + 1
    X, Y, x_y = fft(x, n), fft(y, n), []
    for i in range(n):
        x_y.append(X[i] * Y[i])

    # Returns the inverse Fourier transform with padding correction
    return fft.ifft(x_y)[4:len(x)+4]
开发者ID:smartass101,项目名称:pycwt,代码行数:9,代码来源:helpers.py


示例9: algoChannelSelection

def algoChannelSelection(left, right):

    ''' Algorithm which automatically selects the channel with dominant vocals from a stereo flamenco recording
    based on spectral band energies as described in section 2-A-I of

    Kroher, N. & Gomez, E. (2016). Automatic Transcription of Flamenco Singing from Polyphonic Music Recordings.
    ACM / IEEE Transactions on Audio, Speech and Language Processing, 24(5), pp. 901-913.

    :param left: samples of the left audio channel in 44.1kHz
    :param right: samples of the right audio channel in 44.1kHz
    :return: index of the dominant vocal channel (0 = left, 1 = right)
    '''

    # PARAMETERS
    fs = 44100 # sample rate
    wSize = 2048 # window size in samples
    hSize = 2048 # hop size in samples
    fftSize = 2048 # FFT size
    freqGuitLow = 80.0 # lower bound for guitar band
    freqGuitHigh = 400.0 # upper bound for guitar band
    freqVocLow = 500.0 # lower bound for vocal band
    freqVocHigh = 6000.0 # higher bound for vocal band

    # INIT
    window = hanning(wSize)
    numFrames = int(math.floor(float(len(left))/float(wSize)))
    # bin indices corresponding to freqeuncy band limits
    indGuitLow = int(round((freqGuitLow/fs)*fftSize))
    indGuitHigh = int(round((freqGuitHigh/fs)*fftSize))
    indVocLow = int(round((freqVocLow/fs)*fftSize))
    indVocHigh = int(round((freqVocHigh/fs)*fftSize))

    # frame-wise computation of the spectral band ratio
    sbrL = []
    sbrR = []
    for i in range(0,numFrames-100):
        frameL = left[i*hSize:i*hSize+wSize]
        specL = fft(frameL*window) / fftSize
        specL = abs(specL * conj(specL))
        guitMag = sum(specL[indGuitLow:indGuitHigh],0)
        vocMag = sum(specL[indVocLow:indVocHigh],0)
        sbrL.append(20*math.log10(vocMag/guitMag))
        frameR = right[i*hSize:i*wSize+wSize]
        specR = fft(frameR*window) / fftSize
        specR = abs(specR * conj(specR))
        guitMag = sum(specR[indGuitLow:indGuitHigh],0)
        vocMag = sum(specR[indVocLow:indVocHigh],0)
        sbrR.append(20*math.log10(vocMag/guitMag))

    # select channel based on mean SBR
    if mean(sbrL)>=mean(sbrR):
        ind = 0
    else:
        ind = 1

    return ind
开发者ID:NadineKroher,项目名称:PyCante,代码行数:56,代码来源:algoChannelSelection.py


示例10: calculation

 def calculation(self, data):
     if(isinstance(data[0], types.ListType)):
         freq = [np.abs(fft(l)/len(l))[1:len(l)/2] for l in data]
         freq = [n.tolist() for n in freq]
     else:
         l = data
         freq = np.abs(fft(l)/len(l))[1:len(l)/2]
         #freq = [[v] for v in freq]
         #freq = freq.tolist()
     return freq  # .tolist()
开发者ID:ManuKrapf,项目名称:IntTec,代码行数:10,代码来源:classifier.py


示例11: prob3

def prob3():
	rate1,sig1 = wavfile.read('chopinw.wav')
	n = sig1.shape[0]
	rate2,sig2 = wavfile.read('balloon.wav')
	m = sig2.shape[0]
	sig1 = sp.append(sig1,sp.zeros((m,2)))
	sig2 = sp.append(sig2,sp.zeros((n,2)))
	f1 = sp.fft(sig1)
	f2 = sp.fft(sig2)
	out = sp.ifft((f1*f2))
	out = sp.real(out)
	scaled = sp.int16(out/sp.absolute(out).max() * 32767)
	wavfile.write('test.wav',rate1,scaled)
开发者ID:davidreber,项目名称:Labs,代码行数:13,代码来源:filter_conv_solutions.py


示例12: makeIR

def makeIR(wav_in,wav_out,fs,duration,noise=0.025):
    """ measures the response of a speaker (+amp+mic) and build an IR """
    # step 1: full duplex playback and recording. Input: provided sweep wav file
    # output: recorded time response
    ecasound_cmd="ecasound -f:16,1,%i -a:1 -i jack,system,capture " + \
    " -o /tmp/capture.wav -a:2 -i %s -o jack,system -t %i"
    ecasound_cmd=ecasound_cmd%(int(fs),wav_in,int(duration))
    # run capture    
    os.system(ecasound_cmd)
    # load input and capture wave files 
    time.sleep(3)
    f=wave.open(wav_in,'rb')
    len1=f.getnframes()
    #nc1=f.getnchannels()
    #bp1=f.getsampwidth()
    data=f.readframes(len1)
    f.close()
    Y1=scipy.float32(scipy.fromstring(data,dtype='int16'))
    f=wave.open('/tmp/capture.wav','rb')
    len2=f.getnframes()
    #nc1=f.getnchannels()
    #bp1=f.getsampwidth()
    data=f.readframes(len2)
    f.close()    
    Y2=scipy.float32(scipy.fromstring(data,dtype='int16'))
    # truncate and normalize wave file 
    #(or we could pad the shortest to the longest... TODO!)
    minlen = min([len1,len2])
    Y2=Y2[0:minlen]
    Y2=Y2/max(abs(Y2))
    Y1=Y1[0:minlen]
    Y1=Y1/max(abs(Y1))
    # compute frequency response function as ration of both spectra
    FRF=scipy.fft(Y2)/scipy.fft(Y1)
    # compute impulse response as inverse FFT of FRF
    IRraw=scipy.real(scipy.ifft(FRF))
    # get rid of initial lag in IR
    thr=max(abs(IRraw))*noise
    offset=max([0 , min(min(scipy.where(abs(IRraw)>thr)))-5 ])
    IR=IRraw[offset:-1] 
    IRnorm=IR/max(abs(IR))
    # TODO: add post pro options such as low/high pass and decay
    # write output IR
    f = wave.open(wav_out, 'w')
    f.setparams((1, 2, fs, 0, 'NONE', 'not compressed'))
    maxVol=2**15-1.0 #maximum amplitude
    wvData=""
    for i in range(len(IRnorm)):
        wvData+=pack('h', maxVol*IRnorm[i])
    f.writeframes(wvData)
    f.close()
开发者ID:jcugnoni,项目名称:picabsim,代码行数:51,代码来源:makeIR.py


示例13: load_validation_set

def load_validation_set():
    """
    Output
        a tuple of features: (fft features, mfcc features, mean-std features)
    Description
        extracts three types of features from validation set.
    """
    ffts = dict()
    mfccs = dict()
    mean_stds = dict()

    for i in validation_ids:
        path = './validation/validation.{i}.wav'.format(i=i)

        _, X = read_wav(path)

        # FFT
        fft = np.array(abs(sp.fft(X)[:1000]))
        ffts.update({i: fft})

        # MFCC
        ceps, mspec, spec = mfcc(X)
        num_ceps = len(ceps)
        x = np.mean(ceps[int(num_ceps*1/10):int(num_ceps*9/10)], axis=0)
        mfccs.update({i: x})


        # Mean-Std
        [Fs, x] = audioBasicIO.readAudioFile(path);
        F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 0.050*Fs, 0.025*Fs);
        mean_std = []
        for f in F:
            mean_std.extend([f.mean(), f.std()])
        mean_stds.update({i: np.array(mean_std)})
    return (ffts, mfccs, mean_stds)
开发者ID:hyunwooj,项目名称:unm-cs429,代码行数:35,代码来源:run.py


示例14: _fft

 def _fft(self, data):
     data_length = len(data)
     frequencies = scipy.fft(data) / data_length
     frequencies = frequencies[range(data_length / 2)]
     frequencies[0] = 0
     frequencies = np.abs(frequencies)
     return frequencies
开发者ID:CrazyCrud,项目名称:interactiondesign-python,代码行数:7,代码来源:analyze_values.py


示例15: printer

def printer(function):
    window[function] = eval("scipy.signal.%s(size)" % function)
    pylab.plot(numpy.abs(window[function]))
    pylab.xlim(0, size - 1)
    pylab.savefig("%s-%03d.png" % (function, speed))
    pylab.close()

    fft[function] = scipy.fft(window[function])
    pylab.loglog(numpy.abs(fft[function])[0 : size / 2 + 1])
    pylab.savefig("%s-fft-%03d.png" % (function, speed))
    pylab.close()

    sinus[function] = scipy.fft(y * window[function])
    pylab.loglog(numpy.abs(sinus[function])[0 : size / 2 + 1])
    pylab.savefig("%s-sinus-%03d.png" % (function, speed))
    pylab.close()
开发者ID:almorel,项目名称:lab,代码行数:16,代码来源:generate.py


示例16: get_amplitude

 def get_amplitude(self, signal, l):
     if self.amplitude.has_key(l):
         return self.amplitude[l]
     else:
         amp = sp.absolute(sp.fft(get_frame(signal, self.winsize, l) * self.window))
         self.amplitude[l] = amp
         return amp
开发者ID:jeromexlee,项目名称:CS289A,代码行数:7,代码来源:LTSD.py


示例17: save_plotSpectrum

def save_plotSpectrum(y,Fs,image_name):
    """
    Plots a Single-Sided Amplitude Spectrum of y(t)
    """
    fig = Figure(linewidth=0.0)
    fig.set_size_inches(fig_width,fig_length, forward=True)
    Figure.subplots_adjust(fig, left = fig_left, right = fig_right, bottom = fig_bottom, top = fig_top, hspace = fig_hspace)
    n = len(y) # length of the signal

    _subplot = fig.add_subplot(2,1,1)        
    print "Fi"
    _subplot.plot(arange(0,n),y)
    xlabel('Time')
    ylabel('Amplitude')
    _subploti_2=fig.add_subplot(2,1,2)
    k = arange(n)
    T = n/Fs
    frq = k/T # two sides frequency range
    frq = frq[range(n/2)] # one side frequency range

    Y = fft(y)/n # fft computing and normalization
    Y = Y[range(n/2)]

    _subplot_2.plot(frq,abs(Y),'r') # plotting the spectrum
    xlabel('Freq (Hz)')
    ylabel('|Y(freq)|')
    print "here"
    canvas = FigureCanvasAgg(fig)
    if '.eps' in outfile_name:
        canvas.print_eps(outfile_name, dpi = 110)
    if '.png' in outfile_name:
        canvas.print_figure(outfile_name, dpi = 110)
开发者ID:FomkaV,项目名称:wifi-arsenal,代码行数:32,代码来源:non_wifi_interference_analysis.py


示例18: test

def test():
    run_c("fft.c")
    x_re = [float(i) for i in open("x_re")]
    x_im = [float(i) for i in open("x_im")]
    fft_x_re = [float(i) for i in open("fft_x_re")]
    fft_x_im = [float(i) for i in open("fft_x_im")]

    time_complex = [i + (j*1.0) for i, j in zip(x_re, x_im)]
    numpy_complex = s.fft(time_complex)
    numpy_magnitude = n.abs(numpy_complex)

    chips_complex = [i + (j*1.0j) for i, j in zip(fft_x_re, fft_x_im)]
    chips_magnitude = n.abs(chips_complex)

    f, subplot = pyplot.subplots(3, sharex=True)

    pyplot.subplots_adjust(hspace=1.0)
    subplot[0].plot(x_re, 'g')
    subplot[1].plot(numpy_magnitude, 'r')
    subplot[2].plot(chips_magnitude, 'b')
    pyplot.xlim(0, 1023)
    subplot[0].set_title("Time Domain Signal (64 point sine)")
    subplot[1].set_title("Frequency Spectrum - Numpy")
    subplot[2].set_title("Frequency Spectrum - Chips")
    subplot[0].set_xlabel("Sample")
    subplot[1].set_xlabel("Sample")
    subplot[2].set_xlabel("Sample")
    pyplot.savefig("../docs/source/examples/images/example_5.png")
    pyplot.show()
开发者ID:freecores,项目名称:tcp_socket,代码行数:29,代码来源:example_6.py


示例19: compute_spectrum

def compute_spectrum(signal, rate):
    n = len(signal)
    k = np.arange(n)
    T = n/rate
    freq = k/T
    Y = sp.fft(signal)/n
    return freq, Y
开发者ID:bizatheo,项目名称:training-material,代码行数:7,代码来源:analyse.py


示例20: returnSpectrum

def returnSpectrum(y,Fs):
    """
    Plots a Single-Sided Amplitude Spectrum of y(t)
    y = wavefile in array form
    Fs = sample frequency, sometimes called sampling rate; likely 44100
    """

    n = len(y) # length of the signal
    k = arange(n) # array from [0, 1, 2, ... n-1]
    T = n/float(Fs) # need to make Fs a float so T can be 0.xx decimal

    if y.ndim > 1: # stereo music has more than one dimension for stereo sound
        y = y[:,0] # taking 1st dimension, slice of matrix

    frq = k/T # two sides frequency range
    # take array, divide by num secs
    frq = frq[range(n/2)] # one side frequency range

    Y = fft(y)/n # fft computing and normalization
    Y = Y[range(n/2)]

    zipped =  zip(frq, abs(Y)) # takes 2 arrays of same size & combines

    frequencies = dict(zipped)
    return frequencies
开发者ID:brittinator,项目名称:OhMyBeats---Ada-Capstone,代码行数:25,代码来源:musicFourierTransform.py



注:本文中的scipy.fft函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python scipy.finfo函数代码示例发布时间:2022-05-27
下一篇:
Python scipy.factorial函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap