当前位置: 首页>>代码示例>>Python>>正文


Python numpy.hanning方法代码示例

本文整理汇总了Python中numpy.hanning方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.hanning方法的具体用法?Python numpy.hanning怎么用?Python numpy.hanning使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


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

示例1: periodic_hann

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def periodic_hann(window_length):
  """Calculate a "periodic" Hann window.

  The classic Hann window is defined as a raised cosine that starts and
  ends on zero, and where every value appears twice, except the middle
  point for an odd-length window.  Matlab calls this a "symmetric" window
  and np.hanning() returns it.  However, for Fourier analysis, this
  actually represents just over one cycle of a period N-1 cosine, and
  thus is not compactly expressed on a length-N Fourier basis.  Instead,
  it's better to use a raised cosine that ends just before the final
  zero value - i.e. a complete cycle of a period-N cosine.  Matlab
  calls this a "periodic" window. This routine calculates it.

  Args:
    window_length: The number of points in the returned window.

  Returns:
    A 1D np.array containing the periodic hann window.
  """
  return 0.5 - (0.5 * np.cos(2 * np.pi / window_length *
                             np.arange(window_length))) 
开发者ID:jordipons,项目名称:sklearn-audio-transfer-learning,代码行数:23,代码来源:mel_features.py

示例2: test_dft_2d

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def test_dft_2d(self):
        """Test the discrete Fourier transform on 2D data"""
        N = 16
        da = xr.DataArray(np.random.rand(N,N), dims=['x','y'],
                        coords={'x':range(N),'y':range(N)}
                         )
        ft = xrft.dft(da, shift=False)
        npt.assert_almost_equal(ft.values, np.fft.fftn(da.values))

        ft = xrft.dft(da, shift=False, window=True, detrend='constant')
        dim = da.dims
        window = np.hanning(N) * np.hanning(N)[:, np.newaxis]
        da_prime = (da - da.mean(dim=dim)).values
        npt.assert_almost_equal(ft.values, np.fft.fftn(da_prime*window))

        da = xr.DataArray(np.random.rand(N,N), dims=['x','y'],
                         coords={'x':range(N,0,-1),'y':range(N,0,-1)}
                         )
        assert (xrft.power_spectrum(da, shift=False,
                                   density=True) >= 0.).all() 
开发者ID:xgcm,项目名称:xrft,代码行数:22,代码来源:test_xrft.py

示例3: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def __init__(self, parallel, wave_len=254, wave_dif=64, buffer_size=5, loop_num=5, window=np.hanning(254)):
        self.wave_len = wave_len
        self.wave_dif = wave_dif
        self.buffer_size = buffer_size
        self.loop_num = loop_num
        self.parallel = parallel
        self.window = cp.array([window for _ in range(parallel)])

        self.wave_buf = cp.zeros((parallel, wave_len+wave_dif), dtype=float)
        self.overwrap_buf = cp.zeros((parallel, wave_dif*buffer_size+(wave_len-wave_dif)), dtype=float)
        self.spectrum_buffer = cp.ones((parallel, self.buffer_size, self.wave_len), dtype=complex)
        self.absolute_buffer = cp.ones((parallel, self.buffer_size, self.wave_len), dtype=complex)
        
        self.phase = cp.zeros((parallel, self.wave_len), dtype=complex)
        self.phase += cp.random.random((parallel, self.wave_len))-0.5 + cp.random.random((parallel, self.wave_len))*1j - 0.5j
        self.phase[self.phase == 0] = 1
        self.phase /= cp.abs(self.phase) 
开发者ID:pstuvwx,项目名称:Deep_VoiceChanger,代码行数:19,代码来源:gla_gpu.py

示例4: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def __init__(self, wave_len=254, wave_dif=64, buffer_size=5, loop_num=5, window=np.hanning(254)):
        self.wave_len = wave_len
        self.wave_dif = wave_dif
        self.buffer_size = buffer_size
        self.loop_num = loop_num
        self.window = window

        self.wave_buf = np.zeros(wave_len+wave_dif, dtype=float)
        self.overwrap_buf = np.zeros(wave_dif*buffer_size+(wave_len-wave_dif), dtype=float)
        self.spectrum_buffer = np.ones((self.buffer_size, self.wave_len), dtype=complex)
        self.absolute_buffer = np.ones((self.buffer_size, self.wave_len), dtype=complex)
        
        self.phase = np.zeros(self.wave_len, dtype=complex)
        self.phase += np.random.random(self.wave_len)-0.5 + np.random.random(self.wave_len)*1j - 0.5j
        self.phase[self.phase == 0] = 1
        self.phase /= np.abs(self.phase) 
