0% found this document useful (0 votes)
39 views23 pages

Final 4,5,6

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views23 pages

Final 4,5,6

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Experiment – 4

ALLAMSETTI JAYARAM BT21ECE052

A) Generate a signal sampled at 8 kHz, which contains a sum of three


sinusoids at frequencies 50 Hz, 500 Hz, and 1000 Hz. Plot this signal for
a reasonable number of samples.
CODE:
import numpy as np
import matplotlib.pyplot as plt
fs = 8000
f1 = 50
f2 = 500
f3 = 1000
n = np.arange(0, fs)
x = np.sin(2*np.pi*f1*n/fs) + np.sin(2*np.pi*f2*n/fs) + np.sin(2*np.pi*f3*n/fs)
plt.plot(x[0:1500])
plt. tle("Input Signal: Sum of Three Sinusoids")
plt.ylabel("Amplitude")
plt.xlabel("Sample Index")
plt.show()
Output:
B) Design a standard factor-of-40 decimator. The edge frequencies of the
decimator filter are 90 Hz and 100 Hz. The peak passband and stopband
ripples are 0.001 and 0.005, respec vely. Design the filter. Plot the
magnitude and phase response of the filter.
C) Process the input signal by the standard decimator. Plot the output of
the decimator.
D) Design a two-stage decimator based on the IFIR approach. Use 20 as
the stretch factor for the IFIR filter. Plot the magnitude and phase
responses of the two filters.
E) Process the input signal by the two-stage IFIR decimator. Plot the
output of the decimator and compare it with that of part (2).
Repeat the above experiment for a factor-of-40 interpola on.
Code:
from scipy import signal

M = 4034
w = signal.windows.kaiser(M, beta=4.088)
h = (np.sin((np.pi)*(np.arange(M)-int(M/2))/40))/(np.pi*(np.arange(M)-int(M/2)))
h[int(M/2)] = 1/40

plt.plot(h)
plt. tle("Filter Impulse Response: Kaiser Window (beta=4.088)")
plt.ylabel("Amplitude")
plt.xlabel("Time (Sample Index)")
plt.show()

h_padded = np.zeros(fs)
h_filtered = h * w
h_padded[0:M] = h_filtered
H = np. . (h_padded)
plt.stem(np.abs(H))
plt. tle("Magnitude Response of Decimator Filter")
plt.ylabel("Magnitude")
plt.xlabel("Frequency (Hz)")

plt.show()

Output:
Code:
y = np.convolve(x, h_filtered, mode='same')

plt.plot(y)

plt. tle("Output of the Standard Decimator")


plt.ylabel("Amplitude")
plt.xlabel("Sample Index")
plt.show()
Output:

Code:
M_s = M / 2
w_s = signal.windows.kaiser(M_s, beta=4.088)
s = (np.sin((np.pi)*(np.arange(M_s)-int(M_s/2))/20))/(np.pi*(np.arange(M_s)-
int(M_s/2)))
s[int(M_s/2)] = 1/20
plt.plot(s)
plt. tle("Impulse Response of First Stage Filter: Kaiser Window (beta=4.088)")
plt.ylabel("Amplitude")
plt.xlabel("Sample Index")
plt.show()
s_filtered = s * w_s

S = np. . (s_filtered)
plt.stem(np.abs(S))
plt. tle("Magnitude Response of First Stage Filter")
plt.ylabel("Magnitude")
plt.xlabel("Frequency (Hz)")
plt.show()

s_upsampled = np.zeros(fs)
for i in range(int(M_s)):
s_upsampled[2*i] = s_filtered[i]
S_upsampled = np. . (s_upsampled)
plt.stem(np.abs(S_upsampled)[:150])
plt. tle("Magnitude Response of Upsampled First Stage Filter")
plt.ylabel("Magnitude")
plt.xlabel("Frequency (in Hz)")
plt.show()
H_stage2 = S
plt.stem(np.abs(H_stage2))
plt. tle("Magnitude Response of Second Stage Filter")
plt.ylabel("Magnitude")
plt.xlabel("Frequency (in Hz)")
plt.show()
Outputs:
F) Process the input signal by the two-stage IFIR decimator. Plot the output of the
decimator and compare it with that of part (2).
Code:
y_stage1 = np.convolve(x, s_filtered, mode='same')
y_stage2 = np.convolve(y_stage1, s_upsampled, mode='same')
plt.plot(y_stage2)
plt. tle("Output of the Two-Stage IFIR Decimator")
plt.ylabel("Amplitude")
plt.xlabel("Sample Index")
plt.show()
Output:
Part – B:

Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

