【发布时间】:2019-06-19 12:33:28
【问题描述】:
我需要过滤一个信号。我想将频率保持在 0 到 51Hz 之间。以下是我正在使用的代码,部分摘自这两个问题(Python: Designing a time-series filter after Fourier analysis,Creating lowpass filter in SciPy - understanding methods and units):
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# y is the original signal
# getting the unbiased signal
y = list(np.array(y)-sts.mean(y))
# saving the original signal
y_before = y
# x is the time vector
# for the spectrum of the original signal
yps_before = np.abs(np.fft.fft(y_before))**2
yfreqs_before = np.fft.fftfreq(6000, d = 0.001)
y_idx_before = np.argsort(yfreqs_before)
#Filtering
order = 8
fs = 1000.0
cutoff = 50.0
y = butter_lowpass_filter(y, cutoff, fs, order)
# for the spectrum of the filtered signal
yps = np.abs(np.fft.fft(y))**2
yfreqs = np.fft.fftfreq(6000, d = 0.001)
y_idx = np.argsort(yfreqs)
fig = plt.figure(figsize=(14,10))
fig.suptitle(file_name, fontsize=20)
plt.plot(yfreqs_before[y_idx_before], yps_before[y_idx_before], 'k-', label='original spectrum',linewidth=0.5)
plt.plot(yfreqs[y_idx], yps[y_idx], 'r-', linewidth=2, label='filtered spectrum')
plt.xlabel('Frequency [Hz]')
plt.yscale('log')
plt.grid()
plt.legend()
plt.show()
正如您所见,频谱在 100Hz 之后看起来不错,但是,在 50Hz 和大约 100Hz 之间仍然存在分量。因此,我尝试使用更高阶 (20) 的滤波器,但作为输出,我得到了一个非常奇怪的频谱:
所以,我知道过滤器不能也永远不会是完美的,但对我来说,这似乎有点过分了。根据我的经验,我总是能够在我的截止频率处获得非常好的滤波信号。有什么建议吗?
【问题讨论】:
标签: python filtering signal-processing