Академический Документы
Профессиональный Документы
Культура Документы
LABMANUAL
K L UNIVERSITY
VADDESWARAM, GUNTUR 522 502 (A.P.) INDIA
2017-18
1
Signal Processing Lab 15 EC 2206
List of Experiments
2
LAB Evaluation Pattern
Student Sign
Faculty Sign
Remarks
No. Observation Results Viva Performance Total
5 marks 5 marks 5 marks 5 marks 20 marks
1
2
3
4
5
6
7
8
9
10
3
Course Team members and Chamber Venue details
6 R Chelladurai C324
7 J L Prasanna C204
4
Experiment 1
(i) x[n] sin(0.12 n) (ii) x[n] (0.9)n u[n] (iii) x[n] (0.5)n sin(0.2 n)u[n] (iv)
b) To develop MATLAB scripts for the DT sequence shown below and plot for the
following operations.
(i) x[n] (ii) x[n 2] (iii) x[n / 2] (iv) x[2n] (v) x[2n 1]
Theory:
The basic elementary signals / sequences are much useful in digital signal processing
for analysis purpose. These signals are described both in mathematical and graphical
representations as below.
1, n 0
sample / impulse sequence is defined as [n]
0, n 0
The Unit Step Sequence: A discrete time (D.T) unit step
sequence is defined as
5
1, n 0
u[n]
0, n 0
The Unit Ramp Sequence: A discrete time (D.T) ramp sequence is defined as
n, n 0
r[ n ]
0, n 0
Operations on Signals
(a) Transformation of independent variable (time): A sequence x[n] may be
shifted in time by replacing the independent variable n by n k , where k is
an integer. If k a is positive integer, the time shift results in a delay of the
6
sequence by k units of time. If k a is negative integer, the time shift results in
an advance of the signal of the sequence by | k | units of time.
(b) Folding / Reflection / Time reversal: Another useful modification of the
time base is to replace the independent variable n by n . The results of this
operation is a folding or a reflection of the signal about the time origin n 0 .
(c) Addition, subtraction and multiplication of DT sequences:
Addition x1[n] x2[n]
Subtraction
x1[n] x2[n] 0 2 5 0 -3 4
Multiplication x1[n] x2[n] 4 3 4 9 -2 5
(d) Amplitude scaling: Amplification and Attenuation:
Amplification by a factor N: y1[n] = Nx[n]
Attenuation by a factor N: y2[n] = x[n]/N
MATLAB Program:
% matlab program for generation of discrete time signals
clc; clear all; close all;
n=-10:1:20;
x=[zeros(1,6),-1,2,-2.3,0,1,3,3.5,-
2.1,6,0,7,zeros(1,14)];
x1=sin(0.12*pi*n);
x2=(0.9.^n).*(n>=0);
x3=(0.5.^n).*sin(0.2*pi*n).*(n>=0);
subplot(221);
stem(n,x1);grid on;
title('discrete time sinusoidal sequence');
xlabel('-->n');
ylabel('amplitude'); axis([-10 20 -1 1]);
subplot(222);
stem(n,x2);grid on;
title('discrete time exponential sequence');
xlabel('-->n');
ylabel('amplitude'); axis([-10 20 -1 1]);
subplot(223);
stem(n,x3);grid on;
title('exponential modulated sinusoidal sequence');
xlabel('-->n');
ylabel('amplitude'); axis([-10 20 -1 1]);
7
subplot(224);
stem(n,x); grid on;
title('x[n]=[-1,2,-2.3,0,1,3,3.5,-2.1,6,0,7]');
xlabel('-->n');
ylabel('amplitude'); axis([-10 20 -3 7]);
8
xlabel('-->n');
ylabel('Amplitude');
Outputs:
discrete time sinusoidal sequence discrete time exponential sequence
1 1
0.5 0.5
amplitude
amplitude
0 0
-0.5 -0.5
-1 -1
-10 -5 0 5 10 15 20 -10 -5 0 5 10 15 20
-->n -->n
0.5
4
amplitude
amplitude
0 2
0
-0.5
-2
-1
-10 -5 0 5 10 15 20 -10 -5 0 5 10 15 20
-->n -->n
9
input sequence x[n]
3
Amplitude
0
-1
-2
-3
-3 -2 -1 0 1 2 3 4
-->n
1
Amplitude
-1
-2
-3
-4 -3 -2 -1 0 1 2 3
-->n
2
Amplitude
-2
-5 -4 -3 -2 -1 0 1 2 3 4 5 6
-->n
right shifted input sequence x[n-2]
2
Amplitude
-2
-5 -4 -3 -2 -1 0 1 2 3 4 5 6
-->n
left shifted input sequence x[n+2]
2
Amplitude
-2
-5 -4 -3 -2 -1 0 1 2 3 4 5 6
-->n
2
Amplitude
-2
-4
-3 -2 -1 0 1 2 3 4
-->n
downsampled input sequence x[2n]
2
Amplitude
-2
-3 -2 -1 0 1 2 3 4
-->n
downsampled input sequence x[2n-1]
2
Amplitude
-2
-3 -2 -1 0 1 2 3 4
-->n
Result: The given sequences are generated and the graphs are plotted successfully.
10
Experiment 2
Frequency domain representation of DT sequences: DFT and FFT
AIM: a) To develop MATLAB script for the computation of N-point DFT of 4-point
DT sequence shown below:
1, 0 n 3
x[n]
0, Otherwise
(i) N = 4, (ii) N =8, (iii) N =16, and plot the magnitude and phase response.
b) To perform the following tasks for the sequences given below:
x1[n] {1 2 3 4 5} and x2[n] {2 1 1 1} .
(i) Determine 5-point circular convolution using analytical calculations.
(ii) Verify it by writing a MATLAB script using the cconv function.
(iii) Verify it by writing MATLAB script using DFT and IDFT.
Theory:
The discrete Fourier transform (DFT) is one of the specific forms of Fourier analysis.
It transforms one function into another, which is called the frequency domain
representation, or simply the DFT, of the original function (which is often a function
in the time domain). But the DFT requires an input function that is discrete and whose
non-zero values have a limited (finite) duration. Such inputs are often created by
sampling a continuous function.
11
shifting the original function by multiples of some period, T, and adding all the copies
together. Circular convolution is another way of finding the convolution sum of two
input signals. It resembles the linear convolution, except that the sample values of one
of the input signals is folded and right shifted before the convolution sum is found.
Also note that circular convolution could also be found by taking the DFT of the two
input signals and finding the product of the two frequency domain signals. The
Inverse DFT of the product would give the output of the signal in the time domain
which is the circular convolution output.
MATLAB Program:
% matlab program to find N-point DFT of a given sequence
clc; clear all; close all;
tic;
x=[1 1 1 1];
N=input('enter the length of DFT:');
n=0:1:N-1;
L=length(x);
x=[x zeros(1,N-L)]
%compute fft
disp('N-Point DFT of the given sequence is');
X=fft(x,N)
toc;
subplot(311);stem(n,x);
title('input sequence');
xlabel('n --->');
ylabel('amplitude -->');grid;
subplot(312);stem(n,abs(X));
title('Magnitude Plot');
xlabel('n --->');
ylabel('Magnitude -->');grid;
subplot(313);stem(n,angle(X));
title('Phase Plot');
xlabel('n --->');
ylabel('Phase -->');grid;
12
x1
subplot(222);stem(x2);
title('second sequence x2');
xlabel('time --->');
ylabel('amplitude -->');grid;
disp('Second sequence x2 is');
x2
subplot(2,2,[3,4]);stem(yC);
title('circular convolution of x1 and x2');
xlabel('time --->');
ylabel('amplitude -->');grid;
disp('Circular convolution using cconv()is');
yC
13
Outputs:
Enter the length of DFT: 8
x= 1 1 1 1 0 0 0 0
X=
Columns 1 through 4
Columns 5 through 8
input sequence
1
amplitude -->
0.5
0
0 1 2 3 4 5 6 7
n --->
Magnitude Plot
4
3
Magnitude -->
0
0 1 2 3 4 5 6 7
n --->
Phase Plot
2
1
Phase -->
-1
-2
0 1 2 3 4 5 6 7
n --->
14
Circular convolution using cconv() function
First sequence x1 is
x1 = 1 2 3 4 5
Second sequence x2 is
x2 = 2 -1 1 -1
1.5
4
1
3
amplitude -->
amplitude -->
0.5
2
0
1
-0.5
0 -1
1 1.5 2 2.5 3 3.5 4 4.5 5 1 1.5 2 2.5 3 3.5 4
time ---> time --->
4
amplitude -->
-2
1 1.5 2 2.5 3 3.5 4 4.5 5
time --->
First sequence x1 is
x1 = 1 2 3 4 5
Second sequence x2 is
x2 = 2 -1 1 -1
15
Circular convolution of x1 and x2 using DFT nad IDFT is
1.5
4
1
3
---> amplitude
---> amplitude
0.5
2
0
1
-0.5
0 -1
1 1.5 2 2.5 3 3.5 4 4.5 5 1 1.5 2 2.5 3 3.5 4
---> time ---> time
4
---> amplitude
-2
1 1.5 2 2.5 3 3.5 4 4.5 5
---> time
Result: Hence N-point DFT of a given sequence and Circular convolution of given
two sequences are obtained successfully.
16
Experiment 3
Design and Implementation of Digital IIR Filters
AIM: To design the Digital IIR filters using the given specifications:
Sampling rate of 3500 Hz, pass band edge frequency of 1050 Hz, Stop band edge
frequency of 600 Hz, Pass band ripple of 1 dB, and a minimum stop band attenuation
of 50 dB.
(i) Using MATLAB, determine the lowest order of a digital IIR lowpass filter of
Butterworth and Chebyshev types.
(ii) Design high pass digital filters for the above three approximations using
MATLAB.
(iii) Plot the magnitude and phase response both in normalized frequency and
logarithmic scale.
Theory:
The IIR filter can realize both the poles and zeroes of a system because it has a
rational transfer function, described by polynomials in z in both the numerator and the
denominator
17
These filters differ in the nature of their magnitude responses as well as in their design
and implementation.
BUTTERWORTH FILTERS:
Butterworth filters have very smooth passband, which we pay for with a relatively
wide transition region. A Butterworth filter is characterized by its magnitude
frequency response,
where N is the order of the filter and c is defined as the cutoff frequency where the
filter magnitude is 1/2 times the dc gain (=0).
18
CHEBYSHEV FILTERS:
Chebyshev filters are equiripple in either the passband or stopband. Hence the
magnitude response oscillates between the permitted minimum and maximum values
in the band many times depending upon the order of filters. There are two types of
chebyshev filters. The chebyshev I filter is equiripple in passband and monotonic in
the stopband, where as chebyshev II is just the opposite.
The Chebyshev low-pass filter has a magnitude response given by
where
A is the filter gain and is a constant and is the 3-dB cutoff frequency
The Chebyshev polynomial of the 1st kind of Nth order, CN(x) is given by
The magnitude response has equiripple pass band and maximally flat stop band.
By increasing the filter order N, the Chebyshev response approximates the ideal
response.
The phase response of the Chebyshev filter is more non-linear than the Butter worth
filter for a given filter length N.
19
MATLAB Program:
% Butterworth IIR Filter Design
clc; clear all; close all; warning off;
% IIR filter design specifications
rp=1; rs=50; wp=1050; ws=600; fs=3500;
wpn=2*wp/fs;wsn=2*ws/fs;
[N,wc]=buttord(wpn,wsn,rp,rs);
disp('The order of the required HPF is...');
N
disp('The cut-off frequency of the required Filter is...');
wc
c=input('enter choice of filter 1. LPF 2. HPF \n ');
if(c==1)
[b,a]=butter(N,wc,'low'); % to get the filter coefficients
disp('The coefficients of the required LPF are...');
b
a
end
if(c==2)
[b,a]=butter(N,wc,'high'); % to get the filter coefficients
disp('The coefficients of the required HPF are...');
b
a
end
[H,w]=freqz(b,a,512,fs);% to get the transfer function of the
filter
mag=20*log10(abs(H));
phase=angle(H);
subplot(211);
plot(w,mag);grid on;
ylabel('--> Magnitude in dB');
xlabel('--> Normalized frequency in Hz');
title('Magnitude Response of desired Butterworth IIR Filter');
subplot(212);
plot(w,phase);grid on;
ylabel('--> Phase in radians');
xlabel('--> Normalized frequency in Hz');
title('Phase Response of desired Butterworth IIR Filter');
wpn=2*wp/fs;wsn=2*ws/fs;
[N,wn]=cheb1ord(wpn,wsn,rp,rs);
20
if(c==1)
[b,a]=cheby1(N,0.5, wn,'low');
disp('Filter coefficients of the desired Chebyshev IIR Filter
are:');
b
a
end
if(c==2)
[b,a]=cheby1(N,0.5,wn,'high');
disp('Filter coefficients of the desired Chebyshev IIR Filter
are:');
b
a
end
N=11;
Rw=boxcar(N);
b=fir1(10,0.2,Rw);
disp('window coefficient = ');disp(Rw')
21
%-------------------------------------------------------------
-----------
n = 0:N-1;
figure(); stem(n, Rw,'m','fill','LineWidth',1.5); grid
xlabel('Time index ------>');
ylabel('Magnitude--->');
title('Rectangular Window');
axis([-1 N -0.05 1.05]);
%-------------------------------------------------------------
-------
% Magnitude Response
figure();
subplot(2,1,1);plot(f,mag,'r','LineWidth',1.5); grid
xlabel('Real frequency ----->');ylabel('Gain DB ----->');
title('Magnitude Response of the given FIR filter ');
% Phase response
phase = angle(h);
subplot(2,1,2); plot(f,phase,'b','LineWidth',1.5);
xlabel('Real frequency ---->');ylabel('Angle in Radians ----
>');
title('Phase response of the given FIR filter'); grid
%-------------------------------------------------------------
------
% Result
%
% Filter coefficient
%
% b =
% % 0.00000000000000 0.03989988227886 0.08607915423243
0.12911873134864
% 0.15959952911546 0.17060540604922 0.15959952911546
0.12911873134864
% 0.08607915423243 0.03989988227886 0.00000000000000
% Window coefficient
% 1 1 1 1 1 1 1 1 1 1
1
% Comments:
% % Cut-off frequency given is 5kHz = 0.2 radians/sec (shown
in freq. response
% figure)...................ok
% % Ripples are observed at less than -
20dB..............................ok
% % In Phase response we observe linear
responses......................ok
% % Which show that overall response is satisfactory.
22
Outputs:
The order of the required Butterworth Digital IIR Filter is...
N=8
The cut-off frequency of the required Butterworth IIR Filter is...
wc = 0.5646
enter choice of filter 1. LPF 2. HPF
1
Frequency response of desired Butterworth IIR LPF is:
The coefficients of the required Butterworth IIR LPF are...
b=
0.0199 0.1594 0.5578 1.1156 1.3945 1.1156 0.5578 0.1594 0.0199
a=
1.0000 1.0280 1.4878 0.8588 0.5153 0.1608 0.0430 0.0057 0.0004
-100
--> Magnitude in dB
-200
-300
-400
0 200 400 600 800 1000 1200 1400 1600 1800
--> Normalized frequency in Hz
Phase Response of the desired Butterworth IIR Filter
4
2
--> Phase in radians
-2
-4
0 200 400 600 800 1000 1200 1400 1600 1800
--> Normalized frequency in Hz
23
The coefficients of the required HPF are...
b=
0.0039 -0.0310 0.1086 -0.2173 0.2716 -0.2173 0.1086 -0.0310 0.0039
a=
1.0000 1.0280 1.4878 0.8588 0.5153 0.1608 0.0430 0.0057 0.0004
-200
-400
0 200 400 600 800 1000 1200 1400 1600 1800
--> Normalized frequency in Hz
Phase Response of the desired Butterworth IIR Filter
4
2
--> Phase in radians
-2
-4
0 200 400 600 800 1000 1200 1400 1600 1800
--> Normalized frequency in Hz
The order and cut-off freq of the chebyshev filter for the given specs is:
N = 5 and wn = 0.6000
enter choice of filter 1. LPF 2. HPF
1
Filter coefficients of the Chebyshev Low pass IIR Filter are:
b=
0.0665 0.3327 0.6654 0.6654 0.3327 0.0665
a=
1.0000 0.1825 1.0011 -0.2126 0.2680 -0.1098
24
Magnitude Response of the desired Chebyshev(Type-I) Filter
0
--> Magnitude in dB
-100
-200
-300
0 200 400 600 800 1000 1200 1400 1600 1800
--> Normalized frequency in Hz
Phase Response of the desired Chebyshev(Type-I) Filter
4
2
--> Phase in radians
-2
-4
0 200 400 600 800 1000 1200 1400 1600 1800
--> Normalized frequency in Hz
25
Magnitude Response of the desired Chebyshev(Type-I) Filter
0
--> Magnitude in dB
-100
-200
-300
0 200 400 600 800 1000 1200 1400 1600 1800
--> Normalized frequency in Hz
Phase Response of the desired Chebyshev(Type-I) Filter
4
2
--> Phase in radians
-2
-4
0 200 400 600 800 1000 1200 1400 1600 1800
--> Normalized frequency in Hz
-50
-100
0 0.5 1 1.5 2 2.5 3 3.5
Real frequency ----->
Phase response of the given FIR filter
4
Angle in Radians ---->
-2
-4
0 0.5 1 1.5 2 2.5 3 3.5
Real frequency ---->
Result: Hence Butterworth and Chebyshev type IIR filters and FIR filters are
designed as per the given specifications successfully.
26
Experiment 4
Spectral effects of Decimation and Interpolation of discrete sequences
AIM: To observe the spectral effects of decimation and Interpolation of discrete time
sequences.
The following figure shows a typical M-fold decimation filter, where M is the integer value by
which you want to decrease the sampling frequency. This filter contains a lowpass FIR filter
H(z). This lowpass FIR filter is an anti-aliasing filter followed by anM-fold decimator. The
decimator passes every Mth sample and discards the other samples. After this operation, the
decimation filter changes the sampling frequency fs of the input signal x(n) to a new sampling
frequency fs/M. The decimation filter then returns an output signal y(n) with the new sampling
frequency.
27
To prevent aliasing, this system uses the lowpass filter H(z) before the M-fold decimator to
suppress the frequency contents above the frequency fs/(2M), which is the Nyquist frequency
of the output signal. This system produces the same results as an analog anti-aliasing filter
with a cutoff frequency of fs/(2M) followed by an analog-to-digital (A/D) converter with a
sampling frequency of fs/M. Because the system shown in the figure above is in the digital
domain, H(z) is a digital anti-aliasing filter.
The simplest method to interpolate by a factor of L is to add L-1 zeros in between the
samples, multiply the amplitude by L and filter the generated signal, with a so-called anti-
imaging low pass filter at the high sampling frequency.
MATLAB Program:
%Illustration of effect of interpolation in the frequency domain
clc; clear all; close all;
n=0:1:1023;
i=1:1024;
x=1/4*sinc(1/4*(n-512)).^2; %input sequence
y=[zeros(1,2048)];
y(2*i)=x; %upsampled sequence with a factor of 2
y1=[zeros(1,3072)];
y1(3*i)=x; %upsampled sequence with a factor of 3
f=-2:1/512:2;
h1=freqz(x,1,2*pi*f); %frequency response of original sequence
x
h2=freqz(y,1,2*pi*f); %frequency response of upsampled
sequence with factor 2
h3=freqz(y1,1,2*pi*f); %frequency response of upsampled
sequence with factor 3
subplot(311), plot(f,abs(h1));
xlabel('frequency'); ylabel('magnitude');
subplot(312), plot(f,abs(h2));
xlabel('frequency'); ylabel('magnitude');
subplot(313), plot(f,abs(h3));
xlabel('frequency'); ylabel('magnitude');
28
h1=freqz(xd,1,pi*f); %frequency response of original sequence
xd
h2=freqz(xd1,1,pi*f); %frequency response of decimated
sequence xd1
subplot(211), plot(f,abs(h1));
xlabel('frequency'); ylabel('magnitude');
title('frequency response of input sequence');
subplot(212), plot(f,abs(h2));
xlabel('frequency'); ylabel('magnitude');
title('frequency response of decimated sequence');
axis([-2 2 0 1]);
Outputs:
Illustration of effect decimation of in the frequency domain
Enter the highest normalized frequency component: 0.25
Enter Decimation Factor: 3
0.5
0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
frequency
frequency response of decimated sequence
1
magnitude
0.5
0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
frequency
29
Enter the highest normalized frequency component: 0.25
Enter Decimation Factor: 5
0.5
0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
frequency
frequency response of decimated sequence
1
magnitude
0.5
0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
frequency
1
magnitude
0.5
0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
frequency
1
magnitude
0.5
0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
frequency
1
magnitude
0.5
0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
frequency
30
Experiment 5
Design the analysis/synthesis of two-channel orthogonal filter bank
AIM: To design the analysis and synthesis of two-channel orthogonal filter bank with
the following specifications:
filter length N = 32, and the lowpass passband edge frequency p = 0.43.
Theory:
firpr2chfb: FIR perfect reconstruction 2 channel filter bank design.
[h0,h1,g0,g1] = firpr2chfb (N,Fp) designs four FIR filters for the analysis (h0 and h1)
and synthesis (g0 and g1) sections of a two-channel perfect reconstruction filter bank.
The design corresponds to so-called orthogonal filter banks also known as power-
symmetric filter banks.
N is the order of all four filters, and it must be an odd integer. Fp is the passband-edge
for the lowpass filters H0 and G0 it must be less than 0.5. H1 and G1 are highpass
filters with passband-edge given by 1-Fp.
MATLAB Program:
clc; clear all; close all;
N = 32;
[h0, h1, g0, g1] = firpr2chfb(N-1, 0.43);
n=0:N-1;
figure(1);
subplot(4,1,1);
stem(n,h0);
ylabel('h_0[n]');
title('Figure 1: Impulse Response');
subplot(4,1,2);
stem(n,h1);
xlabel('n-->');
ylabel('h_1[n]');
subplot(4,1,3);
stem(n,g0);
31
xlabel('n-->');
ylabel('g_0[n]');
subplot(4,1,4);
stem(n,g1);
xlabel('n-->');
ylabel('g_1[n]');
figure(2);
zplane(h0,1);
title('Figure 2: Pole-Zero plot of H_0(z)');
figure(3);
zplane(h1,1);
title('Figure 3: Pole-Zero plot of H_1(z)');
figure(4);
zplane(g0,1);
title('Figure 4: Pole-Zero plot of G_0(z)');
figure(5);
zplane(g1,1);
title('Figure 5: Pole-Zero plot of G_1(z)');
[Gdh0,f] = grpdelay(h0,1,512,2);
xlabel('omega/pi'); ylabel('Group delay, samples');
title('Figure 6: Group delay');
legend(-1, 'H_0(z)' , 'H_1(z)');
[H0,f] = freqz(h0,1,1024,2);
[H1,f] = freqz(h1,1,1024,2);
figure(7);
subplot(4,1,1:3);
plot(f, 20*log10(abs(H0)), f, 20*log10(abs(H1)), 'b',
'linewidth', 1); grid on;
title('Figure 7: Two channel filter bank');
xlabel('omega/pi'); ylabel('Gain, dB');
axis([0,1,-60,2]);
% figure(8);
subplot(4,1,4);
t = (conv(h0, g0) + conv(h1, g1))/2;
stem(0:2*(N-1), t);
xlabel('n-->'); ylabel('t[n]');
axis([0,2*(N-1),-0.2,1.1])
32
Outputs:
0
0
-0.5
0 5 10 15 20 25 30 35
0.5
h [n]
0
1
-0.5
0 5 10 15 20 25 30 35
n-->
1
g [n]
0
0
-1
0 5 10 15 20 25 30 35
n-->
1
g [n]
0
1
-1
0 5 10 15 20 25 30 35
n-->
0.8
0.6
0.4
0.2
Imaginary Part
31
0
-0.2
-0.4
-0.6
-0.8
-1
-1 -0.5 0 0.5 1
Real Part
33
Figure 3: Pole-Zero plot of H (z)
1
0.5
Imaginary Part
31
0
-0.5
-1
0.5
Imaginary Part
31
0
-0.5
-1
34
Figure 6: Group delay
1 H (z)
0
H (z)
1
0.5
Group delay, samples
31
0
-0.5
-1
-1 -0.5 0 0.5 1
omega/pi
-10
-20
Gain, dB
-30
-40
-50
-60
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
1 omega/pi
0.5
t[n]
0 10 20 30 40 50 60
n-->
Result: Hence the analysis and synthesis of two-channel orthogonal filter bank with
the given specifications are designed.
35
Experiment 6
Signal feature extraction using the wavelet transformation of White Noise, EMG
or ECG signals
Introduction
The Energy, Variance, Standard Deviation, and the Waveform Length of the
wavelet coefficients are some of the other features by which DT signals can be
characterized. This experiment demonstrates the utility of these features in ad-
dition to the properties of the discrete-time signal, the discrete fourier spectrum
properties.
The energy, E of the signal at level, L of the wavelet tree is defined as,
L 1
NX
EL = |Ck,L |2 (1)
k=0
Objectives
1. Experience of using Wavelets in contrast to FFT for identifying signal
features
2. Select your best choice of wavelet in any one application (White noise,
EMG or ECG) for signal characterization
Methodology
Algorithm Consider DT signal sampled at SF samples/second for seconds
41
Figure 1: Uniformly distributed sequence-1
Generated the plots with the following parameters, N=8192 samples, Window-
Size=1024 samples, WindInc=256 samples, Fs=120 samples/second
1. feat = getmswtfeat(rand(1024*8, 1),128*8,32*8,120);
2. feat = getmswtfeat(rand(1024*8, 1),128*8,32*8,120);
3. feat = getmswtfeat(ecgsignal,128*8,32*8,120);
Pseudo code
Viva
42
Figure 2: Uniformly distributed sequence-2
Figure 3: Electrocardiogram
43
Figure 4: Electrocardiogram
44
Figure 6: Uniformly distributed sequence-2 features
45
Figure 8: Electrocardiogram features
% Inputs
%
% x: columns of signals
% winsize: window size (length of x)
% wininc: spacing of the windows (winsize)
% SF: sampling frequency (Not used in the current implementation,
% but I left you some options down there)
% Outputs
%
% feat: WT features organized as [Energy, Variance, Waveform Length, Entropy]
% Example
%
% feat = getmswtfeat(rand(1024,1),128,32,32);
% Assuming here rand(1024,1) (this can be any one dimensional signal,
% for example EEG or EMG) is a one dimensional signal sampled at 32 samples
% per second for 32 seconds only. Utilizing a window size of 128 at 32 increments,
% features are extracted from the wavelet tree.
% I assumed 10 decomposition levels (J=10) below in the code.
% For a full tree at 10 levels you should get 11 features
% as we have decided to extract 4 types of features then we get 11 x 4 =44
% features.
% =========================================================================
% Multiscale Wavelet Transform feature extraction code by Dr. Rami Khushaba
% Research Fellow Faculty of Engineering and IT
% University of Technology, Sydney.
% Email: Rami.Khushaba@uts.edu.au
% URL: www.ramikhushaba.com (Matlab Code Section)
46
% last modified 29/08/2012
% last modified 09/02/2013
if nargin < 4
if nargin < 3
if nargin < 2
winsize = size(x,1);
end
wininc = winsize;
end
error('Please provide the sampling frequency of this signal')
end
if isequal(dec.dirDec,'c')
dim = 1;
end
[cfs,longs] = wdec2cl(dec,'all'); % retrieve coefficients
level = length(longs)2;
if dim==1
cfs = cfs';
longs = longs';
end
numOfSIGs = size(cfs,1);
num CFS TOT = size(cfs,2);
absCFS = abs(cfs);
absCFS0 = (cfs);
cfs POW2 = absCFS.2;
47
Energy = sum(cfs POW2,2);
percentENER = 0*ones(size(cfs POW2));
notZER = (Energy>0);
percentENER(notZER,:) = 100*cfs POW2(notZER,:)./Energy(notZER,ones(1,num CFS TOT));
100*cfs POW2(notZER,:)./Energy(notZER,ones(1,num CFS TOT));
%% or try this version below and tell us which one is the best on your data
% percentENER(notZER,:) = cfs POW2(notZER,:);
48
Experiment 7
Automatically insert a watermark on an Image
Introduction
Watermarking is a technique for ascertaining the ownership and authenticity of
digital documents and certificates.
This experiment provides clues to the embedding of a small logo or a small
image inside a cover image and the process of regaining back the original cover
image without any loss in pixel values.
The images are encoded into the LL, LH, HL, and HH coefficients by the
choice of any 2-D wavelet transformation. LL is called the fine component of
the signal which encodes the low frequency content and the LH, HL, and HH
are called the coarse components which encode the Low-High, High-Low, and
High-High frequencies of the signal.
The LL of the watermark image is embedded into the LL of the cover image.
Objectives
1. Observe the performance of the various wavelets used in creating a clear
watermarked image.
2. How does the quality of the watermarked image vary with alpha in the
embedded expression LL + L L?
3. Understand the effectiveness of the wavelet method as opposed to other
existing methods such eigen decomposition, SVD, etc.
Methodology
If the images are RGB image, they are converted to grayscale image with the
built-in function rgb2gray()
1. Load image
2. Detect Cover Image and Watermark Image
3. Use DWT to Insert Watermark by adding a percentage of watermark
wavelet coefficients to cover image wavelet coefficients.
4. Reverse the process the extract the watermark and the cover image
5. Compare original Cover Image and watermark images with extracted cover
image and watermark image and conclude on the performance of the var-
ious wavelets used.
Observations
Record your observation and save your plots for the generation of a final report.
49
Figure 9: turtle
50
Figure 11: watermarked feat ecg direct
51
Figure 13: decomposed L1 feat ecg direct
52
Figure 15: normxcorr2 featecgdirectLL1 turtleLL1
Viva
1. Use of gray2rgb()?
Code
clc;
clear all;
close all;
% MEDICAL IMAGE WATERMARKING USING 2D DWT
% MIW > Program written by Dr.P.V.V.Kishore on 26/9/2013
% Medical Image Watermarking Initial Approach to the Problem
% Medical Images contain vital imformation and watermaking them presents a
% significant challenge to the researchers.
% Read a Medical image that is to be watermarked
53
% ORIGINAL IMAGE TO BE WATERMARKED
[filename1,pathname]=uigetfile('*.*','select the image'); % User Input Image
I=imread(num2str(filename1));
I=rgb2gray(I); % Convert to gray scale
I=imresize(I,[512,512],'bilinear'); % Resize the image to standard resolution
figure(1);
imshow(I);
title('original image to watermarked'); % orginal image for watermarking
% IMAGE WATERMARK
% Read Watermark Image In this case it the picture of the person to which
% the mediacl images belong to. Here we have considered a lena image of
% size 64x64.
iw=imread('turtle.png');
% In case of a color image convert to rgb scale
if iw(:,:)
iw=iw;
else iw=rgb2gray(iw);
end
Iw=iw;
Iw=imresize(Iw,[512,512],'bilinear');
% What is the significance of threshold valve
Tr=50; % Set the Threshold Value
k=0.02; % What is this K indicate..
%imshow(iw)
54
a=a+1;
b=1;
end
W=W';
Watermarkedimage=LL+0.1*W;
Watermarkedimage level1= idwt2(Watermarkedimage,LH,HL,HH,'db2');
figure(4)
imshow(Watermarkedimage level1,'DisplayRange',[]), title('Watermarkedimagelevel1');
recovered image=aLL;
figure(5)
imshow(recovered image,[]);
for i=1:m
for j=1:n
e=e+double((img1(i,j)img2(i,j))2);
end
end
embedded meanse=e/(m*n)
%PSNR(Peak SignaltoNoise Ratio for EMBEDDING
e1=embedded meanse;
m=max(max(img1));
embedded psnr=10*log((double(m)2)/e1)
% MEAN SQUARE ERROR FOR EXTRACTION
e=0; % Initialize the error variable to zero
img11=LL; % Original Image
img22=recovered image; % Watermarked image level1
[m n]=size(img11);
for i=1:m
for j=1:n
e=e+double((img11(i,j)img22(i,j))2);
end
end
extracted meanse=e/(m*n)
%PSNR(Peak SignaltoNoise Ratio for EXTRACTION
e1=extracted meanse;
m=max(max(img11));
extracted psnr=10*log((double(m)2)/e1)
%Normalized Cross Coorelation (NCC)
c = normxcorr2(img1,img2);
figure(6), surf(c), shading flat
cc=normxcorr2(img11,img22);
55
figure(7),surf(c),shading flat
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
56
Experiment 8
Measure Similarity between two Voice Signals and Find periodic patterns in
temperature changes during a week.
Introduction
This example shows how to measure signal similarities. It will help you answer
questions such as: How do I compare signals with different lengths or different
sampling rates? How do I find if there is a signal or just noise in a measurement?
Are two signals related? How to measure a delay between two signals (and how
do I align them)? How do I compare the frequency content of two signals?
Similarities can also be found in different sections of a signal to determine if a
signal is periodic.
Objectives
Comparing Signals with Different Sampling Rates
Requirements
MATLAB, Wavelet Toolbox, Personal Computer
Methodology
Measure Similarity between two Voice Signals
1. Comparing Signals with Different Sampling Rates
2. Finding a Signal in a Measurement
3. Measuring Delay Between Signals and Aligning Them
4. Comparing the Frequency Content of Signals
5. Finding Periodicities in a Signal
Observations
Comparing Signals with Different Sampling Rates
Consider a database of audio signals and a pattern matching application where
you need to identify a song as it is playing. Data is commonly stored at a low
sampling rate to occupy less memory.
The first and the second subplot show the template signals from the database.
The third subplot shows the signal which we want to search for in our database.
Just by looking at the time series, the signal does not seem to match to any
of the two templates. A closer inspection reveals that the signals actually have
different lengths and sampling rates,
57
Fs1 = 4096
Fs2 = 4096
Fs = 8192
Different lengths prevent you from calculating the difference between two
signals but this can easily be remedied by extracting the common part of signals.
Furthermore, it is not always necessary to equalize lengths. Cross-correlation
can be performed between signals with different lengths, but it is essential to
ensure that they have identical sampling rates. The safest way to do this is
to resample the signal with a lower sampling rate. The resample function
applies an anti-aliasing(low-pass) FIR filter to the signal during the resampling
process.
Finding a Signal in a Measurement
We can now cross-correlate signal S to templates T1 and T2 with the xcorr
function to determine if there is a match.
The first subplot indicates that the signal and template 1 are less correlated
while the high peak in the second subplot indicates that signal is present in the
second template.
timeDiff = 0.0609
The peak of the cross correlation implies that the signal is present in template
T2 starting after 61 ms.
Measuring Delay Between Signals and Aligning Them
Consider a situation where you are collecting data from different sensors,
recording vibrations caused by cars on both sides of a bridge. When you analyze
the signals, you may need to align them. Assume you have 3 sensors working at
58
same sampling rates and they are measuring signals caused by the same event.
The maximum value of the cross-correlations between s1 and s2 and s1 and
s3 indicate time leads/lags.
t21 = -350
t31 = 150
t21 indicates that s2 lags s1 by 350 samples, and t31 indicates that s3 leads s1
by 150 samples. This information can now used to align the 3 signals.
Comparing the Frequency Content of Signals
A power spectrum displays the power present in each frequency. Spectral
coherence identifies frequency-domain correlation between signals. Coherence
values tending towards 0 indicate that the corresponding frequency components
are uncorrelated while values tending towards 1 indicate that the corresponding
frequency components are correlated. Consider two signals and their respective
power spectra.
The phase lag between the 35 Hz components is close to -90 degrees, and
the phase lag between the 165 Hz components is close to -60 degrees.
Finding Periodicities in a Signal
Consider a set of temperature measurements in an office building during the
winter season. Measurements were taken every 30 minutes for about 16.5 weeks.
With the temperatures in the low 70s, you need to remove the mean to
analyze small fluctuations in the signal. The xcov function removes the
mean of the signal before computing the cross-correlation. It returns the cross-
covariance. Limit the maximum lag to 50% of the signal to get a good estimate
of the cross-covariance.
59
60
61
62
Observe dominant and minor fluctuations in the auto-covariance. Dominant
and minor peaks appear equidistant. To verify if they are, compute and plot
the difference between the locations of subsequent peaks,
mean(cycle1) = 7
mean(cycle2) = 1
The minor peaks indicate 7 cycles/week and the dominant peaks indicate 1
cycle per week. This makes sense given that the data comes from a temperature-
controlled building on a 7 day calendar. The first 7-day cycle indicates that there
is a weekly cyclic behavior of the building temperature where temperatures lower
during the weekends and go back to normal during the week days. The 1-day
cycle behavior indicates that there is also a daily cyclic behavior - temperatures
lower during the night and increase during the day.
Viva
1. Purpose of resample()?
2. Define Power spectral density.
Code
63
%Measure Similarity between two Voice Signals
%S1. Comparing Signals with Different Sampling Rates
%S2. Finding a Signal in a Measurement
%S3. Measuring Delay Between Signals and Aligning Them
%S4. Comparing the Frequency Content of Signals
%S5. Finding Periodicities in a Signal
% Load data
load relatedsig.mat;
figure
ax(1) = subplot(311);
plot((0:numel(T1)1)/Fs1,T1,'k');
ylabel('Template 1');
grid on
ax(2) = subplot(312);
plot((0:numel(T2)1)/Fs2,T2,'r');
ylabel('Template 2');
grid on
ax(3) = subplot(313);
plot((0:numel(S)1)/Fs,S);
ylabel('Signal');
grid on
xlabel('Time (secs)');
linkaxes(ax(1:3),'x')
axis([0 1.61 4 4])
%%
% The first and the second subplot show the template signals from the
% database. The third subplot shows the signal which we want to search for
% in our database. Just by looking at the time series, the signal does not
% seem to match to any of the two templates. A closer inspection reveals
% that the signals actually have different lengths and sampling rates.
%%
% Different lengths prevent you from calculating the difference between two
% signals but this can easily be remedied by extracting the common part of
% signals. Furthermore, it is not always necessary to equalize lengths.
% Crosscorrelation can be performed between signals with different
64
% lengths, but it is essential to ensure that they have identical sampling
% rates. The safest way to do this is to resample the signal with a lower
% sampling rate. The | resample | function applies an antialiasing(lowpass)
% FIR filter to the signal during the resampling process.
[C1,lag1] = xcorr(T1,S);
[C2,lag2] = xcorr(T2,S);
figure
ax(1) = subplot(211);
plot(lag1/Fs,C1,'k');
ylabel('Amplitude');
grid on
title('Crosscorrelation between Template 1 and Signal')
ax(2) = subplot(212);
plot(lag2/Fs,C2,'r');
ylabel('Amplitude');
grid on
title('Crosscorrelation between Template 2 and Signal')
xlabel('Time(secs)');
axis(ax(1:2),[1.5 1.5 700 700 ])
%%
% The first subplot indicates that the signal and template 1 are less
% correlated while the high peak in the second subplot indicates that
% signal is present in the second template.
[,I] = max(abs(C2));
timeDiff = lag2(I)/Fs
%%
% The peak of the cross correlation implies that the signal is present in
% template T2 starting after 61 ms.
figure,
ax(1) = subplot(311);
plot(s1);
ylabel('s1');
grid on
ax(2) = subplot(312);
plot(s2,'k');
65
ylabel('s2');
grid on
ax(3) = subplot(313);
plot(s3,'r');
ylabel('s3');
grid on
xlabel('Samples')
linkaxes(ax,'xy')
%%
% The maximum value of the crosscorrelations between s1 and s2 and s1 and
% s3 indicate time leads/lags.
[C21,lag1] = xcorr(s2,s1);
[C31,lag2] = xcorr(s3,s1);
figure
subplot(211);
plot(lag1,C21/max(C21));
ylabel('C21');
grid on
title('CrossCorrelations')
subplot(212);
plot(lag2,C31/max(C31));
ylabel('C31');
grid on
xlabel('Samples')
%%
% t21 indicates that s2 lags s1 by 350 samples, and t31 indicates that s3
% leads s1 by 150 samples. This information can now used to align the 3
% signals.
s2 = [zeros(abs(t21),1);s2];
s3 = s3(t31:end);
figure
ax(1) = subplot(311);
plot(s1);
grid on;
title('s1');
axis tight
ax(2) = subplot(312);
plot(s2);
grid on;
title('s2');
axis tight
ax(3) = subplot(313);
plot(s3);
grid on;
title('s3');
axis tight
66
linkaxes(ax,'xy')
[P1,f1] = periodogram(sig1,[],[],Fs,'power');
[P2,f2] = periodogram(sig2,[],[],Fs,'power');
figure
t = (0:numel(sig1)1)/Fs;
subplot(221);
plot(t,sig1,'k');
ylabel('s1');
grid on
title('Time Series')
subplot(223);
plot(t,sig2);
ylabel('s2');
grid on
xlabel('Time (secs)')
subplot(222);
plot(f1,P1,'k');
ylabel('P1');
grid on;
axis tight
title('Power Spectrum')
subplot(224);
plot(f2,P2);
ylabel('P2');
grid on;
axis tight
xlabel('Frequency (Hz)')
%%
% The | mscohere | function calculates the spectral coherence between the two
% signals. It confirms that sig1 and sig2 have two correlated components
% around 35 Hz and 165 Hz. In frequencies where spectral coherence is high,
% the relative phase between the correlated components can be estimated
% with the cross spectrum phase.
[Cxy,f] = mscohere(sig1,sig2,[],[],[],Fs);
Pxy = cpsd(sig1,sig2,[],[],[],Fs);
phase = angle(Pxy)/pi*180;
[pks,locs] = findpeaks(Cxy,'MinPeakHeight',0.75);
figure
subplot(211);
plot(f,Cxy);
title('Coherence Estimate');
grid on;
67
hgca = gca;
hgca.XTick = f(locs);
hgca.YTick = .75;
axis([0 200 0 1])
subplot(212);
plot(f,phase);
title('Cross Spectrum Phase (deg)');
grid on;
hgca = gca;
hgca.XTick = f(locs);
hgca.YTick = round(phase(locs));
xlabel('Frequency (Hz)');
axis([0 200 180 180])
%%
% The phase lag between the 35 Hz components is close to 90 degrees, and
% the phase lag between the 165 Hz components is close to 60 degrees.
figure
plot(days,temp)
title('Temperature Data')
xlabel('Time (days)');
ylabel('Temperature (Fahrenheit)')
grid on
%%
% With the temperatures in the low 70s, you need to remove the mean to
% analyze small fluctuations in the signal. The | xcov | function removes the
% mean of the signal before computing the crosscorrelation. It returns the
% crosscovariance. Limit the maximum lag to 50% of the signal to get a
% good estimate of the crosscovariance.
maxlags = numel(temp)*0.5;
[xc,lag] = xcov(temp,maxlags);
[,df] = findpeaks(xc,'MinPeakDistance',5*2*24);
[,mf] = findpeaks(xc);
figure
plot(lag/(2*24),xc,'k',...
lag(df)/(2*24),xc(df),'kv','MarkerFaceColor','r')
grid on
xlim([15 15]);
xlabel('Time (days)')
title('Autocovariance')
%%
% Observe dominant and minor fluctuations in the autocovariance. Dominant
68
% and minor peaks appear equidistant. To verify if they are, compute and
% plot the difference between the locations of subsequent peaks.
cycle1 = diff(df)/(2*24);
cycle2 = diff(mf)/(2*24);
subplot(211);
plot(cycle1);
ylabel('Days');
grid on
title('Dominant peak distance')
subplot(212);
plot(cycle2,'r');
ylabel('Days');
grid on
title('Minor peak distance')
mean(cycle1)
mean(cycle2)
%%
% The minor peaks indicate 7 cycles/week and the dominant peaks indicate 1
% cycle per week. This makes sense given that the data comes from a
% temperaturecontrolled building on a 7 day calendar. The first 7day
% cycle indicates that there is a weekly cyclic behavior of the building
% temperature where temperatures lower during the weekends and go back to
% normal during the week days. The 1day cycle behavior indicates that
% there is also a daily cyclic behavior temperatures lower during the
% night and increase during the day.
displayEndOfDemoMessage(mfilename)
69
Experiment 9
Image Edge Feature Extraction Using Masks
Introduction
A technique of edge detection and line finding for linear feature extraction is
described. Edge detection is by convolution with small edge-like masks. The
importance of effective early processing of visual input for a complete image
understanding system is generally accepted. The early processing may consist
of a description of image discontinuities, usually in the form of edges and lines,
or segmentation into uniform regions. In this paper, we describe a technique for
extracting linear features in an image by a process of edge detection and line
linking and also of deriving higher-level descriptions from the extracted lines.
These techniques are intended to be general. Applications to road detection
and airport recognition tasks are described.
Edge detection in this technique starts by convolving a given image with
masks corresponding to ideal step edges in a selected number of directions. The
magnitude of the convolved output and the direction of the mask giving the
highest output at each pixel are recorded as edge data.
Objectives
1. Compare and contrast between various masks for edge detection - LPF,
HPF, Gradient, Gaussian, Sobel, Roberts, and Prewitt
2. Understand the advantages and disadvantages of each type of mask for
edge detection on images
Requirements
MATLAB, Wavelet Toolbox, Personal Computer
Methodology
1. Read a gray scale image. Find its resolution.
2. Generate Suitable masks for processing. Use LPF, HPF, Gradient, Gaus-
sian and Laplacian masks.
3. Use convolution in 2D to extract edge features. Save the features.
70
Observations
Comparison of Image Segmentation Operators Operators Comparative Study
Parameter Advantages Disadvantages
1. Sobel It produces thin edges. It does not offer detailed information.
Threshold It is simple. Better approximation to gradient magnitude. Sen-
sitivity to Noise. Not accurate in locating edges. Accuracy descends when
magnitude of the edges decreases.
2. Prewitt More sensitive to horizontal and vertical edges. Threshold De-
tection of edges and their orientations are high. Inaccurate. Size of the
coefficient and kernel filter is fixed and cannot be changed to a given image.
3. Roberts Works with binary images only. Does not detect edges when
a minimal change in gray scale value. Threshold It is simple and fast.
Detects thicker edges. Localization is not good.Weak response to genuine
edge.
Viva
1. What is a mask? What is its purpose?
2. What is the type of multiplication between a mask and image?
Code
clc;
close all;
clear all;
%% Lab Exp1 Image Edge Feature Extraction Using Masks
%% S1. Read a gray scale image. Find its resolution.
image=imread('image 01969.jpg');
image = double(image(:,:,1));
[r c] = size(image);
71
Figure 16: feature extraction with lpf
72
Figure 18: feature extraction with Laplacian hpf
73
Figure 20: feature extraction with filter [1, -1]
%% S2. Generate Suitable filter masks for processing. Use LPF, HPF, Gradient, Gaussian and Laplacian
LPF F = 1/9.*[100 100 100;100 100 100;100 100 100];
subplot(1,2,1)
imshow(image,[])
subplot(1,2,2)
imshow(LPF E,[]);
74
subplot(1,2,2)
imshow(LAP HPF E,[]);
gx = [1 1];
Gx = conv2(image,gx,'same');
gy = gx';
Gy = conv2(image,gy,'same');
G = sqrt(Gx.2+Gy.2)>0;
figure,subplot(1,2,1)
imshow(image,[])
subplot(1,2,2)
imshow(G,[]);
%% S4. Create a performance table for the masks and images chosen.
%% S5. Comment on the performance of the masks for different types of edge features.
%The percentage of pixels that were correctly detected
P1 = ((LPF E GT).2)/max(LPF E,GT); % USE this to do it for all filters
% Comparison of Image Segmentation Operators Operators Comparative Study Parameter Advantages Disadva
% 1. Sobel It produces thin edges. It does not offer detailed information.
% Threshold It is simple. Better approximation to gradient magnitude. Sensitivity to Noise.
% Not accurate in locating edges. Accuracy descends when magnitude of the edges decreases.
% 2. Prewitt More sensitive to horizontal and vertical edges.
% Threshold Detection of edges and their orientations are high.
% Inaccurate. Size of the coefficient and kernel filter is fixed and cannot be changed to a given ima
% 3. Roberts Works with binary images only. Does not detect edges when a minimal change in gray scale
% Threshold It is simple and fast. Detects thicker edges. Localization is not good.Weak response to g
75