<jupyter_start><jupyter_text>STFT→iSTFTでちゃんと音がもとに戻るのか確認してみた話<jupyter_code>import wave
import scipy as sp
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>ファイル名の定義<jupyter_code>read_path = "datas/test.wav"
write_path = "datas/re_test.wav"<jupyter_output><empty_output><jupyter_text>ファイルの読み込みとSTFT<jupyter_code>wave_file = wave.open(read_path, "r")

amp = 2 * np.sqrt(2)
length = 50000
fs = wave_file.getframerate()
time = np.arange(length) / float(fs)
x = wave_file.readframes(wave_file.getnframes())
wav_x = np.frombuffer(x, dtype= "int16")

f, t, Zxx = signal.stft(wav_x[:length], fs, nperseg=1024)<jupyter_output><empty_output><jupyter_text>STFT結果の可視化<jupyter_code>plt.pcolormesh(t, f, np.log(np.abs(Zxx)), vmin=0, vmax=amp)
plt.title('STFT Magnitude')
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.show()<jupyter_output><empty_output><jupyter_text>iSTFTを実行する<jupyter_code>Zxx = np.where(np.abs(Zxx) >= amp/10, Zxx, 0)
_, wav_xrec = signal.istft(Zxx, fs)
wav_xrec = np.array(wav_xrec, dtype=np.int16) # 戻しておかないとすごい音がする<jupyter_output><empty_output><jupyter_text>iSTFT結果の可視化と元シグナルの比較<jupyter_code>plt.subplot(211)
plt.plot(time, wav_x[:length])
plt.xlabel('Time [sec]')
plt.ylabel('Signal')
plt.legend(['Raw'])

plt.subplot(212)
plt.plot(time, wav_xrec[:length])
plt.xlabel('Time [sec]')
plt.ylabel('Signal')
plt.legend(['iSTFT'])

plt.show()<jupyter_output><empty_output><jupyter_text>Waveファイルとして書き出し<jupyter_code>write_wave = wave.Wave_write(write_path)
write_wave.setparams(wave_file.getparams())
write_wave.setnframes(length)
write_wave.writeframes(wav_x[:length])
write_wave.close()
wave_file.close()<jupyter_output><empty_output><jupyter_text>平均二乗誤差<jupyter_code>np.mean((wav_xrec[:length] - wav_x[:length]) ** 2)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15938864628820962, 'fraction_numerical': 0.014192139737991267, 'mean_word_length': 10.385093167701863, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 34, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '592408', 'license': 'MIT', 'n_tokens_mistral': 905, 'n_tokens_neox': 866, 'n_words': 89, 'path': '20171026_STFT/STFT.ipynb', 'repo_name': 'EnsekiTT/blog', 'size': '1832'}