Filtfilt

日期2011-11-22(最后修改),2006-11-01(创建)

此示例代码演示了如何使用 scipy.signal.filtfilt 函数,该函数是一个线性滤波器,通过对信号进行两次 IIR 滤波(一次向前,一次向后)来实现零相位延迟。滤波器的阶数是原始滤波器阶数的两倍。该函数还计算初始滤波器参数,以提供更稳定的响应(通过 lfilter_zi)。

为了比较,此脚本还使用 scipy.signal.lfilter 对信号应用相同的 IIR 滤波器;对于这些计算,lfilter_zi 用于为滤波器选择合适的初始条件。如果没有它,这些图在 0 附近会有很长的瞬态。就目前而言,它们在信号的初始值附近有很长的瞬态。

代码

In [1]
from numpy import sin, cos, pi, linspace
from numpy.random import randn
from scipy.signal import lfilter, lfilter_zi, filtfilt, butter

from matplotlib.pyplot import plot, legend, show, hold, grid, figure, savefig


# Generate a noisy signal to be filtered.
t = linspace(-1, 1, 201)
x = (sin(2 * pi * 0.75 * t*(1-t) + 2.1) + 0.1*sin(2 * pi * 1.25 * t + 1) +
    0.18*cos(2 * pi * 3.85 * t))
xn = x + randn(len(t)) * 0.08

# Create an order 3 lowpass butterworth filter.
b, a = butter(3, 0.05)

# Apply the filter to xn.  Use lfilter_zi to choose the initial condition
# of the filter.
zi = lfilter_zi(b, a)
z, _ = lfilter(b, a, xn, zi=zi*xn[0])

# Apply the filter again, to have a result filtered at an order
# the same as filtfilt.
z2, _ = lfilter(b, a, z, zi=zi*z[0])

# Use filtfilt to apply the filter.
y = filtfilt(b, a, xn)


# Make the plot.
figure(figsize=(10,5))
hold(True)
plot(t, xn, 'b', linewidth=1.75, alpha=0.75)
plot(t, z, 'r--', linewidth=1.75)
plot(t, z2, 'r', linewidth=1.75)
plot(t, y, 'k', linewidth=1.75)
legend(('noisy signal',
        'lfilter, once',
        'lfilter, twice',
        'filtfilt'),
        loc='best')
hold(False)
grid(True)
show()
#savefig('plot.png', dpi=65)

章节作者:Unknown[1],Unknown[48],Unknown[49],Unknown[50],Unknown[51],WarrenWeckesser