Vous êtes sur la page 1sur 70

SIGNAL PROCESSING

LABMANUAL

Course code: 15 EC 2206


For
I Semester / III Year
of
B.Tech.
ECE

K L UNIVERSITY
VADDESWARAM, GUNTUR 522 502 (A.P.) INDIA
2017-18

1
Signal Processing Lab 15 EC 2206

List of Experiments

Exp. Name of the experiment Lab


No. Type
1 Generation of DT sequences and Manipulation IN Lab
on DT sequences
2 Frequency domain representation of DT IN Lab
sequences: DFT and FFT
3 Design and Implementation of Digital IIR Filters IN Lab

4 Spectral effects of Decimation and Interpolation IN Lab


of discrete sequences
5 Design the analysis/synthesis of two-channel IN Lab
orthogonal filter bank with filter length is N = 32,
and the lowpass passband edge frequency p =
0.43.
6 Signal Feature Extraction using Wavelet IN Lab
transform
7 Automatically Insert a watermark on an Image IN Lab

8 Measure Similarity between two Voice Signals IN Lab

9 Image Edge Feature Extraction Using Masks IN Lab

10 Image Feature Extraction using Wavelet IN Lab


transform

2
LAB Evaluation Pattern

Internal and External Lab Evaluation Process:


Evaluation
Weightage/ marks Date Duration (Hours) CO
Component

Lab Experiment Weightage (5%) 90 mts 5


Max Marks (5) 5
Weightage (5%) 90 mts 5
Project
Max Marks (5) 5
Weightage (5%) 90 mts 5
SE Lab Exam
Max Marks (5) 5
Weightage (5%) 90 mts 7.5
SE Project
Max Marks (5) 7.5

Experiment wise Evaluation:

Exp. Title Date Experiment Evaluation Process

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

S.No. Name of Faculty Chamber Consultation Room No.

1 Dr. P. Sasi Kiran C204

2 Dr. P V V Kishore Research Lab Library Building


7th Floor
3 Dr. D. S. Phani Kishore C323

4 M. Ashoka Chakravarthy C104

5 M. Venkateswara Rao Sixth Floor-ECE Staff Room

6 R Chelladurai C324

7 J L Prasanna C204

8 R. Selva Kumar Sixth Floor-ECE Staff Room

9 Ali Baig Mohammad C323

4
Experiment 1

Generation of DT sequences and Manipulation on DT sequences

AIM: a) To develop MATLAB scripts for the generation of DT sequences in the


range 10n20 and plot them.

(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)

x[n] {1, 2, 2.3, 0, 1, 3, 3.5, 2.1, 6, 0, 7}


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]

Equipments and Softwares needed:


1) PC
2) Windows XP Operating System
3) MATLAB 7.9 (R2013b)

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.

(a) The Singularity Functions:

The Unit Sample / Impulse Sequence: A discrete time (D.T)

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

(b) Discrete Time Sinusoidal Sequence: A discrete time (D.T.) sinusoidal


sequence is defined as
x[n] A cos(t ), n

(c) The Exponential Signals:

The Exponential signal is a sequence of the form


x[n] n for all n
If are real, then x[n] is real exponential DT sequence. Basically, if | | 1 , the
sequence grows exponentially with n, while if | | 1 , the sequence decaying
exponential as shown in the following figure.

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

(e) Time Scaling: Downsampling and UpSampling


Downsampling by a factor N: y1[n] = x[N*n]
Upsampling 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]);

% matlab program for folding a discrete time signal


clc; clear all; close all;
n=-3:1:4;
x=[-1,-2,-3,3,3,3,3,3];
y=fliplr(x);
m=-fliplr(n);
subplot(211);
stem(n,x);
title('input sequence x[n]');
xlabel('-->n');
ylabel('Amplitude');
subplot(212);
stem(m,y);
title('folded input sequence x[-n]');
xlabel('-->n');
ylabel('Amplitude');

% matlab function for shifting a discrete time signal


function [y,n] = sigshift(x,m,k)
y=x; n=m+k;
end

% matlab program for shifting a discrete time signal


clc; clear all; close all;
n=-3:1:4;
x=[-1,-2,-3,3,3,3,3,3];
k=-2;
m=n-k;
[y,n]=sigshift(x,m,k);
subplot(311);
stem(n,x); axis([-5 6 -3 3]); grid on;
title('input sequence x[n]');
xlabel('-->n');
ylabel('Amplitude');
subplot(312);
stem(m,y); axis([-5 6 -3 3]); grid on;
title('right shifted input sequence x[n-2]');
xlabel('-->n');
ylabel('Amplitude');
subplot(313);
k=2;
m=n-k;
[y2,n2]=sigshift(x,m,k);
stem(m,y2); axis([-5 6 -3 3]); grid on;
title('left shifted input sequence x[n+2]');

