具有时变截止频率的低通滤波器,使用 Python

2023-11-24

如何应用低通滤波器,其截止频率线性变化(或具有比线性更一般的曲线),例如10000hz 至 200hz 随时间变化,使用 numpy/scipy 并且可能没有其他库?

Example:

  • 在 00:00,000,低通截止 = 10000 Hz
  • 在 00:05,000,低通截止 = 5000hz
  • 在 00:09,000,低通截止 = 1000hz
  • 然后截止频率在 1000hz 停留 10 秒,然后截止频率降低至 200hz

以下是如何进行简单的 100hz 低通:

from scipy.io import wavfile
import numpy as np
from scipy.signal import butter, lfilter

sr, x = wavfile.read('test.wav')
b, a = butter(2, 100.0 / sr, btype='low')  # Butterworth
y = lfilter(b, a, x)
wavfile.write('out.wav', sr, np.asarray(y, dtype=np.int16))

但如何使截止值变化呢?

注:我已经读过在Python中应用时变过滤器但答案相当复杂(通常适用于多种过滤器)。


一种相对简单的方法是保持滤波器固定并调制信号时间。例如,如果信号时间运行快 10 倍,则 10KHz 低通将像标准时间内的 1KHz 低通一样工作。

为此,我们需要求解一个简单的 ODE

dy       1
--  =  ----
dt     f(y)

Here t是调制时间y实时和f所需的截止时间y.

原型实现:

from __future__ import division
import numpy as np
from scipy import integrate, interpolate
from scipy.signal import butter, lfilter, spectrogram

slack_l, slack = 0.1, 1
cutoff = 50
L = 25

from scipy.io import wavfile
sr, x = wavfile.read('capriccio.wav')
x = x[:(L + slack) * sr, 0]
x = x

# sr = 44100
# x = np.random.normal(size=((L + slack) * sr,))

b, a = butter(2, 2 * cutoff / sr, btype='low')  # Butterworth

# cutoff function
def f(t):
    return (10000 - 1000 * np.clip(t, 0, 9) - 1000 * np.clip(t-19, 0, 0.8)) \
        / cutoff

# and its reciprocal
def fr(_, t):
    return cutoff / (10000 - 1000 * t.clip(0, 9) - 1000 * (t-19).clip(0, 0.8))

# modulate time
# calculate upper end of td first
tdmax = integrate.quad(f, 0, L + slack_l, points=[9, 19, 19.8])[0]
span = (0, tdmax)
t = np.arange(x.size) / sr
tdinfo = integrate.solve_ivp(fr, span, np.zeros((1,)),
                             t_eval=np.arange(0, span[-1], 1 / sr),
                             vectorized=True)
td = tdinfo.y.ravel()
# modulate signal
xd = interpolate.interp1d(t, x)(td)
# and linearly filter
yd = lfilter(b, a, xd)
# modulate signal back to linear time
y = interpolate.interp1d(td, yd)(t[:-sr*slack])

# check
import pylab
xa, ya, z = spectrogram(y, sr)
pylab.pcolor(ya, xa, z, vmax=2**8, cmap='nipy_spectral')
pylab.savefig('tst.png')

wavfile.write('capriccio_vandalized.wav', sr, y.astype(np.int16))

示例输出:

Spectrogram of first 25 seconds of BWV 826 Capriccio filtered with a time varying lowpass implemented via time bending.

BWV 826 Capriccio 前 25 秒的频谱图通过时间弯曲实现时变低通滤波。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有时变截止频率的低通滤波器,使用 Python 的相关文章

随机推荐