python
复制代码
def design_fir_filter(Fs, pass_freq, stop_freq, pass_attenuation, stop_attenuation, density_factor, filter_type):
nyquist_freq = Fs * 0.5
# filter_order2 = int(density_factor * nyquist_freq / (np.min(np.diff(stop_freq))))
if (filter_type == 'low_pass'):
if isinstance(pass_freq, list) or isinstance(stop_freq, list):
print('pass_freq or stop_freq length not 1 !')
return False
filter_order = density_factor
# filter_order = int(density_factor * nyquist_freq / (pass_freq - stop_freq))
filter_coeff = signal.remez(filter_order + 1, [0, pass_freq, pass_freq + stop_freq, nyquist_freq],
[1, 0], [pass_attenuation, stop_attenuation], fs=Fs)
elif (filter_type == 'high_pass'):
if isinstance(pass_freq, list) or isinstance(stop_freq, list):
print('pass_freq or stop_freq length not 1 !')
return False
filter_order = density_factor
filter_coeff = signal.remez(filter_order + 1, [0, pass_freq - stop_freq, pass_freq , nyquist_freq],
[0, 1], [stop_attenuation, pass_attenuation], fs=Fs)
else:
filter_order = density_factor
filter_coeff = signal.remez(filter_order + 1, [0, pass_freq[0]- stop_freq[0], pass_freq[0], pass_freq[1], pass_freq[1] + stop_freq[1], nyquist_freq],
[0, 1, 0], [stop_attenuation, pass_attenuation, stop_attenuation], fs=Fs)
plot_response(filter_coeff, Fs, filter_type)
return filter_coeff
def apply_fir_filter(filter_coeff, input_signal, num=None):
if num is None:
num = input_signal.shape[0]
filtered_signals = np.zeros_like(input_signal[:num, :])
for i in range(num):
filtered_signals[i, :] = signal.lfilter(filter_coeff, 1, input_signal[i, :])
return filtered_signals
python
复制代码
def design_iir_butterworth_filter(pass_freq, stop_freq, gpass, gstop, fs_in=None, design_type='sos', filter_type='butterworth'):
if design_type is 'sos':
sos = signal.iirdesign(pass_freq, stop_freq, gpass, gstop, analog=False, ftype='butter', output='sos', fs=None)
filter_coeff = sos
else:
b, a = signal.iirdesign(pass_freq, stop_freq, gpass, gstop, analog=False, ftype='butter', output='ba', fs=None)
filter_coeff = [b, a]
plot_response(filter_coeff, fs_in, filter_type)
return filter_coeff
def apply_iir_filter(filter_coeff, input_signal, design_type='sos', num=None):
if num is None:
num = input_signal.shape[0]
filtered_signals = np.zeros_like(input_signal[:num, :])
if design_type is 'sos':
for i in range(num):
filtered_signals[i, :] = signal.sosfilt(filter_coeff, input_signal[i, :])
else:
for i in range(num):
filtered_signals[i, :] = signal.lfilter(filter_coeff[0], filter_coeff[1], input_signal[i, :])
return filtered_signals