sampling_freq = 8000
freq1 = 50
freq2 = 500
freq3 = 1000
me_samples = np.arange(0, sampling_freq)
input_signal = np.sin(2*np.pi*freq1* me_samples/sampling_freq) +
np.sin(2*np.pi*freq2* me_samples/sampling_freq) +
np.sin(2*np.pi*freq3* me_samples/sampling_freq)

interpola on_factor = 40
filter_length = 4034
kaiser_window = signal.windows.kaiser(filter_length, beta=4.088)
filter_coeffs = (np.sin((np.pi)*(np.arange(filter_length)-
int(filter_length/2))/interpola on_factor))/(np.pi*(np.arange(filter_length)-
int(filter_length/2)))
filter_coeffs[int(filter_length/2)] = 1/interpola on_factor

padded_filter = np.zeros(sampling_freq)
windowed_filter = filter_coeffs * kaiser_window
padded_filter[0:filter_length] = windowed_filter
frequency_response = np. . (padded_filter)

input_length = int(len(input_signal)/interpola on_factor)


upsampled_input = np.zeros(input_length*interpola on_factor)
for i in range(input_length):
upsampled_input[i*interpola on_factor] = input_signal[i]

# Process the upsampled signal with the standard interpolator filter


freq_upsampled_filtered = np. . (upsampled_input) * frequency_response
upsampled_filtered = np. .i (freq_upsampled_filtered)

plt.plot(np.real(upsampled_filtered))
plt. tle("Output of the Standard Interpolator")
plt.ylabel("Amplitude")
plt.xlabel("Sample Index")
plt.show()

transi on_band = 10 * 2 * np.pi / sampling_freq


min_a enua on = 0.001
stopband_a enua on = -20 * np.log10(min_a enua on)
filter_order = int((stopband_a enua on - 8) / (2.285 * transi on_band)) + 1
window_beta = 0.1102 * (stopband_a enua on - 8.7)
window_coeffs = signal.windows.kaiser(filter_order, beta=window_beta)

def compute_impulse_response(filter_order, stretch_factor):


tap_indices = np.arange(filter_order)
impulse_resp = (np.sin(np.pi * (tap_indices - int(filter_order/2)) / stretch_factor)) / (np.pi
* (tap_indices - int(filter_order/2)))
impulse_resp[int(filter_order/2)] = 1 / stretch_factor
return impulse_resp

def design_filter(filter_length, filter_order, stretch_factor, window_coeffs):


impulse_resp = compute_impulse_response(filter_order, stretch_factor)
filter_coeffs = impulse_resp * window_coeffs
padded_filter = np.zeros(filter_length)
padded_filter[0:filter_order] = filter_coeffs

return padded_filter

stretch_factor = 20
filter_coeffs = design_filter(sampling_freq, filter_order, stretch_factor, window_coeffs)
frequency_response = np. . (filter_coeffs)

upsampled_input = np.zeros(input_length*interpola on_factor)


for i in range(input_length):
upsampled_input[i*interpola on_factor] = input_signal[i]

freq_upsampled_filtered = np. . (upsampled_input) * frequency_response


upsampled_filtered = np. .i (freq_upsampled_filtered)

plt.plot(np.real(upsampled_filtered))
plt. tle("Output of the Two-Stage IFIR Interpolator")
plt.ylabel("Amplitude")
plt.xlabel("Sample Index")
plt.show()
Output:

Conclusion:
The results obtained from the conven onal decima on method and the IFIR (Interpolated
Finite Impulse Response) decima on technique are comparable. However, the IFIR approach
requires fewer computa onal resources compared to the tradi onal method. Consequently,
the IFIR decima on process offers a more efficient alterna ve for decima on opera ons.
Experiment – 5
ALLAMSETTI JAYARAM BT21ECE052

To compute STFT for an audio signal


Code:
import numpy as np
import matplotlib.pyplot as plt
import librosa
from IPython.display import Audio

audio_data, sampling_rate = librosa.load('female sample.wav', sr=40000)


Audio(data=audio_data, rate=sampling_rate)

signal_length = 4000
me_vector = np.arange(0, 1, 4/signal_length)
synthe c_signal = np.zeros(signal_length)

sinusoid_1 = np.sin(2*np.pi*2* me_vector)


