Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Created May 18, 2021 07:01
Show Gist options
  • Save JustinSDK/c65f454bd66d232edecea7bf17c81fce to your computer and use it in GitHub Desktop.
Save JustinSDK/c65f454bd66d232edecea7bf17c81fce to your computer and use it in GitHub Desktop.
簡單的濾波
import numpy as np
import matplotlib.pyplot as plt
t = 2 # 取樣時間
sample_rate = 800 # 取樣率,每秒取幾個樣本
def signal(t, sample_rate):
f = 10
x = np.linspace(0, t, int(t * sample_rate), endpoint = False)
return (np.sin(f * 2 * np.pi * x) +
np.sin(3 * f * 2 * np.pi * x) / 2 +
np.sin(4 * f * 2 * np.pi * x) / 5 +
np.sin(8 * f * 2 * np.pi * x) / 3)
samples = signal(t, sample_rate)
sp = np.fft.fft(samples)
freq = np.fft.fftfreq(samples.size, d = 1 / sample_rate)
sp2 = sp.copy()
# 頻率 10 與 -10 以外的部份設為 0
sp2[np.intersect1d(np.where(freq != 10), np.where(freq != -10))] = 0
# 逆轉換
samples2 = np.fft.ifft(sp2).real
x = np.linspace(0, t, int(t * sample_rate), endpoint = False)
plt.plot(x, samples)
plt.plot(x, samples2)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment