Amazing-Python-Scripts
55 строк · 2.4 Кб
1# Spectral Subtraction: Method used for noise reduction
2import scipy.io.wavfile as wav3import numpy as np4import matplotlib.pyplot as plt5
6file = input("Enter the file path: ")7sr, data = wav.read(file)8fl = 400 # frame_length9frames = [] # empty list10for i in range(0, int(len(data)/(int(fl/2))-1)):11arr = data[int(i*int(fl/2)):int(i*int(fl/2)+fl)]12frames.append(arr) # appending each array data into the frames list13frames = np.array(frames) # converting the frames list into an array14ham_window = np.hamming(fl) # using np.hamming15windowed_frames = frames*ham_window # multiplying frames array with ham_window16dft = [] # empty list containing fft of windowed_frames17for i in windowed_frames:18# now taking the first fourier transform of each window19dft.append(np.fft.fft(i))20dft = np.array(dft) # converting dft into array21
22dft_mag_spec = np.abs(dft) # converting dft into absolute values23dft_phase_spec = np.angle(dft) # finding dft angle24noise_estimate = np.mean(dft_mag_spec, axis=0) # mean25noise_estimate_mag = np.abs(noise_estimate) # absolute value26
27estimate_mag = (dft_mag_spec-2*noise_estimate_mag) # subtraction method28estimate_mag[estimate_mag < 0] = 029# calculating the final estimate
30estimate = estimate_mag*np.exp(1j*dft_phase_spec)31ift = [] # taking ift as input list containing inverse fourier transform of estimate32for i in estimate:33ift.append(np.fft.ifft(i)) # appending in ift list34
35clean_data = []36clean_data.extend(ift[0][:int(fl/2)]) # extending clean_data containg ift list37for i in range(len(ift)-1):38clean_data.extend(ift[i][int(fl/2):]+ift[i+1][:int(fl/2)])39# extending clean_data containing ift list
40clean_data.extend(ift[-1][int(fl/2):])41clean_data = np.array(clean_data) # converting it into array42
43# finally plotting the graph showing the diffrence in the noise
44fig = plt.figure(figsize=(8, 5))45ax = plt.subplot(1, 1, 1)46ax.plot(np.linspace(0, 64000, 64000), data, label='Original', color="orange")47ax.plot(np.linspace(0, 64000, 64000), clean_data,48label='Filtered', color="purple")49ax.legend(fontsize=12)50ax.set_title('Spectral Subtraction Method', fontsize=15)51filename = os.path.basename(file)52cleaned_file = "(Filtered_Audio)"+filename # final filtered audio53wav.write(cleaned_file, rate=sr, data=clean_data.astype(np.int16))54# saved file name as audio.wav(Spectral Subtraction graph).jpg
55plt.savefig(filename+"(Spectral Subtraction graph).jpg")56