sinusoid_2 = np.sin(2*np.pi*200* me_vector)
sinusoid_3 = np.sin(2*np.pi*20* me_vector)
sinusoid_4 = np.sin(2*np.pi*5* me_vector)

synthe c_signal[0:int(signal_length/4)] = sinusoid_1


synthe c_signal[int(signal_length/4):int(signal_length/2)] = sinusoid_2
synthe c_signal[int(signal_length/2):int(3*signal_length/4)] = sinusoid_3
synthe c_signal[int(3*signal_length/4):signal_length] = sinusoid_4

plt.plot(synthe c_signal)
plt.plot(np.abs(np. . (synthe c_signal)))
block_size = 400

gaussian_param = 0.01

def gaussian_window(gaussian_param, window_length):


indices = np.arange(window_length)
window_coeffs = np.exp(-gaussian_param*((indices-int(window_length/2))**2)/2)
return window_coeffs

window_func = gaussian_window(gaussian_param, block_size)


plt.plot(window_func)

def s t_jaya(signal, block_size, num_freqs, window_func):


index = 0
signal_length = len(signal)
s t_matrix = np.zeros([signal_length, num_freqs])

while index < signal_length:


freq_bins = np.zeros(num_freqs)
if index + block_size >= signal_length:
window_func = window_func[0:signal_length-index]
windowed_signal = window_func * signal[index:signal_length]
freq_bins[0:signal_length-index] = windowed_signal
else:
windowed_signal = window_func * signal[index:index+block_size]
freq_bins[0:block_size] = windowed_signal

s t_coeffs = np. . (freq_bins)


for j in range(len(windowed_signal)):
s t_matrix[index+j][0:num_freqs] = s t_coeffs

index += block_size

return s t_matrix

num_freqs = 800
s t_result = s t_jaya(synthe c_signal, block_size, num_freqs, window_func)

freq_indices = np.arange(0, num_freqs)


me_indices = np.arange(0, signal_length)
freq_indices, me_indices = np.meshgrid(freq_indices, me_indices)

fig = plt.figure()
plot_axis = fig.add_subplot(111, projec on='3d')
plot_axis.plot_surface(freq_indices, me_indices, (np.abs(s t_result)), cmap='viridis')
plot_axis.set_xlabel('Frequency')
plot_axis.set_ylabel('Time')
plot_axis.set_zlabel('Magnitude')
plt.show()

speech_block_size = 3000
speech_max_freq = 4000
speech_window = gaussian_window(gaussian_param, speech_block_size)
s t_speech = s t_jaya(audio_data, speech_block_size, speech_max_freq,
speech_window)

freq_indices = np.arange(0, speech_max_freq)


me_indices = np.arange(0, len(audio_data))
freq_indices, me_indices = np.meshgrid(freq_indices, me_indices)
fig = plt.figure()
plot_axis = fig.add_subplot(111, projec on='3d')
plot_axis.plot_surface(freq_indices, me_indices, (np.abs(s t_speech)), cmap='viridis')
plot_axis.set_xlabel('Frequency')

plot_axis.set_ylabel('Time')
plot_axis.set_zlabel('Magnitude')

Outputs:
Conclusion:
The Short-Time Fourier Transform (STFT) is employed for analyzing non-sta onary
signals, as it enables the iden fica on of me-varying frequency components that
cannot be discerned through the tradi onal Fourier Transform alone. The selec on
of the block size and window func on can significantly influence the visual
representa on of the STFT plot.
Experiment – 6
ALLAMSETTI JAYARAM BT21ECE052

Noise removal from the signal using Haar wavelet:


Audio data:
a. Import an audio file and add zero mean Gaussian noise to it. Perform
level-1 DWT decomposi on using Haar wavelet.
b. Suppress noise using a hard/so threshold and reconstruct the audio
signal.
c. Compare the original audio, noisy audio, and denoised audio files.
d. Repeat for different strengths of added noise.
Code:

import numpy as np

import matplotlib.pyplot as plt

import librosa

from IPython.display import Audio

from PIL import Image

# Load the audio file

audio_data, sampling_rate = librosa.load('female sample.wav', sr=40000)

Audio(data=audio_data, rate=sampling_rate)

audio_data = np.array(audio_data)

signal_length = len(audio_data)

# Pad the signal if its length is odd

if signal_length % 2 == 1:

audio_data = np.pad(audio_data, (0, 1), 'constant')