8
xlabel('-->n');
ylabel('Amplitude');

% matlab program for downsampling a discrete time signal


clc; clear all; close all;
n=-3:1:4;
x=[-1,-2,-3,3,3,3,3,3];
y=downsample(x,2);
m=downsample(n,2);
subplot(311);
stem(n,x); grid on;
title('input sequence x[n]');
xlabel('-->n');
ylabel('Amplitude');
subplot(312);
stem(m,y);
axis([-3 4 -3 3]); grid on;
title('downsampled input sequence x[2n]');
xlabel('-->n');
ylabel('Amplitude');
subplot(313); grid on;
[y1,n]=sigshift(y,m,1);
stem(n,y1); grid on;
axis([-3 4 -3 3]);
title('downsampled input sequence x[2n-1]');
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

exponential modulated sinusoidal sequence x[n]=[-1,2,-2.3,0,1,3,3.5,-2.1,6,0,7]


1

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

folded input sequence x[-n]


3

1
Amplitude

-1

-2

-3
-4 -3 -2 -1 0 1 2 3
-->n

input sequence x[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

input sequence x[n]


4

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.

Equipments and Softwares needed:


1) PC
2) Windows XP Operating System
3) MATLAB 7.9 (R2013b)

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.

An N-point DFT is expressed as an N-by-N matrix multiplication as X = Wx, where x


is the original input signal, and X is the DFT of the signal. The equation for N-point
DFT of a sequence x[n] is given by,

A circular convolution of two functions is defined in terms of the periodic extension


of one or both functions. Periodic extension means a new function is formed by

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;

% matlab program for circular convolution using cconv()

clc; clear all; close all;


x1=[1 2 3 4 5];
x2=[2 -1 1 -1];
yC=cconv(x1,x2,5);
subplot(221);stem(x1);
title('first sequence x1');
xlabel('time --->');
ylabel('amplitude -->');grid;
disp('First sequence x1 is');

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

% matlab program for circular convolution using DFT and IDFT

clc; clear all; close all;


x1=[1 2 3 4 5];
x2=[2,-1,1,-1];
N1=length(x1);
N2=length(x2);
N=max(N1,N2);
X1=fft(x1,N);
X2=fft(x2,N);
YC=X1.*X2;
yC=ifft(YC,N);
subplot(221);
stem(x1); grid on;
xlabel('---> time');
ylabel('---> amplitude');
title('First Input x1');
disp('First input is:');
x1
subplot(222);
stem(x2); grid on;
xlabel('---> time');
ylabel('---> amplitude');
title('Second input x2');
disp('Second input is:');
x2
subplot(2,2,[3,4]);
stem(yC); grid on;
xlabel('---> time');
ylabel('---> amplitude');
title('Circular Convolution of x1 and x2 using DFT');
disp('Circular Convolution using DFT and IDFT is');
yC

13
Outputs:
Enter the length of DFT: 8

x= 1 1 1 1 0 0 0 0

N-Point DFT of the given sequence is

X=

Columns 1 through 4

4.0000 1.0000 - 2.4142i 0 1.0000 - 0.4142i

Columns 5 through 8

0 1.0000 + 0.4142i 0 1.0000 + 2.4142i

Elapsed time is 5.032820 seconds.

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

Circular convolution of x1 and x2 using cconv() is

yC = -2.0000 4.0000 0.0000 6.0000 7.0000

first sequence x1 second sequence x2


5 2

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 --->

circular convolution of x1 and x2


8

4
amplitude -->

-2
1 1.5 2 2.5 3 3.5 4 4.5 5
time --->

Circular convolution using DFT and IDFT

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

yC = -2.0000 4.0000 0.0000 6.0000 7.0000

First Input x1 Second input x2


5 2

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

Circular Convolution of x1 and x2 using DFT


8

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.

Equipments and Softwares needed:


1) PC
2) Windows XP Operating System
3) MATLAB 7.9 (R2013b)

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

A desired frequency response is approximated by a transfer function expressed as a


ratio of polynomials. This type of transfer function yields an impulse response of
infinite duration. Therefore, the analog filters are commonly referred to as infinite
impulse response (IIR) filters The main classes of analog filters are
1.Butterworth Filter. 2.Chebyshev Filter.

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).

Butterworth filter tables


N=1 (s+1)
N=2 (s2+0.5s+1)
N=3 (s2+s+1) (s+1)
N=4 (s2+0.7653s+1) (s2+1.8647s+1)
N=5 (s+1) (s2+0.6180s+1) (s2+1.6180s+1)

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');

% Chebyshev (Type-I) 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,wn]=cheb1ord(wpn,wsn,rp,rs);

disp('The order and cut-off freq of the Chebyshev filter for


the given specs is:');
N
wn
c=input('enter choice of filter 1. LPF 2. HPF \n ');

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

[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 the desired Chebyshev(Type-I)
Filter');
subplot(212);
plot(w,phase);grid on;
ylabel('--> Phase in radians');
xlabel('--> Normalized frequency in Hz');
title('Phase Response of the desired Chebyshev(Type-I)
Filter');

FIR Filter Design


% Design a low-pass FIR filter, with cut-off frequency of 5
kHz, length 11
% using rectangular window. Assume the sampling frequency is
50 kHz.
% Find the filter coefficients, measure the magnitude and
phase
% responses and comment. Plot the magnitude and phase versus
real frequency f in Hz.

% Cut-off frequency given is 5kHz = 0.2 radians/sec


% rectangular window

clear all; close all; clc;

N=11;
Rw=boxcar(N);
b=fir1(10,0.2,Rw);
disp('window coefficient = ');disp(Rw')

[h,f]=freqz(b,1,512);% frequency response of the window


mag = 20*log10(abs(h)); %DB magnitude
an = angle(h);

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

Magnitude Response of the desired Butterworth IIR Filter


0

-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

enter choice of filter 1. LPF 2. HPF


2
Frequency response of Butterworth IIR HPF is:

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

Magnitude Response of the desired Butterworth IIR Filter


200
--> Magnitude in dB

-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

enter choice of filter 1. LPF 2. HPF


2
Filter coefficients of the desired Chebyshev High Pass IIR Filter are:
b=
0.0100 -0.0500 0.1000 -0.1000 0.0500 -0.0100
a=
1.0000 2.0057 2.6046 2.0186 0.9720 0.2324

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

Magnitude Response of the given FIR filter


0
Gain DB ----->

-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.

Equipments and Softwares needed:


1) PC
2) Windows XP Operating System
3) MATLAB 7.9 (R2013b)
Theory:
Decimation is the process of reducing the sampling frequency of a signal to a lower sampling
frequency that differs from the original frequency by an integer value. Decimation also is
known as down-sampling. The lowpass filtering associated with decimation removes high-
frequency content from the signal to accommodate the new sampling frequency.

Decimation is useful in applications in which the Nyquist frequency of a signal is much


higher than the highest frequency of the signal. Decimation filters help you remove the excess
bandwidth and reduce the sampling frequency of the signal. Decimation filters also help you
reduce the computational resources required for processing and storing the signal. During the
analog-to-digital (A/D) conversion process, decimation filters also can reduce the variance of
quantization noise in a signal and maintain the signal power, thus improving the signal-to-
noise ratio (SNR).

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 process of increasing the sampling rate is called interpolation. Interpolation is


upsampling followed by appropriate filtering. The output y(n) is obtained by interpolating
x(n) and is generally represented as:

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');

%Illustration of effect of decimation in the frequency domain


clc; clear all; close all;
F=input('Enter the highest normalized frequency component:');
D=input('Enter Decimation Factor:');
n=0:1:1024;
xd=F/2*sinc(F/2*(n-512)).^2; %input sequence
xd1=F/2*sinc(F/2*(n-512)*D).^2; %decimated input sequence
f=-2:1/512:2;

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

frequency response of input sequence


1
magnitude

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

frequency response of input sequence


1
magnitude

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

Illustration of effect of interpolation in the frequency domain

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

Result: Hence the spectral effects of decimation and interpolation on different


discrete time sequences are observed successfully.

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.

Equipments and Softwares needed:


1) PC
2) Windows XP Operating System
3) MATLAB 7.9 (R2013b)

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:

Figure 1: Impulse Response


0.5
h [n]

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-->

Figure 2: Pole-Zero plot of H (z)


0

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

-1.5 -1 -0.5 0 0.5 1 1.5


Real Part

Figure 4: Pole-Zero plot of G (z)


0

0.5
Imaginary Part

31
0

-0.5

-1

-1.5 -1 -0.5 0 0.5 1 1.5


Real Part

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

Figure 7: Two channel filter bank

-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

The waveform length, W at level L is defined as the following,


L 2
NX
2
WL = |dEL | (2)
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

3. Observe the features of any two different kinds of signals

Methodology
Algorithm Consider DT signal sampled at SF samples/second for seconds

1. Load the signal into workspace


2. Slice the signal using a sliding window of size WindowSize at WindInc
increments
3. Find the wavelet transform over each window

4. Compute 4 features at each level of the wavelet tree (Total=44 features)


5. Average the features over the windows

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

Observations and Results


While clear difference is visible in the graphs for features for each kind of signals,
the features with class look similar.

Viva

% GETMSWTFEAT Gets the Multiscale Wavelet Transform features, these


% include: Energy, Variance, Standard Deviation, and Waveform Length
% feat = getmswtfeat(x,winsize,wininc,SF)
%
% The signals in x are divided into multiple windows of size
% "winsize" and the windows are spaced "wininc" apart.

42
Figure 2: Uniformly distributed sequence-2

Figure 3: Electrocardiogram

43
Figure 4: Electrocardiogram

Figure 5: Uniformly distributed sequence-1 features

44
Figure 6: Uniformly distributed sequence-2 features

Figure 7: Electrocardiogram 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

function feat = getmswtfeat(x,winsize,wininc,SF)

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

datawin = ones(winsize,1); % data in the window


datasize = size(x,1); % length of signal in each column
Nsignals = size(x,2); % total number of signals

%% Chop the signal according to a sliding window approach


numwin = floor((datasize winsize)/wininc)+1;
% allocate memory
feat = zeros(winsize,numwin); % windowsize by the number of windows
st = 1;
en = winsize;
for i = 1:numwin
curwin = x(st:en,:).*repmat(datawin,1,Nsignals); % get a chunk of data within a window
feat(1:winsize,i) = detrend(curwin); % remove any linear trends in the signals

st = st + wininc; % next window coordinate


en = en + wininc;
end
%% Various options for J
% Note I put SF above in the inputs because you can use SF to determine the
% best decompisition level J, however for simplicity here I put it J=10;
J=10;% Number of decomposition levels which can also be set using
% or J=wmaxlev(winsize,'Sym5');
% or J=(log(SF/2)/log(2))1;
%% Multisignal onedimensional wavelet transform decomposition
dec = mdwtdec('col',feat,J,'db4');
% Proceed with Multisignal 1D decomposition energy distribution

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,:);

%% Predefine and allocate memory


tab ENER = zeros(numOfSIGs,level+1);
tab VAR = zeros(numOfSIGs,level+1);
% tab STD = zeros(numOfSIGs,level+1);
tab WL = zeros(numOfSIGs,level+1);
tab entropy = zeros(numOfSIGs,level+1);

%% Feature extraction section


st = 1;
for k=1:level+1
nbCFS = longs(k);
en = st+nbCFS1;
tab ENER(:,k) = mean(percentENER(:,st:en),2); % energy per waveform length
tab VAR(:,k) = var(percentENER(:,st:en),0,2); % variance of coefficients
% tab STD(:,k) = std(percentENER(:,st:en),[],2); % standard deviation
tab WL(:,k) = sum(abs(diff(percentENER(:,st:en)').2))'; % waveform length
percentENER(:,st:en) = percentENER(:,st:en)./repmat(sum(percentENER(:,st:en),2),1,...
size(percentENER(:,st:en),2));
tab entropy(:,k) = sum(percentENER(:,st:en).*log(percentENER(:,st:en)),2)./...
size(percentENER(:,st:en),2);
st = en + 1;
end
feat =([log1p([tab ENER tab VAR tab WL]) tab entropy]);
end

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

Figure 10: feat ecg abdomen1

50
Figure 11: watermarked feat ecg direct

Figure 12: turtle decomposed Level1 LL

51
Figure 13: decomposed L1 feat ecg direct

Figure 14: normxcorr2 featecgdirect turtle

52
Figure 15: normxcorr2 featecgdirectLL1 turtleLL1

Viva
1. Use of gray2rgb()?

2. Use of wfilters(), dwt2(), idwt2()?

Code

%Automatically Insert a watermark on an Image


%Step 1: Load image
%Step 2: Detect Cover Image and Watermark Image
%Step 3: Use DWT to Insert Watermark by adding a percentage of watermark wavelet coefficients to cove
%Step 4: Reverse the process the extract the watermark and the cover image
%Step 5: Compare original Cover Image and watermark images with extracted cover image and watermark i

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

% Convert the image to Double format for Wavelet Transform operation


I1=double(I);
[row,col]=size(I1);

% 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)

% DISCRETE WAVELET TRANSFORM


% DWT for original medical image
[F1,F2]= wfilters('db2', 'd');
[LL,LH,HL,HH] = dwt2(I1,'db2','d');
figure(2)
imshow(LL,'DisplayRange',[]), title('1 level dwt of cover image');

% DWT of the watermark iamge


[WF1,WF2]= wfilters('haar', 'd');
[L L,L H,H L,H H] = dwt2(Iw,'db2','d');
figure(3)
imshow(L L,'DisplayRange',[]), title('1 level dwt of watermark image');

% WATERMARKING MEDICAL IMAGE PROCESS


%computing level1 idwt2
[w h]=size(L L'); % Indicates the size of Key Image w=64 and h=64
[w1 h1]=size(LL'); % Indicates the size of original image w1=512,h1=512
a=1;
b=1;
W=zeros(size(LL')); % Create a empty target matrix of size 512
% What Exactly is happening here...?
for i=1:w:w1
for j=1:h:h1
W(i:a*w,j:b*h)=L L';
b=b+1;
end

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');

% Recoverey Process Watermarked Image


% Apply DWT for the watermarked image
[F11,F22]= wfilters('haar', 'd');
[a b c d]=dwt2(Watermarkedimage level1,'db2','d');

recovered image=aLL;

figure(5)
imshow(recovered image,[]);

% MEAN SQUARE ERROR FOR EMBEDDING


e=0; % Initialize the error variable to zero
img1=I1; % Original Image
img2=Watermarkedimage level1; % Watermarked image level1
[m n]=size(img1);

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.

3. what does xcorr() compute?


4. what is periodogram()?

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

%% Measuring Signal Similarities


% 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.

% Copyright 20122014 The MathWorks, Inc.

%% 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.

% 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.

[Fs1 Fs2 Fs]

%%
% 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.

[P1,Q1] = rat(Fs/Fs1); % Rational fraction approximation


[P2,Q2] = rat(Fs/Fs2); % Rational fraction approximation
T1 = resample(T1,P1,Q1); % Change sampling rate by rational factor
T2 = resample(T2,P2,Q2); % Change sampling rate by rational factor

%% Finding a Signal in a Measurement


% We can now crosscorrelate signal S to templates T1 and T2 with the
% | xcorr | function to determine if there is a match.

[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.

%% 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 same sampling rates and they are measuring signals
% caused by the same event.

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')

[,I1] = max(abs(C21)); % Find the index of the highest peak


[,I2] = max(abs(C31)); % Find the index of the highest peak
t21 = lag1(I1) % Time difference between the signals s2,s1
t31 = lag2(I2) % Time difference between the signals s3,s1

%%
% 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')

%% Comparing the Frequency Content of Signals


% A power spectrum displays the power present in each frequency. Spectral
% coherence identifies frequencydomain 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.

Fs = FsSig; % Sampling Rate

[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.

%% 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.

load officetemp.mat % Load Temperature Data


Fs = 1/(60*30); % Sample rate is 1 sample every 30 minutes
days = (0:length(temp)1)/(Fs*60*60*24);

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.

4. Create a performance table for the masks and images chosen.


5. Comment on the performance of the masks for different types of edge
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?

3. Explain False Positives?


4. Explain False Negatives?
5. Explain True Positives?

6. Explain True Negatives?

Code

%Image Edge Feature Extraction Using Masks


%S1. Read a gray scale image. Find its resolution.
%S2. Generate Suitable masks for processing. Use LPF, HPF, Gradient, Gaussian and Laplacian masks.
%S3. Use convolution in 2D to extract edge features. Save the features.
%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.

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

Figure 17: feature extraction with hpf

72
Figure 18: feature extraction with Laplacian hpf

Figure 19: feature extraction with Gaussian hpf

73
Figure 20: feature extraction with filter [1, -1]

GT = imread('image 01969 B&W.jpg');


GT = double(GT(:,:,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];

%% S3. Use convolution in 2D to extract edge features. Save the features.


LPF E = conv2(image,LPF F,'same')>0;
% image edge=filter2(filter,image);

subplot(1,2,1)
imshow(image,[])
subplot(1,2,2)
imshow(LPF E,[]);

HPF F = [1 1 1;1 8 1;1 1 1];


HPF E = conv2(image,HPF F,'same')>0;
figure,
subplot(1,2,1)
imshow(image,[])
subplot(1,2,2)
imshow(HPF E,[]);

LAP HPF F = [0 2 0;2 8 2;0 2 0];


LAP HPF E = conv2(image,LAP HPF F,'same')>0;
figure,
subplot(1,2,1)
imshow(image,[])

74
subplot(1,2,2)
imshow(LAP HPF E,[]);

GAU F = [1/16 1/8 1/16;1/8 1/4 1/8;1/16 1/8 1/16];


GAU HPF E = conv2(image,GAU F,'same')>0;
figure,
subplot(1,2,1)
imshow(image,[])
subplot(1,2,2)
imshow(GAU 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