|
| 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 | + dft.append(np.fft.fft(i)) #now taking the first fourier transform of each window |
| 19 | +dft = np.array(dft) #converting dft into array |
| 20 | + |
| 21 | +dft_mag_spec = np.abs(dft) #converting dft into absolute values |
| 22 | +dft_phase_spec = np.angle(dft) #finding dft angle |
| 23 | +noise_estimate = np.mean(dft_mag_spec,axis=0) #mean |
| 24 | +noise_estimate_mag = np.abs(noise_estimate) #absolute value |
| 25 | + |
| 26 | +estimate_mag = (dft_mag_spec-2*noise_estimate_mag) #subtraction method |
| 27 | +estimate_mag[estimate_mag<0]=0 |
| 28 | +estimate = estimate_mag*np.exp(1j*dft_phase_spec) #calculating the final estimate |
| 29 | +ift = [] #taking ift as input list containing inverse fourier transform of estimate |
| 30 | +for i in estimate: |
| 31 | + ift.append(np.fft.ifft(i)) #appending in ift list |
| 32 | + |
| 33 | +clean_data = [] |
| 34 | +clean_data.extend(ift[0][:int(fl/2)]) #extending clean_data containg ift list |
| 35 | +for i in range(len(ift)-1): |
| 36 | + clean_data.extend(ift[i][int(fl/2):]+ift[i+1][:int(fl/2)]) |
| 37 | +clean_data.extend(ift[-1][int(fl/2):]) #extending clean_data containing ift list |
| 38 | +clean_data = np.array(clean_data) #converting it into array |
| 39 | + |
| 40 | +#finally plotting the graph showing the diffrence in the noise |
| 41 | +fig = plt.figure(figsize=(8,5)) |
| 42 | +ax = plt.subplot(1,1,1) |
| 43 | +ax.plot(np.linspace(0,64000,64000),data,label='Original',color="orange") |
| 44 | +ax.plot(np.linspace(0,64000,64000),clean_data,label='Filtered',color="purple") |
| 45 | +ax.legend(fontsize=12) |
| 46 | +ax.set_title('Spectral Subtraction Method', fontsize=15) |
| 47 | +filename = os.path.basename(file) |
| 48 | +cleaned_file = "(Filtered_Audio)"+filename #final filtered audio |
| 49 | +wav.write(cleaned_file,rate=sr, data = clean_data.astype(np.int16)) |
| 50 | +plt.savefig(filename+"(Spectral Subtraction graph).jpg") #saved file name as audio.wav(Spectral Subtraction graph).jpg |
0 commit comments