signal_length = len(audio_data)
# Add zero-mean Gaussian noise

noise_signal = np.random.normal(0, 0.01, signal_length)

noisy_audio = audio_data + noise_signal

plt.plot(noisy_audio)

Audio(data=noisy_audio, rate=sampling_rate)

plt. tle("Noisy_audio waveform")

wavelet_coeffs = np.zeros(signal_length)

wavelet_coeffs[:int(signal_length / 2)] = (noisy_audio[0::2] + noisy_audio[1::2]) / (2 ** 0.5)

wavelet_coeffs[int(signal_length / 2):] = (noisy_audio[0::2] - noisy_audio[1::2]) / (2 ** 0.5)

plt.plot(wavelet_coeffs)

plt. tle("level-1 DWT decomposi on using Haar wavelet")

Output:
Code:

wavelet_coeffs[int(signal_length / 2):] = np.zeros(int(signal_length / 2))

plt.plot(wavelet_coeffs)

plt. tle("Hard thresholding")

reconstructed_signal = np.zeros(signal_length)

approxima on = wavelet_coeffs[:int(signal_length / 2)]

detail = wavelet_coeffs[int(signal_length / 2):]

idx = 0

while idx < int(signal_length / 2):

reconstructed_signal[2 * idx] = (approxima on[idx] + detail[idx]) / ((2 ** 0.5))

reconstructed_signal[2 * idx + 1] = (approxima on[idx] - detail[idx]) / ((2 ** 0.5))

idx += 1

plt.plot(reconstructed_signal)

plt. tle("Reconstruc on of the denoised signal")

Audio(data=reconstructed_signal, rate=sampling_rate)

Output:
Image data:
a. Import an image (convert to grayscale if it is a colour image) and add zero
mean Gaussian noise with a standard devia on of 20.
b. Perform level-1 DWT decomposi on using Haar wavelet.
c. Suppress noise using a hard/so threshold and reconstruct the image.
d. Compute the following: PSNR (original_grayscale_image, noisy_image) and
e. PSNR (original_grayscale_image, denoised_image)
Code:
import cv2

import numpy as np

import pywt

# image to grayscale

img = cv2.imread('image.jpg')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# here we are adding zero-mean Gaussian noise with standard devia on 20

noise = np.random.normal(0, 20, gray.shape)

noisy_img = gray + noise.astype(np.int8)

# Level-1 DWT decomposi on using Haar wavelet

coeffs = pywt.wavedec2(noisy_img, 'haar', level=1)

cA, (cH, cV, cD) = coeffs

# Suppressing the noise using so thresholding

sigma = np.median(np.abs(cD)) / 0.6745 # Es mate noise level

threshold = sigma * np.sqrt(2 * np.log(noisy_img.size)) # So threshold

cH_so = pywt.threshold(cH, threshold, mode='so ')

cV_so = pywt.threshold(cV, threshold, mode='so ')

cD_so = pywt.threshold(cD, threshold, mode='so ')

# Reconstruc ng the denoised image

coeffs_denoised = [cA, (cH_so , cV_so , cD_so )]

denoised_img = pywt.waverec2(coeffs_denoised, 'haar')

denoised_img = np.uint8(np.clip(denoised_img, 0, 255))

# To resize the denoised image to match the original grayscale image size

denoised_img = cv2.resize(denoised_img, gray.shape[::-1])


# To Compute PSNR (original_grayscale_image, noisy_image)

psnr_noisy = cv2.PSNR(gray, noisy_img.astype(np.uint8))

print(f"PSNR (original_grayscale_image, noisy_image): {psnr_noisy:.2f} dB")

# To Compute PSNR (original_grayscale_image, denoised_image)

psnr_denoised = cv2.PSNR(gray, denoised_img)

print(f"PSNR (original_grayscale_image, denoised_image): {psnr_denoised:.2f} dB")

# To Display the original, noisy, and denoised images

cv2.imshow('Original', gray)

cv2.imshow('Noisy', noisy_img.astype(np.uint8))

cv2.imshow('Denoised', denoised_img)

cv2.waitKey(0)

cv2.destroyAllWindows()

Outputs:

Gray scalled image and Noisy Image:


Reconstructed Image:

Conclusion:

The applica on of the Haar transform to audio signals decomposes the signal into low and
high-frequency components, enabling the mi ga on of high-frequency noise through the
implementa on of hard or so thresholding techniques.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy