窓関数の効果 | python3Xのブログ

python3Xのブログ

ここでは40代、50代の方が日々の生活で役に立つ情報や私の趣味であるプログラム、Excelや科学に関する内容で投稿する予定です。

その比較

サンプリング周波数 fs:2000

サンプリングの長さ:256

合成される波の周波数

①440Hz ②600Hz(振幅x2倍)  ③800Hz(振幅x3倍)

下図はフーリエ変換後得られた結果

440Hz、600Hz、800Hzの3つのスペクトルの周波数と振幅の大きさの違いが

はっきり分かります

#coding UTF-8
from matplotlib import pyplot as plt
import numpy as np
fs = 2000 # Sampling rate
L = 256   # Sampling length
# 440Hzのsin波を作る
sin440 = np.sin(2. * np.pi * np.arange(L) * 440. / fs)
# 600Hzのsin波を作る
sin600= 2 * np.sin(2. * np.pi * np.arange(L) * 600. / fs)
# 800Hzのsin波を作る
sin800 = 3 * np.sin(2. * np.pi * np.arange(L) * 800. / fs)
# 3つを足し合わせる
sinall = sin440 + sin600 + sin800
# 窓関数
hammingWindow = np.hamming(L)
hanningWindow = np.hanning(L)
bartlettWindow = np.bartlett(L)
blackmanWindow = np.blackman(L)
# フーリエ変換
spect_nW = np.fft.fft(sinall) # 窓関数なし
hammingWin = np.fft.fft(sinall * hammingWindow)
hanningWin = np.fft.fft(sinall * hanningWindow)
bartlettWin = np.fft.fft(sinall * bartlettWindow)
blackmanWin = np.fft.fft(sinall * blackmanWindow)
spect_nw = abs(spect_nW)
hamming = abs(hammingWin)
hanning = abs(hanningWin)
bartlett = abs(bartlettWin)
blackman = abs(blackmanWin)
# フーリエ逆変換
inv_hamming = np.fft.ifft(hammingWin)
inv_hamming /= hammingWindow
inv_hanning = np.fft.ifft(hanningWin)
inv_hanning /= hanningWindow
inv_bartlett = np.fft.ifft(bartlettWin)
inv_bartlett /= bartlettWindow
inv_blackman = np.fft.ifft(blackmanWin)
inv_blackman /= blackmanWindow
# 図を表示
freq = np.linspace(0, fs, L)
fig = plt.figure(figsize=(20, 70))
plt.rcParams["font.size"] = 20
fig.add_subplot(511)
plt.plot(sinall)
plt.xlim([0, L])
plt.xlabel("時間")
plt.ylabel("信号")
plt.grid(True)
plt.legend()
plt.title("1. 入力信号")
fig.add_subplot(512)
plt.plot(freq, spect_nw, label="窓関数なし")
plt.plot(freq, hamming, label="ハミング窓")
plt.xlabel("周波数")
plt.ylabel("振幅")
plt.grid(True)
plt.legend()
plt.title("2. 比較:ハミング窓")
fig.add_subplot(513)
plt.plot(freq, spect_nw, label="窓関数なし")
plt.plot(freq, hanning, label="ハン窓")
plt.xlabel("周波数")
plt.ylabel("振幅")
plt.grid(True)
plt.legend()
plt.title("3. 比較:ハン窓")
fig.add_subplot(514)
plt.plot(freq, spect_nw, label="窓関数なし")
plt.plot(freq, bartlett, label="バートレット窓")
plt.xlabel("周波数")
plt.ylabel("振幅")
plt.grid(True)
plt.legend()
plt.title("4. 比較:バートレット窓")
fig.add_subplot(515)
plt.plot(freq, spect_nw, label="窓関数なし")
plt.plot(freq, blackman, label="ブラックマン窓")
plt.xlabel("周波数")
plt.ylabel("振幅")
plt.grid(True)
plt.legend()
plt.title("5. 比較:ブラックマン窓")
plt.subplots_adjust(hspace=0.5) # グラフ間の隙間調整
plt.show()