开发者ID:pstuvwx,项目名称:Deep_VoiceChanger,代码行数:18,代码来源:gla_util.py

示例5: stft_magnitude

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def stft_magnitude(signal, fft_length,
                   hop_length=None,
                   window_length=None):
  """Calculate the short-time Fourier transform magnitude.

  Args:
    signal: 1D np.array of the input time-domain signal.
    fft_length: Size of the FFT to apply.
    hop_length: Advance (in samples) between each frame passed to FFT.
    window_length: Length of each block of samples to pass to FFT.

  Returns:
    2D np.array where each row contains the magnitudes of the fft_length/2+1
    unique values of the FFT for the corresponding frame of input samples.
  """
  frames = frame(signal, window_length, hop_length)
  # Apply frame window to each frame. We use a periodic Hann (cosine of period
  # window_length) instead of the symmetric Hann of np.hanning (period
  # window_length-1).
  window = periodic_hann(window_length)
  windowed_frames = frames * window
  return np.abs(np.fft.rfft(windowed_frames, int(fft_length)))


# Mel spectrum constants and functions. 
开发者ID:jordipons,项目名称:sklearn-audio-transfer-learning,代码行数:27,代码来源:mel_features.py

示例6: stft

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def stft(data, fft_size=512, step_size=160,padding=True):
    # short time fourier transform
    if padding == True:
        # for 16K sample rate data, 48192-192 = 48000
        pad = np.zeros(192,)
        data = np.concatenate((data,pad),axis=0)
    # padding hanning window 512-400 = 112
    window = np.concatenate((np.zeros((56,)),np.hanning(fft_size-112),np.zeros((56,))),axis=0)
    win_num = (len(data) - fft_size) // step_size
    out = np.ndarray((win_num, fft_size), dtype=data.dtype)
    for i in range(win_num):
        left = int(i * step_size)
        right = int(left + fft_size)
        out[i] = data[left: right] * window
    F = np.fft.rfft(out, axis=1)
    return F 
开发者ID:bill9800,项目名称:speech_separation,代码行数:18,代码来源:utils.py

示例7: istft

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def istft(F, fft_size=512, step_size=160,padding=True):
    # inverse short time fourier transform
    data = np.fft.irfft(F, axis=-1)
    # padding hanning window 512-400 = 112
    window = np.concatenate((np.zeros((56,)),np.hanning(fft_size-112),np.zeros((56,))),axis=0)
    number_windows = F.shape[0]
    T = np.zeros((number_windows * step_size + fft_size))
    for i in range(number_windows):
        head = int(i * step_size)
        tail = int(head + fft_size)
        T[head:tail] = T[head:tail] + data[i, :] * window
    if padding == True:
        T = T[:48000]
    return T

# combine FFT bins to mel frequency bins 
开发者ID:bill9800,项目名称:speech_separation,代码行数:18,代码来源:utils.py

示例8: periodic_hann

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def periodic_hann(window_length):
    """Calculate a "periodic" Hann window.

    The classic Hann window is defined as a raised cosine that starts and
    ends on zero, and where every value appears twice, except the middle
    point for an odd-length window.  Matlab calls this a "symmetric" window
    and np.hanning() returns it.  However, for Fourier analysis, this
    actually represents just over one cycle of a period N-1 cosine, and
    thus is not compactly expressed on a length-N Fourier basis.  Instead,
    it's better to use a raised cosine that ends just before the final
    zero value - i.e. a complete cycle of a period-N cosine.  Matlab
    calls this a "periodic" window. This routine calculates it.

    Args:
      window_length: The number of points in the returned window.

    Returns:
      A 1D np.array containing the periodic hann window.
    """
    return 0.5 - (0.5 * np.cos(2 * np.pi / window_length *
                               np.arange(window_length))) 
开发者ID:devicehive,项目名称:devicehive-audio-analysis,代码行数:23,代码来源:mel_features.py

