Jan 29, 2023

파이썬으로 구현한 1차 저역필터 (Low pass filter in Python)


# First order LPF
import numpy as np
import matplotlib.pyplot as plt

def first_order_low_pass_filer(data, alpha):
    filtered_data = np.zeros_like(data)
    filtered_data[0] = data[0]
    for i in range(1, len(data)):
        filtered_data[i] = alpha * data[i] + (1 - alpha) * filtered_data[i-1]
    return filtered_data

low_alpha = 0.4  # filter weight
high_alpha = 0.8 # filter weight

# np.linspace(start, stop, num, ...)
time = np.linspace(0, 5, 200)

data = np.sin(2 * np.pi * 50 * time) + np.sin(2 * np.pi * 250 * time) * 2  

low_alpha_data = first_order_low_pass_filer(data, low_alpha)
high_alpha_data = first_order_low_pass_filer(data, high_alpha)

plt.figure(figsize=(25, 7))
plt.plot(time, data, label='real Data', color = 'lawngreen')
plt.plot(time, low_alpha_data, label = 'low 1-st LPF', color = 'black', linestyle = '--')
plt.plot(time, high_alpha_data, label = 'high 1-st LPF', color = 'red', linestyle = '-.')

plt.xlabel('time (sec.)')
plt.ylabel('amplitude')
plt.title('First Order Low Pass Filter')
plt.legend()
plt.show()

Output



No comments:

Post a Comment