Amazing-Python-Scripts

Форк
0
55 строк · 2.4 Кб
1
# Spectral Subtraction: Method used for noise reduction
2
import scipy.io.wavfile as wav
3
import numpy as np
4
import matplotlib.pyplot as plt
5

6
file = input("Enter the file path: ")
7
sr, data = wav.read(file)
8
fl = 400  # frame_length
9
frames = []  # empty list
10
for i in range(0, int(len(data)/(int(fl/2))-1)):
11
    arr = data[int(i*int(fl/2)):int(i*int(fl/2)+fl)]
12
    frames.append(arr)  # appending each array data into the frames list
13
frames = np.array(frames)  # converting the frames list into an array
14
ham_window = np.hamming(fl)  # using np.hamming
15
windowed_frames = frames*ham_window  # multiplying frames array with ham_window
16
dft = []  # empty list containing fft of windowed_frames
17
for i in windowed_frames:
18
    # now taking the first fourier transform of each window
19
    dft.append(np.fft.fft(i))
20
dft = np.array(dft)  # converting dft into array
21

22
dft_mag_spec = np.abs(dft)  # converting dft into absolute values
23
dft_phase_spec = np.angle(dft)  # finding dft angle
24
noise_estimate = np.mean(dft_mag_spec, axis=0)  # mean
25
noise_estimate_mag = np.abs(noise_estimate)  # absolute value
26

27
estimate_mag = (dft_mag_spec-2*noise_estimate_mag)  # subtraction method
28
estimate_mag[estimate_mag < 0] = 0
29
# calculating the final estimate
30
estimate = estimate_mag*np.exp(1j*dft_phase_spec)
31
ift = []  # taking ift as input list containing inverse fourier transform of estimate
32
for i in estimate:
33
    ift.append(np.fft.ifft(i))  # appending in ift list
34

35
clean_data = []
36
clean_data.extend(ift[0][:int(fl/2)])  # extending clean_data containg ift list
37
for i in range(len(ift)-1):
38
    clean_data.extend(ift[i][int(fl/2):]+ift[i+1][:int(fl/2)])
39
# extending clean_data containing ift list
40
clean_data.extend(ift[-1][int(fl/2):])
41
clean_data = np.array(clean_data)  # converting it into array
42

43
# finally plotting the graph showing the diffrence in the noise
44
fig = plt.figure(figsize=(8, 5))
45
ax = plt.subplot(1, 1, 1)
46
ax.plot(np.linspace(0, 64000, 64000), data, label='Original', color="orange")
47
ax.plot(np.linspace(0, 64000, 64000), clean_data,
48
        label='Filtered', color="purple")
49
ax.legend(fontsize=12)
50
ax.set_title('Spectral Subtraction Method', fontsize=15)
51
filename = os.path.basename(file)
52
cleaned_file = "(Filtered_Audio)"+filename  # final filtered audio
53
wav.write(cleaned_file, rate=sr, data=clean_data.astype(np.int16))
54
# saved file name as audio.wav(Spectral Subtraction graph).jpg
55
plt.savefig(filename+"(Spectral Subtraction graph).jpg")
56

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.