示例9: stft_magnitude

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def stft_magnitude(signal, fft_length,
                   hop_length=None,
                   window_length=None):
    """Calculate the short-time Fourier transform magnitude.

    Args:
      signal: 1D np.array of the input time-domain signal.
      fft_length: Size of the FFT to apply.
      hop_length: Advance (in samples) between each frame passed to FFT.
      window_length: Length of each block of samples to pass to FFT.

    Returns:
      2D np.array where each row contains the magnitudes of the fft_length/2+1
      unique values of the FFT for the corresponding frame of input samples.
    """
    frames = frame(signal, window_length, hop_length)
    # Apply frame window to each frame. We use a periodic Hann (cosine of period
    # window_length) instead of the symmetric Hann of np.hanning (period
    # window_length-1).
    window = periodic_hann(window_length)
    windowed_frames = frames * window
    return np.abs(np.fft.rfft(windowed_frames, int(fft_length)))


# Mel spectrum constants and functions. 
开发者ID:devicehive,项目名称:devicehive-audio-analysis,代码行数:27,代码来源:mel_features.py

示例10: test_high_frequency_completion

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def test_high_frequency_completion(self):
        path = dirpath + '/data/test16000.wav'
        fs, x = wavfile.read(path)

        f0rate = 0.5
        shifter = Shifter(fs, f0rate=f0rate)
        mod_x = shifter.f0transform(x, completion=False)
        mod_xc = shifter.f0transform(x, completion=True)
        assert len(mod_x) == len(mod_xc)

        N = 512
        fl = int(fs * 25 / 1000)
        win = np.hanning(fl)
        sts = [1000, 5000, 10000, 20000]
        for st in sts:
            # confirm w/o completion
            f_mod_x = fft(mod_x[st: st + fl] / 2**16 * win)
            amp_mod_x = 20.0 * np.log10(np.abs(f_mod_x))

            # confirm w/ completion
            f_mod_xc = fft(mod_xc[st: st + fl] / 2**16 * win)
            amp_mod_xc = 20.0 * np.log10(np.abs(f_mod_xc))

            assert np.mean(amp_mod_x[N // 4:] < np.mean(amp_mod_xc[N // 4:])) 
开发者ID:k2kobayashi,项目名称:sprocket,代码行数:26,代码来源:test_shifter.py

示例11: test_nonstationary_convmtx

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def test_nonstationary_convmtx(par):
    """Compare nonstationary_convmtx with convmtx for stationary filter
    """
    x = np.random.normal(0, 1, par['nt']) + \
        par['imag'] * np.random.normal(0, 1, par['nt'])

    nh = 7
    h = np.hanning(7)
    H = convmtx(h, par['nt'])
    H = H[:, nh//2:-nh//2+1]

    H1 = \
        nonstationary_convmtx(np.repeat(h[:, np.newaxis], par['nt'], axis=1).T,
                              par['nt'], hc=nh//2, pad=(par['nt'], par['nt']))
    y = np.dot(H, x)
    y1 = np.dot(H1, x)
    assert_array_almost_equal(y, y1, decimal=4) 
开发者ID:equinor,项目名称:pylops,代码行数:19,代码来源:test_signalutils.py

示例12: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def __init__(self, model, PENALTY_K=0.16, WINDOW_INFLUENCE=0.40, LR=0.30, EXEMPLAR_SIZE=127,
                 INSTANCE_SIZ=287, BASE_SIZE=0, CONTEXT_AMOUNT=0.5,
                 STRIDE=8, RATIOS=(0.33, 0.5, 1, 2, 3), SCALES=(8,)):
        super(SiamRPNTracker, self).__init__()
        self.PENALTY_K = PENALTY_K
        self.WINDOW_INFLUENCE = WINDOW_INFLUENCE
        self.LR = LR
        self.EXEMPLAR_SIZE = EXEMPLAR_SIZE
        self.INSTANCE_SIZE = INSTANCE_SIZ
        self.BASE_SIZE = BASE_SIZE
        self.CONTEXT_AMOUNT = CONTEXT_AMOUNT
        self.STRIDE = STRIDE
        self.RATIOS = list(RATIOS)
        self.SCALES = list(SCALES)
        self.score_size = (self.INSTANCE_SIZE - self.EXEMPLAR_SIZE) // \
            self.STRIDE + 1 + self.BASE_SIZE
        self.anchor_num = len(self.RATIOS) * len(self.SCALES)
        hanning = np.hanning(self.score_size)
        window = np.outer(hanning, hanning)
        self.window = np.tile(window.flatten(), self.anchor_num)
        self.anchors = self.generate_anchor(self.score_size)
        self.model = model
        self.channel_average = None
        self.size = None
        self.center_pos = None 
开发者ID:dmlc,项目名称:gluon-cv,代码行数:27,代码来源:siamrpn_tracker.py

示例13: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin, fmax):
        '''Log mel feature extractor. 
        
        Args:
          sample_rate: int
          window_size: int
          hop_size: int
          mel_bins: int
          fmin: int, minimum frequency of mel filter banks
          fmax: int, maximum frequency of mel filter banks
        '''
        
        self.window_size = window_size
        self.hop_size = hop_size
        self.window_func = np.hanning(window_size)
        
        self.melW = librosa.filters.mel(
            sr=sample_rate, 
            n_fft=window_size, 
            n_mels=mel_bins, 
            fmin=fmin, 
            fmax=fmax).T
        '''(n_fft // 2 + 1, mel_bins)''' 
开发者ID:qiuqiangkong,项目名称:dcase2019_task2,代码行数:25,代码来源:features.py

示例14: _get_interp_fourier

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def _get_interp_fourier(self, sz):
        """
            compute the fourier series of the interpolation function.
        """
        f1 = np.arange(-(sz[0]-1) / 2, (sz[0]-1)/2+1, dtype=np.float32)[:, np.newaxis] / sz[0]
        interp1_fs = np.real(cubic_spline_fourier(f1, config.interp_bicubic_a) / sz[0])
        f2 = np.arange(-(sz[1]-1) / 2, (sz[1]-1)/2+1, dtype=np.float32)[np.newaxis, :] / sz[1]
        interp2_fs = np.real(cubic_spline_fourier(f2, config.interp_bicubic_a) / sz[1])
        if config.interp_centering:
            f1 = np.arange(-(sz[0]-1) / 2, (sz[0]-1)/2+1, dtype=np.float32)[:, np.newaxis]
            interp1_fs = interp1_fs * np.exp(-1j*np.pi / sz[0] * f1)
            f2 = np.arange(-(sz[1]-1) / 2, (sz[1]-1)/2+1, dtype=np.float32)[np.newaxis, :]
            interp2_fs = interp2_fs * np.exp(-1j*np.pi / sz[1] * f2)

        if config.interp_windowing:
            win1 = np.hanning(sz[0]+2)[:, np.newaxis]
            win2 = np.hanning(sz[1]+2)[np.newaxis, :]
            interp1_fs = interp1_fs * win1[1:-1]
            interp2_fs = interp2_fs * win2[1:-1]
        if not config.use_gpu:
            return (interp1_fs[:, :, np.newaxis, np.newaxis],
                    interp2_fs[:, :, np.newaxis, np.newaxis])
        else:
            return (cp.asarray(interp1_fs[:, :, np.newaxis, np.newaxis]),
                    cp.asarray(interp2_fs[:, :, np.newaxis, np.newaxis])) 
开发者ID:StrangerZhang,项目名称:pyECO,代码行数:27,代码来源:tracker.py

示例15: stft

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import hanning [as 别名]
def stft(sig, frame_size, overlap_fac=0.5, window=np.hanning):
    """ short time fourier transform of audio signal """
    win = window(frame_size)
    hop_size = int(frame_size - np.floor(overlap_fac * frame_size))

    # zeros at beginning (thus center of 1st window should be for sample nr. 0)
    samples = np.append(np.zeros(np.floor(frame_size / 2.0)), sig)
    # cols for windowing
    cols = np.ceil((len(samples) - frame_size) / float(hop_size)) + 1
    # zeros at end (thus samples can be fully covered by frames)
    samples = np.append(samples, np.zeros(frame_size))

    frames = stride_tricks.as_strided(
        samples,
        shape=(cols, frame_size),
        strides=(
            samples.strides[0] * hop_size,
            samples.strides[0]
        )
    ).copy()

    frames *= win

    return np.fft.rfft(frames) 
开发者ID:psobot,项目名称:SampleScanner,代码行数:26,代码来源:spectrogram.py


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