0% found this document useful (0 votes)
16 views126 pages

24-25 DSP Lab Manual - Reference

The document is a Digital Signal Processing (DSP) Lab Manual for BTech (ECE) students at SRKR Engineering College, focusing on MATLAB simulations for DSP analysis and design. It outlines course objectives, outcomes, and a comprehensive list of experiments designed to teach students various DSP concepts, including signal generation, convolution, frequency domain analysis, filter design, and basic image processing. Each experiment includes specific aims, MATLAB programs, and tasks to reinforce practical understanding of DSP techniques.

Uploaded by

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

24-25 DSP Lab Manual - Reference

The document is a Digital Signal Processing (DSP) Lab Manual for BTech (ECE) students at SRKR Engineering College, focusing on MATLAB simulations for DSP analysis and design. It outlines course objectives, outcomes, and a comprehensive list of experiments designed to teach students various DSP concepts, including signal generation, convolution, frequency domain analysis, filter design, and basic image processing. Each experiment includes specific aims, MATLAB programs, and tasks to reinforce practical understanding of DSP techniques.

Uploaded by

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

Department of ECE, SRKR Engineering College

DSP Laboratory

BTech (ECE) 3/4 II-Semester DSP Lab (R-20)

Digital Signal Processing Lab Manual (MATLAB Simulation)

Course Objectives:
To make students learn & explore how MATLAB programming supports time-
domain and frequency-domain DSP analysis, design & operations by process
simulation
To equip students with MATLAB skills in the area of DSP to solve problems &
build small applications and projects
To prepare students ready for the Advanced DSP courses by reinforcing DSP
concepts with simulation experiments
Students should learn
To implement Convolution and Transform techniques on a given sequence
To analyse frequency response of Discrete Time Signals and Systems
To design different Digital filters
To implement basic Image Processing techniques

Focus will be on the Generation of basic DT signals, Transformations


&Operations on signals, Convolution, LTI systems analysis & simulation,
Frequency domain representations using DTFT, Computing DFT & FFT, Spectrum
analysis using FFT, IIR & FIR digital filter design, LTI digital filtering, Multi-rate
Decimation & Interpolation, Sampling, Reconstruction & aliasing, Basic Image
Processing tasks

Course Outcomes:
Students taking DSP Lab will be able to:
Simulate and Verify DSP concepts using MATLAB
Generate various deterministic & random signals
Apply transformations & Perform operations on DT signals, Compute & sketch
convolutions
Compute & Plot spectrum of non-periodic signals by computing: DTFT & DFT
Analyze LTI systems using: Impulse & Step response, Frequency response
Verify sampling theorem & understand the effects of under sampling
Apply FFT for Spectrum analysis of DT/CT signals
Design IIR & FIR digital filters to meet the Frequency response specifications
Implement LTI digital filtering
Implement Multi-Rate Up/Down sampling, Decimation & Interpolation operations
Implement basic Image Processing operations

1
Department of ECE, SRKR Engineering College
DSP Laboratory

Make use of MATLAB simulation tool for performing various operations on


discrete signals
Make use of MATLAB simulation tool to verify different DSP algorithms
Make use of MATLAB simulation tool to perform various operations on an Image

List of Experiments (R-20)

1. Verification of Sampling Theorem & Aliasing


2. Generation & Transformations of Discrete Time (DT) Signals
3. Sampling and Quantization of Speech & Image Signals
4. DT Linear Convolution & Circular Convolution
5. Frequency Domain Analysis of DT Signals & Systems using DTFT
6. Computation of DFT & FFT
7. DT-LTI System Simulation
8. Design and Verification of IIR Digital Filters
9. Design and Verification of FIR Digital Filters using Windows
10. Spectrum Analysis using Fast Fourier Transform (FFT)
11. LTI Digital Filtering of Signals
12. Simulation of Multi-Rate Up Sampling & Down Sampling Operations
13. Simulation of Interpolation & Decimation Operations
14. Generation & Detection of DTMF Signals
15. Image Enhancement: Image Properties & Display, Brightness & Contrast
Adjustment, Intensity Transformations, Histogram Equalization, Edge Detection
Operators
16. Image Filtering in Spatial & Frequency Domains
17. Image Restoration: De-Blurring & De-Noising
18. Image Transforms: Fourier & Discrete Cosine Transforms (DCT)
19. Computation of N-point DFT of a given sequence using DSP processor
20. Computation of FFT of a given sequence using DSP processor

2
Department of ECE, SRKR Engineering College
DSP Laboratory

List of Experiments & MATLAB Programs


Sno Expt. & Title Aim & Programs
1. Expt-1: Aim: To Generate & Manipulate the Basic
Discrete-Time (DT) Signal Discrete-Time Signals.
Generation &
Transformations P1: Sinusoidal, Complex exponential, Unit
impulse & Unit step sequences
P2: Random Signals & Gaussian Noise
P3: Implement Amplitude scaling, DC biasing,
Time shifting, Time reversal, Time scaling,
Addition & Multiplication Operations
P4: Perform Even/Odd decomposition

2. Expt-2: Aim: To compute Linear & Circular


Discrete-Time Linear & Convolutions in Time-domain
Circular Convolutions
P1: Linear convolution
P2: Discrete Circular Shift & Circular Reversal
P3: Circular convolution

3. Expt-3: Aim: To carry out the Frequency-domain


Frequency Domain Analysis Analysis of DT Signals & Systems by
of DT Signals & Systems computing DTFT
using DTFT
P1: DTFT of x(n)
P2: Frequency response of a LTI system,
Magnitude/Phase characteristics

4. Expt-4: Aim: To Implement and study DFT & FFT


Computation of DFT & FFT
P1: DFT and FFT of x(n) & x(t)
P2: Linear & Circular convolutions in
Frequency-domain using FFT
P3: DFT properties

5. Expt-5: Aim: To perform DT-LTI system simulations


DT-LTI System Simulation & compare with analytical results
To simulate & verify the response of a DT-LTI
system to different inputs: Impulse, Step &
Sinusoidal signals

P1: Impulse response & Step response


P2: Steady-state Sine response

3
Department of ECE, SRKR Engineering College
DSP Laboratory

6. Expt-6: Aim: To Compute & Plot the Spectrum of


Spectrum Analysis using DT/CT Signals using FFT & To compare with
Fast Fourier Transform Theoretical results
(FFT)
P1: Frequency analysis of a DT pulse signal
P2: Spectrum analysis of a CT tone signal &
aliasing

7. Expt-7: Aim: To design & verify IIR Low-pass Digital


Design and Verification of filters using Bilinear Transformation &
IIR Digital Filters Impulse Invariance Techniques

P1: Butterworth Low-pass Digital filter design


using Bilinear Transformation
P2: Chebyshev-I Low-pass IIR digital filter
design using Impulse Invariance Technique

8. Expt-8: Aim: To design & verify FIR Digital filters


Design and Verification of using Windows Technique
FIR Digital Filters using
Windows P1: FIR Digital low-pass Filter design using
different windows: Rectangular, Hamming &
Blackman
P2: FIR Digital low-pass Filter design using a
fixed window and different filter lengths

9. Expt-9: Aim: To design & implement the LTI digital


LTI Filtering of DT Signals filtering operation

P1: BPF
P2: LPF & HPF

10. Expt-10: Aim: To implement and study the multi-rate


Simulation of Multi-rate DSP operations: Up-sampling & Down-
DSP Operations: Up- sampling
sampling & Down-sampling
P1: Up-sampling & Down-sampling
P2: Up-sampling & Down-sampling in
Frequency Domain

11. Expt-11: Aim: To implement and study the multi-rate


Simulation of Multi-rate DSP operations: Decimation & Interpolation
DSP Operations:
Decimation & Interpolation P1: Decimation & Interpolation
P2: Fractional Rate Sampling Rate Alteration

4
Department of ECE, SRKR Engineering College
DSP Laboratory

End End

12. Expt-12: Aim: To verify Sampling Theorem & Observe


Sampling Theorem, Signal Aliasing
Reconstruction & Aliasing
P1: Sampling & Ideal Reconstruction of
Signals
P2: ZOH & FOH Reconstruction

13. Expt-13: Aim: To Implement & Visualize the basic


Digital Image Processing Image Processing operations
Experiments
P1: Image Enhancement: Image size &
display, Sampling and Quantization,
Brightness & Contrast Adjustment, Histogram
& Equalization, Edge Detection, Image
Filtering in Spatial/Frequency domains
P2: Image Restoration: Image De-Blurring &
De-Noising
P3: Image Transforms: Fourier, DCT

14.

15.

5
Department of ECE, SRKR Engineering College
DSP Laboratory

6
Department of ECE, SRKR Engineering College
DSP Laboratory

DSP Lab Model Report

2. Discrete-Time Linear & Circular Convolutions (Title)

Expt. No: 2 Date: 31-03-2023

Aim: To Compute & Plot Discrete Linear & Circular Convolutions in Time-domain

P1: Linear convolution

P2: Circular Shift & Circular Reversal

P3: Circular convolution

Software: MATLAB 7.5 (R2007b)

Write Problem/Task Statements:

Task-1: Problem-1 statement

Task-2: Problem-2 statement

P1: Program-1 statement

P2: Program-2 statement

Theory: to be written by student

MATLAB Programs: append code sheets

Results & Waveforms: to be written by students & attach printouts

Analysis, Code Description, Observations & Conclusions: to be written by


students in their own words individually

7
Department of ECE, SRKR Engineering College
DSP Laboratory

8
Department of ECE, SRKR Engineering College
DSP Laboratory

1. Discrete-Time (DT) Signal Generation & Transformations

Expt. No: 1 Date:

Aim: To Generate & Manipulate the Basic Discrete-Time Signals.

P1: Sinusoidal, Complex exponential, Unit impulse & Unit step sequences
P2: Random Signals & Gaussian Noise
P3: Implement Amplitude scaling, DC biasing, Time shifting, Time reversal, Time
scaling on signals
P4: Perform Addition & Multiplication, Even/Odd decomposition on signals

Software: MATLAB 7.5 (R2007b)

9
Department of ECE, SRKR Engineering College
DSP Laboratory

MATLAB Programs:

Expt-1: Discrete-Time (DT) Signal Generation & Manipulation


Aim: To generate & plot various discrete-time (DT) sequences and
signals

Expt-1: Generation of DT Sequences and Signals


Generation of Impulse, Step & Sine signals

Expt-1.1A: DT Unit impulse function or delta sequence, delta(n)

deln = @(n) (n == 0); % use function handle to define a fun


n = -4:10; % time range
x1 = deln(n); % create unit impulse signal
x2 = 2*deln(n+2)+deln(n)-deln(n-4); % delayed impulse sequence

% Plots
figure, subplot(211), stem(n,x1,'LineWidth',2);
axis([min(n)-1 max(n)+1 min(x1)-0.5 max(x1)+0.5]);grid;
title('Signal, \delta(n)','fontsize',12,'fontweight','b');

subplot(212), stem(n,x2,'LineWidth',2);
xlabel('time, n','fontsize',12,'fontweight','b');
axis([min(n)-1 max(n)+1 min(x2)-0.5 max(x2)+0.5]);grid;
title('x(n) = 2\delta(n-2)+\delta(n)-\delta(n-4)','fontsize',12,'fontweight','b');

Expt-1.1B: DT Unit step function or step sequence, u(n)

un = @(n) (n >= 0); % use function handle to define fun


n = -5:20; % time range
x1 = un(n); % create unit step signal
x2 = un(n-4); % delayed step

% Plots
figure, subplot(211), stem(n,x1,'LineWidth',2);
title('Signal, u(n)','fontsize',12,'fontweight','b');
axis([min(n)-1 max(n)+1 min(x1)-0.5 max(x1)+0.5]); grid;
subplot(212), stem(n,x2,'LineWidth',2);
xlabel('time, n','fontsize',12,'fontweight','b');
title('x(n) = u(n-4)','fontsize',12,'fontweight','b');
axis([min(n)-1 max(n)+1 min(x1)-0.5 max(x1)+0.5]); grid;

Expt-1.1C: Generation of DT Sequences and Signals

% Aim: To generate & plot various DT sequences and signals


% Generation of Impulse, Step, Complex exponential& Sine signals

10
Department of ECE, SRKR Engineering College
DSP Laboratory

% clc; clear; close all;


% x(n) = 2*delta(n+2) - delta(n-4), -4<=n<=10
del = @(n) (n==0); % define delta
u = @(n) (n>=0); % define unit step
n = [-4:10]; % define time
x1 = 2*del(n+2)+0*del(n)+0*del(n-1)+0*del(n-2)-del(n-4); % define x1(n)
x2 = u(n)-u(n-5); % define x2(n)
x3 = (2*(0.7).^n).*(u(n+2)-u(n-8)); % define x3(n)

figure,
subplot(2,2,1); stem(n,x1,'LineWidth',2);
title('x(n) = 2\delta(n+2) - \delta(n-4)'); grid;
axis([-2+min(n),max(n)+2,min(x1)-1,max(x1)+1]);
subplot(2,2,2); stem(n,x2,'LineWidth',2);
title('x(n) = u(n)-u(n-5)'); grid;
axis([-2+min(n),max(n)+2,min(x1)-1,max(x1)+1]);
subplot(2,2,3); stem(n,x3,'LineWidth',2);
legend('x(n) = 2(0.7)^n');
title('Exponential seq');grid;xlabel('time, n');
axis([-2+min(n),max(n)+2,min(x3)-1,max(x3)+1]);
% plot x(n) = sin(0.2*pi*n) 0<=n<=30
n2 = 0:30; x4 = 1*sin(0.2*pi*n2);
subplot(2,2,4); stem(n2,x4);
title('DT sine, x(n) = sin(0.2*pi*n)');
xlabel('time, n'); % axis([n2(1),n2(end),-0.2,1.2])

x5 = (2*(0.9).^n2).*sin(0.2*pi*n2); % define x5(n)


x6 = (2*(1.1).^n2).*sin(0.2*pi*n2); % define x6(n)
figure; subplot(211);
stem(n2,x5,'LineWidth',2); grid; legend('a = 0.9');
title('DT complex exponentials, x(n) = a^n sin(0.2*pi*n)');
subplot(212);stem(n2,x6,'LineWidth',2);grid;legend('a = 1.1');
axis([-2+min(n2),max(n2)+2,min(x6)-1,max(x6)+1]); xlabel('n');
xlabel('Time index, n'); % axis([n2(1),n2(end),-0.2,1.2])

Expt-1.1D: Generation of DT Random Sequences and Signals

% Aim: To generate zero-mean Gaussian noise & Produce a noisy sine-wave


with SNR = 20 dB

% clc; clear; close all;


f = 2; A = 2; noisedB = 10; % set parameters
sigpower = A^2/2; % signal power
t = [0:1/(100*f):4/f]; % define time-axis

11
Department of ECE, SRKR Engineering College
DSP Laboratory

x = A*cos(2*pi*f*t); % signal
noisevar = sigpower/(10^(noisedB/10)); % compute noise variance or power
n = sqrt(noisevar)*randn(1,10*length(t)); % generate Gaussian noise
y = x + n(1:10:length(n)); % add noise

% plots
subplot(2,2,1); plot(0:length(n)-1,n);
title('Gaussian noise samples'); grid; xlim([0 4010]);
subplot(2,2,2); hist(n,50);
title('Noise pdf'); grid; % check density & plot
subplot(2,2,3); plot(t,x); xlabel('t in sec.');
title('Sinewave'); grid;
subplot(2,2,4); plot(t,y);
xlabel('t in sec.'); title('Sine + noise');grid;
% plot(t,y,'y-',t,y,'go')
% xlabel('time, n','fontsize',12,'fontweight','b');
% title('Signal, x(n) = e^{-0.5t} sin(5t)')

Expt-1.2A: Generate & Manipulate a DT Signal:

% To Perform Operations on Signals


% Aim: Given signal x(n), Determine and plot the following sequences:
% y(n) = x(2*n-4);
% list
% n = [-3:3]; x = [0,1,2,3,2,1,0]; stem(n,x);
% deln = @(n) (n == 0); % use function handle
% n = -4:10; % time range
% clc; clear; close all;

deln = @(n) (n == 0); % define delta sig using function_handle


x = @(n) 0*deln(n+3)+1*deln(n+2)+2*deln(n+1)+3*deln(n) + ...
2*deln(n-1)+1*deln(n-2)+0*deln(n-3); % sig
% x = @(n) (n >= -2)&(n <= 2);
u = @(n) (n >= 0); % define unit step using function_handle
n = -20:10; % discrete-time
% x = n.*u(-n+3);
% x = u(n+2)-u(n-3);
% x = u(n);
% x = @(n) n.*u(n+3); % define fn
x1 = x(n); % form sig
A = 0; B = 1; % assign, A = DC level, B = gain
a = -2; b = 2; % assign, a = time scale/reversal, b = time shift
x2 = A + B*x(a*n+b); % transform x(n)
% y = conv(x,x);
% Plots

12
Department of ECE, SRKR Engineering College
DSP Laboratory

figure, subplot(211); stem(n,x1,'LineWidth',2);grid;


title('Signal, x(n)','Color','b','fontsize',12);
axis([-2+min(n),max(n)+2,min(x1)-1,max(x1)+1]);
subplot(212); stem(n,x2,'LineWidth',2);grid;
axis([-2+min(n),max(n)+2,min(x2)-1,max(x2)+1]);
% title('y(n) = x(a*n + b)','fontsize',12,'fontweight','b');
title(['y(n) = x(a*n + b), a = ',int2str(a),', b = ',int2str(b)],...
'Color','r','fontsize',12);
xlabel('time, n','fontsize',12,'fontweight','b');
% title('Signal, x(n) = e^{-0.5t} sin(5t)');

Expt-1.2B: Addition & Multiplication of Signals

% function [y3,y4,n] = sigaddmult(x1,n1,x2,n2)


% implements y3(n) = x1(n1) + x2(n2)
% implements y4(n) = x1(n1) * x2(n2)
% -----------------------------
% [y3,y4,n] = sigaddmult(x1,n1,x2,n2)
% y3 = sum sequence over n, which includes n1 and n2
% y4 = product sequence over n, which includes n1 and n2
% x1 = first sequence over n1
% x2 = second sequence over n2 (n2 can be different from n1)
%
x1 = [1,2,3,4,5,6,7]; % signal x1
n1 = [-2:4]; % x1 time
x2 = [8,9,7,6,5,4]; % signal x2
n2 = [3:8]; % x2 time
% n1 = 0:length(x1)-1; % x1 causal time
% n2 = 0:length(x2)-1; % x2 causal time

n = min(min(n1),min(n2)):max(max(n1),max(n2)); % duration of y1(n)


y1 = zeros(1,length(n)); y2 = y1; % initialization
y1((n>=min(n1))&(n<=max(n1)))= x1; % x1 with duration of y1
y2((n>=min(n2))&(n<=max(n2)))= x2; % x2 with duration of y1
y3 = y1 + y2; % sequence addition
y4 = y1 .* y2; % sequence multiplication

% Plots
figure,
subplot(2,1,1); stem(n1,x1,'LineWidth',2);
title('x_1(n)','FontSize',12,'Fontweight','b');grid;
subplot(2,1,2); stem(n2,x2,'LineWidth',2);
title('x_2(n)','FontSize',12,'Fontweight','b');grid;
xlabel('time, n','fontsize',12,'fontweight','b');

13
Department of ECE, SRKR Engineering College
DSP Laboratory

figure; % common time-axis


subplot(2,2,1); stem(n,y1,'LineWidth',2);
title('x_1(n), common time-axis','FontSize',12);grid;
subplot(2,2,2); stem(n,y2,'LineWidth',2);
title('x_2(n)','FontSize',12);grid;
subplot(2,2,3); stem(n,y3,'LineWidth',2);
title('y_3(n) = x_1(n) + x_2(n)','FontSize',12);grid;
xlabel('time, n','fontsize',12,'fontweight','b');
subplot(2,2,4); stem(n,y4,'LineWidth',2);
title('y_4(n) = x_1(n) * x_2(n)','FontSize',12);grid;
xlabel('time, n','fontsize',12,'fontweight','b');

Expt-1.2C: Even-Odd Decomposition of DT Real Signals

% Aim: To split real signal x(n) into Even & Odd parts
% Even-Odd Synthesis of x(n)
% function [xe,xo,m] = evenodd(x,n)
% [xe,xo,m] = evenodd(x,n); % split into even/odd parts
% x(n) = u(n)-u(n-10); % real sig, neither even nor odd
% n = [0:10]; % discrete time
% x = stepseq(0,0,10)-stepseq(10,0,10); % sequence

% clc; clear; close all;


% x(n) = 2*delta(n+2) - delta(n-4), -4<=n<=10
del = @(n) (n==0); % define delta
u = @(n) (n>=0); % define unit step
n = [-4:10]; % define time

% x1 = 2*del(n+2)+0*del(n)+0*del(n-1)+0*del(n-2)-del(n-4); % define x1(n)


% x2 = u(n)-u(n-5); % define x2(n)
% x3 = (2*(0.7).^n).*(u(n+2)-u(n-8)); % define x3(n)
% x = [1 2 3 4 5 6]; % sig
% n = -2:3; % discrete time

x = u(n)-u(n-10); % define x(n)

% split into even/odd parts


% check for real signal or not
if any(imag(x) ~= 0)
error('x is not a real sequence')
end
m = -fliplr(n); % time reversal
m1 = min([m,n]); m2 = max([m,n]);
m = m1:m2; % common time axis

14
Department of ECE, SRKR Engineering College
DSP Laboratory

nm = n(1)-m(1); n1 = 1:length(n);
x1 = zeros(1,length(m)); % align sig
x1(n1+nm) = x; % x = x1; % copy
xe = 0.5*(x1 + fliplr(x1)); % even part
xo = 0.5*(x1 - fliplr(x1)); % odd part
xs = xe + xo; % synthesis

% Plots
% subplot(1,1,1);
figure(); % new figure
subplot(2,2,1); stem(n,x,'LineWidth',2);
title('Rectangular pulse, x(n)');
% axis([-10,10,-0.1,1.2]);
subplot(2,2,2); stem(m,xe,'LineWidth',2);
title('Even part, x_e(m)');
% axis([-10,10,-0.1,1.2]);
subplot(2,2,3); stem(m,xo,'LineWidth',2);
title('Odd part, x_o(m)');
xlabel('m','fontsize',12,'fontweight','b');
% axis([-10,10,-0.6,0.6]);
subplot(2,2,4); stem(m,xe+xo,'LineWidth',2);
title('Even + Odd, x_e(m)+x_o(m)');
xlabel('m','fontsize',12,'fontweight','b');
% axis([-10,10,-0.1,1.2]);

15
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Waveforms:

Fig. 1.1 P1.1A: Unit impulse sequence & delayed version

Fig. 1.2 P1.1B: Unit step sequence & delayed version

16
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 1.3 P1.1C: Various DT signals

Fig. 1.4 P1.1C: DT Complex exponential signals

17
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 1.5 P1.1D: Gaussian noise, PDF & Noisy sine signal

Fig. 1.6 P1.2A: Operations on a DT signal

18
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 1.7 P1.2B: Two signals for Arithmetic Operations

Fig. 1.8 P1.2B: Addition & Multiplication of Signals

19
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 1.9 P1.2C: Even-Odd decomposition of x(n)

20
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

21
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

22
Department of ECE, SRKR Engineering College
DSP Laboratory

2. Discrete-Time Linear & Circular Convolutions

Expt. No: 2 Date:

Aim: To Evaluate & Plot the Linear & Circular Convolutions of Discrete-Time
Signals in Time-Domain.

P1: Linear convolution


P2: Discrete Circular Shift & Circular Reversal
P3: Circular convolution

Software: MATLAB 7.5 (R2007b)

23
Department of ECE, SRKR Engineering College
DSP Laboratory

MATLAB Programs:

Expt-2: Linear Convolution of Signals: Causal finite sequences

Expt-2: Discrete Linear Convolution & Circular Convolution of Signals in Time-


Domain
Aim: To compute linear & circular convolutions in time-domain

Expt-2.1: DT Linear Convolution in Time-domain: Matrix method

% Aim: Compute & Plot Discrete Linear Convolution

x = [1 2 3 4]; % sig
h = [5,6,7];
% h = input('Enter h vector using [] ');
% x = [1,2,2,1]; h = [1,2,3];
Nx = length(x); Nh = length(h); % sig lengths
Ny = Nx+Nh-1; % conv length

H = zeros(Ny,Nx); % fill or form H matrix


for i = 1:Nx
H(i:i+Nh-1,i) = h;
end
y = H*x'; % convolution by matrix-vec mult

% plots
nx = 0:Nx-1; % causal time of x
nh = 0:Nh-1; % time of h
ny = 0:Ny-1; % time of y
figure, subplot(2,2,1); stem(nx,x,'LineWidth',2);
title(['x(n), Nx = ',int2str(Nx)]);
axis([min(nx)-1,max(nx)+1,min(x)-1,max(x)+1]);
subplot(2,2,2); stem(nh,h,'LineWidth',2);
title(['h(n), Nh = ',int2str(Nh)]);
axis([min(nh)-1,max(nh)+1,min(h)-1,max(h)+1]);
subplot(2,2,[3,4]); stem(ny,y,'LineWidth',2);
% axis([min(ny)-1,max(ny)+1,min(y)-1,max(y)+1]);
xlim([min(ny)-1,max(ny)+1]); xlabel('Time, n'); grid;
title(['Linear causal convolution, y(n), Ny = ',int2str(Ny)],'fontsize',12);

Expt-2.2: Circular Shift & Circular Reversal with period = N


% Aim: Compute & Plot Discrete Circular Shift & Circular Reversal

x = [2,3,4,5]; % sig
% x = [6,7,8,9,0]; % sig

24
Department of ECE, SRKR Engineering College
DSP Laboratory

N = 5; % period
m = 1; % shift, + (right), - (left)

xp = [x zeros(1,N-length(x))]; % append zeros if necessary


xr = [xp,xp,xp]; % repeat x 3-times
xcs = xr(N+1-m:2*N-m); % circular shift
xcr = [xp(1),xp(end:-1:2)]; % circular reversal

% Plots
Nx = length(x); % sig length
nx = 0:Nx-1; % causal time of x
nxp = 0:N-1; % time of zero-padded sig over one period
figure, subplot(2,2,1); stem(nx,x,'LineWidth',2);
title('x(n)'); axis([min(nx)-1,max(nx)+1,min(x)-1,max(x)+1]);
subplot(2,2,2); stem(nxp,xp,'LineWidth',2);
title(['xp(n), period = ',int2str(N)]);
axis([min(nxp)-1,max(nxp)+1,min(xp)-1,max(xp)+1]);

subplot(2,2,3); stem(nxp,xcs,'LineWidth',2);
axis([min(nxp)-1,max(nxp)+1,min(xcs)-1,max(xcs)+1]);
title('Circular shift'); xlabel('Time, n'); grid;

subplot(2,2,4); stem(nxp,xcr,'LineWidth',2);
axis([min(nxp)-1,max(nxp)+1,min(xcr)-1,max(xcr)+1]);
title('Circular reversal'); xlabel('Time, n'); grid;

Expt-2.3: DT Circular/Periodic Convolution in Time-domain - Matrix


method
% Aim: Compute & Plot Discrete Circular Convolution

x = [1 2 3 4]; % sig
h = [5,6,7];
% x = [1,2,2,1]; h = [1,2,3,0];
N = 5; % period

Nx = length(x); Nh = length(h);
nx = 0:Nx-1; nh = 0:Nh-1; % time of x,h
xp = [x zeros(1,N-Nx)]; % append zeros if necessary
hp = [h zeros(1,N-Nh)];
hpr = [hp hp]; % repeat hp 2-times

H = zeros(N,N); % fill or form H matrix


for i = 0:N-1
H(:,i+1) = hpr(N+1-i:2*N-i);
end

25
Department of ECE, SRKR Engineering College
DSP Laboratory

yp = H*xp'; % circular convolution by matrix-vec mult

% plots
n = 0:N-1; % time of xp,hp,yp
figure, subplot(2,2,1); stem(n,xp,'LineWidth',2);
title('xp(n)'); axis([min(n)-1,max(n)+1,min(xp)-1,max(xp)+1]);
subplot(2,2,2); stem(n,hp,'LineWidth',2);
title('hp(n)'); axis([min(n)-1,max(n)+1,min(hp)-1,max(hp)+1]);
subplot(2,2,[3,4]); stem(n,yp,'LineWidth',2);
% axis([min(n)-1,max(n)+1,min(yp)-1,max(yp)+1]);
xlim([min(n)-1,max(n)+1]); xlabel('Time, n'); grid;
title(['Periodic convolution, yp(n), period = ',int2str(N)],'fontsize',12);

26
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Waveforms:

Fig. 2.1 P2.1: DT Convolution: Causal finite sequences

Fig. 2.2 P2.2: Circular Shift & Circular Reversal of a DT signal

27
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 2.3 P2.3: Circular or Periodic Convolution of DT signals

28
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

29
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

30
Department of ECE, SRKR Engineering College
DSP Laboratory

3. Frequency Domain Analysis of DT Signals & Systems using DTFT

Expt. No: 3 Date:

Aim: To carry out the Frequency-domain Analysis of DT Signals & Systems by


computing DTFT.

To obtain the Spectrum of DT Non-periodic signals using DTFT and to study


Magnitude & Phase characteristics of a LTI system by obtaining its Frequency
response

P1: Compute& Plot DTFT of x(n): Magnitude & Phase

P2: Obtain & plot the Frequency Response of a DT-LTI System: Magnitude/Phase
characteristics

Software: MATLAB 7.5 (R2007b)

31
Department of ECE, SRKR Engineering College
DSP Laboratory

MATLAB Programs:

Expt-3: Frequency Domain Analysis of DT Signals & Systems using DTFT

Aim: To carry out the frequency-domain analysis of DT signals & systems by


computing DTFT
Aim: (1) Compute & plot DTFT, (2) Obtain & plot the Freq response of a DTLTI
system
P1: Compute & Plot DTFT of x(n)
P2: Obtain Frequency Response of DT System

Expt-3.1: Frequency Domain Analysis of DT Signals & Systems using


DTFT

% Aim: To Obtain the Spectrum of DT Non-Periodic Signals using DTFT.


% help signal % Signal Processing Toolbox functions list
% freqz or fft can also be used
% DTFT of finite duration seq x(n)
% DTFT numerical computation using vector-matrix product
% compute/plot DTFT, observe DTFT is periodic

n = -1:3; % time index n, row vector


x = 1:5; % sequence x(n)
% n = 0:20; x = (0.5).^n;
k = -500*3:500*3; % frequency index k, row vecor
% define freq spacing = pi/500, [0,pi] axis divided into 501 points
w = (pi/500)*k; % freq grid,
N = length(x); L = length(k);
nk = n'*k; % creates a N by L matrix of nk values

X = x * (exp(-j*pi/500)).^(nk); % Compute DTFT using matrix-vector product


magX = abs(X); angX = angle(X); % magnitude & phase
realX = real(X); imagX = imag(X); % real & img parts

% DTFT plots
figure, subplot(2,2,1); plot(w/pi,magX,'LineWidth',2);
title('DTFT Magnitude'); grid;
subplot(2,2,3); plot(w/pi,angX,'LineWidth',2); grid
xlabel('Frequency in pi units'); title('DTFT Angle, Radians');
subplot(2,2,2); plot(w/pi,realX,'LineWidth',2); grid
title('Real Part');
subplot(2,2,4); plot(w/pi,imagX,'LineWidth',2); grid
xlabel('Frequency in pi units'); title('Imaginary Part');

32
Department of ECE, SRKR Engineering College
DSP Laboratory

Expt-3.2: Frequency response of a DTLTI system

% Aim: To get the frequency response of a DT-LTI system

% use DTFT, freqz, fvtool commands


% help freqz
% H(z) = B(z)/A(z), % DT TF evaluation
% TF = b/a; % define transfer function as vectors b,a

% b = [0,1,3,2]; a = [1,0 -1]; freqz(b,a) % define LTI system transfer function


% w = [0:pi/100:pi]; % [H,w] = freqz(b,a,w);

b = [0.0000,0.0054,0.0181,0.0040]; % define digital TF


a = [1.0000,-3.0591,3.8323,-2.2919,0.5495]; % Chebyshev LP filter
% b = [0.0181, 0.0543, 0.0543, 0.0181]; % num coeff vector
% a = [1.0000, -1.7600, 1.1829, -0.2781]; % den coeff vector
% b = [0.5,1,0.5]; a = [1]; % tf

% Frequency response graphs


figure, freqz(b,a) % get freq response magnitude/phase
% FVTOOL Filter Visualization GUI Tool (FVTool).
fvtool(b,a) % get impulse/step/freq response

Expt-3.3: Frequency Response of DT-LTI systems

% Aim: To get the frequency response of a DT-LTI system

% help freqz
% H(z) = B(z)/A(z), % DT TF evaluation
% TF = b/a; % define transfer function as vectors b,a
% Digital Butterworth LP filter, retain digits
b = [0.0181, 0.0543, 0.0543, 0.0181]; % num coeff vector
a = [1.0000, -1.7600, 1.1829, -0.2781]; % den coeff vector

% figure,freqz(b,a) % plot freq response directly


% w = linspace(-pi*0,pi,500+1); % linear freq scale: (-pi,pi)
% H = freqz(b,a,w); % compute freq res at w
[H,w] = freqz(b,a); % compute freq res
magH = abs(H); magHdB = 20*log10(magH); % mag in dB
angH = unwrap(angle(H))*180/pi; % phase in deg

% Plots
figure,
% subplot(2,1,1); plot(w/pi,magH,'LineWidth',2);grid; % axis([0,1,0,1])
subplot(2,1,1); plot(w/pi,magHdB,'LineWidth',2); grid;

33
Department of ECE, SRKR Engineering College
DSP Laboratory

ylim([-90 0]); xlim([0 1]);


title('Magnitude Response, |H(e^{jw})|');
subplot(2,1,2); plot(w/pi,angH,'LineWidth',2); grid
xlabel('Frequency in pi units');
title('Phase Response, \angleH(e^{jw}) in deg');

34
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Waveforms:

Fig. 3.1 P3.1: Discrete-Time Fourier Transform (DTFT) of x(n)

Fig. 3.2 P3.2: Frequency response Magnitude & Phase of a DT-LTI


system using DTFT (Chebyshev LP Filter)

35
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 3.3 P3.2: Frequency response of a DT-LTI system


(Chebyshev LP Filter) using fvtool GUI

Fig. 3.4 P3.3: Frequency response Magnitude & Phase of a DT-LTI


system (Butterworth LP Filter) using freqz

36
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

37
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

38
Department of ECE, SRKR Engineering College
DSP Laboratory

4. Computation of DFT & FFT

Expt. No: 4 Date:

Aim: To compute DFT & FFT, Linear & Circular convolutions using FFT and to
verify DFT properties

P1: Compute& Plot DFT/FFT of finite x(n)

P2: Compute convolutions using FFT

P3: Verify DFT Properties

Software: MATLAB 7.5 (R2007b)

39
Department of ECE, SRKR Engineering College
DSP Laboratory

MATLAB Programs:

Expt-4: Implementation of DFT & FFT

Aim: To compute DFT & FFT, To compute convolutions using FFT, To verify DFT
properties

Expt-4.1A: DFT

% function [Xk] = dft(xn,N)


% Computes Discrete Fourier Transform
% -----------------------------------
% [Xk] = dft(xn,N)
% Xk = DFT coeff. array over 0 <= k <= N-1
% xn = N-point finite-duration sequence
% N = Length of DFT
%

xn = [0:7]; N = 8;
n = 0:N-1; % time index n, row vector
k = 0:N-1; % frequency index k, row vecor
WN = exp(-j*2*pi/N); % Wn factor
nk = n'*k; % creates a N by N matrix of nk values
WNnk = WN .^ nk; % DFT matrix
Xk = xn * WNnk; % row vector for DFT coefficients

Expt-4.1B: IDFT

% function [xn] = idft(Xk,N)


% Computes Inverse Discrete Transform
% -----------------------------------
% [xn] = idft(Xk,N)
% xn = N-point sequence over 0 <= n <= N-1
% Xk = DFT coeff. array over 0 <= k <= N-1
% N = length of DFT

Xk = [0:7]; N = 8;
n = 0:N-1; % row vector for n
k = 0:N-1; % row vecor for k
WN = exp(-j*2*pi/N); % Wn factor
nk = n'*k; % creates a N by N matrix of nk values
WNnk = WN .^ (-nk); % IDFT matrix
xn = (Xk * WNnk)/N; % row vector for IDFT values

40
Department of ECE, SRKR Engineering College
DSP Laboratory

Lab-4.2A: DFT of x(n) = delta(n), dc sig, u(n), cos(wn)

x1 = [1,0,0,0,0,0,0,0]; % delta(n)
X1 = fft(x1);

x2 = [1,1,1,1,1,1,1,1]; % dc
X2 = fft(x2);

% zero-centered fft plots


N = 2^5; x3 = [zeros(1,N/2),ones(1,N/2)]; % u(n) or sq. wave pulse
% X3 = fft(x3); figure, subplot(211), stem(0:length(x3)-1,abs(X3),
'LineWidth',2);
X3 = fft(x3,2^8);
figure, subplot(211),
stem([-length(X3)/2:length(X3)/2-1],abs(fftshift(X3)),'LineWidth',2);
title('DFT of Sq. wave'); grid;
N = 2^5; k = 3; w = k*(2*pi/N); % freq, k = 0,1,2,...,N-1
n = 0:N-1;
x4 = cos(w*n); % cos sig
% X4 = fft(x4); subplot(212), stem(0:length(x4)-1,abs(X4),'LineWidth',2);
X4 = fft(x4); subplot(212),
stem([-length(X4)/2:length(X4)/2-1],abs(fftshift(X4)),'LineWidth',2)
xlabel('Freq index, k'); title('DFT of cos(wn)'); grid;

Lab-4.2B: Apply DFT to a CT signal, x(t) = cos(wt)

Fs = 8000; T = 1/Fs; % sampling freq


N = 2^10;
fftres = Fs/N;
n = 0:N-1; % samples
k = n;
t = n*T; % sampling grid
f = 1000+125*0; % analog freq
k1 = f/fftres; k2 = N-k1; % DFT peak positions
k1+k2,
x = sin(2*pi*f*t); % sig, figure, plot(t,x);
X = fft(x); % dft

figure, stem(k,abs(X),'LineWidth',2); grid;


xlabel('Freq index, k'); title('DFT of cos(wt)');
% zero-centered fft plots
figure, subplot(211), stem([-N/2:N/2-1],abs(fftshift(X)),'LineWidth',2);
xlabel('Freq index, k'); title('DFT of cos(wt)'); grid;
subplot(212),stem([-N/2:N/2-1]*fftres,abs(fftshift(X)),'LineWidth',2);
xlabel('Freq, Hz'); title('DFT of cos(wt)'); grid;

41
Department of ECE, SRKR Engineering College
DSP Laboratory

Expt-4.3A: Linear & Circular Convolution in Frequency Domain


% Aim: To compute linear & circular convolutions in frequency-domain using FFT

% clc; clear; close all;


x1 = [1 2 3 4]; x2 = [5 6 7 8]; % define signals

% Linear convolution in freq-domain


y1 = conv(x1,x2); % freq-domain convolution by built-in function
% Circular convolution in freq-domain by built-in function
y2 = cconv(x1,x2,4); % 4-point
y3 = cconv(x1,x2,6); % 6-point
% Linear convolution by circular conv in freq domain
N = length(x1)+length(x2)-1; % make N to get linear conv result
y4 = cconv(x1,x2,N);

% Circular convolution via DFT(FFT)


L = 5; % period
X1 = fft(x1,L); X2 = fft(x2,L); % use dft/idft
X3 = X1.*X2; % multiply element-wise
y5 = ifft(X3);
% Linear convolution via DFT(FFT)
X4 = fft(x1,N); X5 = fft(x2,N); % use dft/idft
X6 = X4.*X5; % multiply element-wise
y6 = ifft(X6);

% Plots
figure, subplot(2,2,1);
stem(0:length(x1)-1,x1,'LineWidth',2); title('x_1(n)');
subplot(2,2,2);
stem(0:length(x2)-1,x2,'LineWidth',2); title('x_2(n)');
subplot(2,2,3);
stem(0:length(y1)-1,y1,'LineWidth',2); xlabel('time, n');
title('Linear convolution'); grid;
subplot(2,2,4); stem(0:length(y5)-1,y5,'LineWidth',2); xlabel('time, n');
title('L-point Circular convolution'); grid;

Lab-4.4A: Circular reversal:


% if x(n) <---> X(k), then x(-n) <---> X(-k) = X(N-k)

x = [1 2 3 4]; % seq
N = 4; X = fft(x,N);
xcr = [x(1),x(end:-1:2)]; % x reversal
LHS = fft(xcr,N);
RHS = [X(1),X(end:-1:2)]; % X reversal
LHS-RHS

42
Department of ECE, SRKR Engineering College
DSP Laboratory

Lab-4.4B: Use FFT to compute IFFT

x = [1 2 3 4];
N = 5; X = fft(x,N);
LHS = ifft(X); % ifft
RHS = (1/N)*conj(fft(conj(X))); % ifft using fft only
LHS-RHS

Lab-

x = [1 2 3 4]; % seq
N = 4; X = fft(x,N);
LHS = sum(x.^2); % energy from time domain
RHS = (1/N)*sum(abs(X).^2); % energy from DFT domain
LHS-RHS

Lab-4.4D: Duality property of DFT:


% if x(n) <---> X(k), then X(n) <---> Nx(N-k)

x = [1 2 3 4]; % seq
N = 4; X = fft(x,N);
LHS = fft(X);
xcr = [x(1),x(end:-1:2)]; % x reversal
RHS = N*xcr;
LHS == RHS

43
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Waveforms:

Fig. 4.1 P4.2A: DFT of DT signals: Pulse & Cosine

Fig. 4.2 P4.2B: DFT of a CT signal: Cosine

44
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 4.3 P4.2B: DFT of a CT signal: Cosine

Fig. 4.4 P4.3A: DT Linear & Circular Convolutions using FFT

45
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

46
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

47
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

48
Department of ECE, SRKR Engineering College
DSP Laboratory

5. DT-LTI System Simulation

Expt. No: 5 Date:

Aim: To perform DT-LTI system simulations & compare with analytical results.
To simulate & verify the response of a DT-LTI system to different inputs:
Impulse, Step & Sinusoidal signals

P1: Impulse response &Step response

P2: Steady-state sine response

Software: MATLAB 7.5 (R2007b)

49
Department of ECE, SRKR Engineering College
DSP Laboratory

MATLAB Programs:

Expt-5: DT-LTI System Simulation

Aim: To perform DT-LTI system simulations & compare with analytical results
DT-LTI System Simulation
Aim: To simulate & verify the response of a DT-LTI system to different inputs:
Impulse, Step & Sinusoidal signals
P1: Impulse response & Step response
P2: Steady-state sine response

Expt-5.1: DT-LTI System Simulation

% Aim: To simulate and get the Impulse & Step responses of a DT-LTI system

% Extra function files required:


% clc; clear; close all;
% First try to get analytical solution
% b = [1 -2 2 -1]; a = poly([1 0.5 0.2]); fvtool(b,a)
% next simulate & compare
b = [1 -1 1]; a = [1 -0.7 0.1]; % define system or transfer function = b/a
[r1,p1,k1] = residuez(b,a); % z-partial fractions

% Impulse response
start = -2; final = 20; n = [start:final]; % time interval
% x1 = impseq(0,start,final); % define system input
% x1 = [zeros(1,(n0-n1)), 1, zeros(1,(n2-n0))];
deln = @(n) (n == 0); % impulse
x1 = deln(n); % impulse input
% use filter function to get output when input is applied to the system
% filter: One-dimensional digital filter.
y1 = filter(b,a,x1); % impulse output
% Plots
figure,
subplot(2,2,1); stem(n,x1,'LineWidth',2);
axis([start,final,min(x1)-0.5,max(x1)+0.5]);
title('Impulse input, \delta(n)'); %ylabel('h(n)')
subplot(2,2,2); stem(n,y1,'LineWidth',2);
axis([start,final,min(y1)-0.5,max(y1)+0.5]);
title('Impulse Response, h(n)'); %ylabel('h(n)')

% Step response
b1 = conv(b,[1 0]); a1 = conv(a,[1 -1]); % define system or tf = b/a
[r2,p2,k2] = residuez(b1,a1); % z-partial fractions

50
Department of ECE, SRKR Engineering College
DSP Laboratory

% x2 = stepseq(0,start,final); % step input


% x2 = [zeros(1,(n0-n1)), ones(1,(n2-n0+1))];
un = @(n) (n >= 0); % unit step
x2 = un(n); % step input
y2 = filter(b,a,x2); % step output
subplot(2,2,3); stem(n,x2,'LineWidth',2);
axis([start,final,min(x2)-0.5,max(x2)+0.5]);
title('Step input, u(n)');
xlabel('time, n','fontsize',12); % ylabel('u(n)');
subplot(2,2,4); stem(n,y2,'LineWidth',2);
axis([start,final,min(y2)-0.5,max(y2)+0.5]);
title('Step Response, s(n)');
xlabel('time, n','fontsize',12); % ylabel('s(n)')

Expt-5.2: Time response of a DT-LTI system to sinusoidal input &


Frequency response

% Aim: To simulate a DT-LTI system for a sinewave input & study its
% frequency response

% clc; clear; close all;


% define digital transfer function or system = b/a
% b = [1,1]; a = [1]; % sys1 = filt(b,a); % freqz(b,a)
% w = 1/2*pi; % set frequency
% b = [1 -2 2 -1]; a = poly([1 0.5 0.2]); % Notch system
b = [1 -1 1]; a = [1 -0.7 0.1]; % define Notch filter, tf = b/a

b = 2*[0.0000,0.0054,0.0181,0.0040];
a =[1.0000,-3.0591,3.8323,-2.2919,0.5495]; % Chebyshev LP filter
figure,freqz(b,a); title('Freq response'); % get freq response
sys1 = filt(b,a); % system object
% w = 0.05*pi; % set frequency
w = 0.7*pi; % choose PB,TB,SB freq
% w = 0.334*pi; % notch freq
H = freqresp(sys1,w); % compute freq resp at w
% H = freqz(b,a,w);
magH = abs(H); angH = angle(H)*180/pi;

% Sine response
n = [0:200]; x = 1*cos(w*n); % input sine signal
y = filter(b,a,x); % give input to system to get output
% Plots
figure,
subplot(2,1,1); stem(n,x);
axis([min(n)-1,max(n)+1,min(x)-1,max(x)+1]);

51
Department of ECE, SRKR Engineering College
DSP Laboratory

ylabel('x(n)'); title('Input sine');


subplot(2,1,2); stem(n,y);
axis([min(n)-1,max(n)+1,min(y)-1,max(y)+1]);
xlabel('time, n','fontsize',12); ylabel('y(n)');
title('Output sine');

52
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Waveforms:

Fig. 5.1 P5.1: DT-LTI System Simulation: Impulse & Step responses

Fig. 5.2 P5.2: DT-LTI system: Frequency response Magnitude & Phase

53
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 5.3 P5.2: DT-LTI system: Time response to sinusoidal input at a


Passband freq.

Fig. 5.4 P5.2: DT-LTI system: Time response to sinusoidal input at a


Stopband freq.

54
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

55
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

56
Department of ECE, SRKR Engineering College
DSP Laboratory

6. Spectrum Analysis using Fast Fourier Transform (FFT)

Expt. No: 6 Date:

Aim: To Numerically Compute & Plot the Spectrum of DT & CT Signals using FFT
& to Compare with the Theoretical results.

P1: Frequency analysis of a DT pulse signal

P2: Spectrum analysis of a CT tone signal & aliasing

Software: MATLAB 7.5 (R2007b)

57
Department of ECE, SRKR Engineering College
DSP Laboratory

MATLAB Programs:

Expt-6: Spectrum Analysis using Fast Fourier Transform (FFT)


Aim: To compute the spectrum of DT & CT Signals using FFT & compare with
theoretical results

Part-A: DT pulse signal

Expt-6.1: Spectrum Analysis using Fast Fourier Transform (FFT)

% Aim: To use FFT for the frequency analysis of a DT pulse signal


% DTFT sampled = FFT

x = [ones(1,8) zeros(1,8)]; % signal


n = 0:length(x)-1; % time
N = 1024*1; % fft length
X = fft(x,N); % compute FFT/DTFT at N-points by zero-padding
magX = abs(X); angX = angle(X); % fft magnitude & phase
k = -N/2:N/2-1; % DFT freq index
w = (pi/500)*k; % define digital freq grid, [0,pi] axis divided into 512 points.

% Plots
figure, stem(n,x,'LineWidth',2); grid;
xlabel('Time index, n'); title('Signal, x(n)');
axis([min(n)-1,max(n)+1,min(x)-0.5,max(x)+0.5]);
figure, subplot(211); plot(w/pi,fftshift(magX),'LineWidth',2);
title('Magnitude part: Sinc & Even');
ylabel('Magnitude'); grid;
subplot(212); plot(w/pi,fftshift(angX),'LineWidth',2);
xlabel('Frequency in pi units'); ylabel('Radians');
title('Phase part: Odd'); grid;

Part-B: Continuous-Time Analog signal

Expt-6.2: Spectrum Analysis using Fast Fourier Transform (FFT)

% Aim: To use FFT for the spectrum analysis of a CT tone signal & Observe
aliasing

Fs = 100; T = 1/Fs; % set sampling freq


t = 0:T:2-T; % time-range & sample times
f = 20 + 0.5*0; % tone freq
x = 2*cos(2*pi*f*t) + 0.0*randn(size(t)); % sampled tone sig + noise;
t1 = 0:T/10:1-T/10; % time axis for a smooth plot
x1 = 2*cos(2*pi*f*t1) + 0.0*randn(size(t1)); % sampled tone sig + noise;
x = x(1:end); N = length(x)*1;

58
Department of ECE, SRKR Engineering College
DSP Laboratory

% apply fft function


X = fft(x,N); magX = abs(X); % fft magnitude
k = 0:N-1; % freq index
FFTres = Fs/N; % fft resolution
w1 = k*FFTres; % +ve freq in Hz only
w2 = [-N/2:N/2-1]*FFTres; % define freq axis in +/- ve Hz

% Plots
figure, stem(k,magX); xlabel('Freq index, k');
title('FFT mag');grid,
figure; subplot(211); plot(t1(1:500),x1(1:500)); grid;
title('Analog sig'); xlabel('Time, s');
subplot(212); stem(w2,fftshift(magX),'LineWidth',2); % fft zero-centered
axis([min(w2)-1,max(w2)+1,min(magX)-5,max(magX)+5]);
xlabel('Freq in Hz'); ylabel('FFT Mag'); grid;
title('Frequency analysis with FFT');

59
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Waveforms:

Fig. 6.1 P6.1: Discrete-Time Pulse Signal x(n)

Fig. 6.2 P6.1: DTFT/DFT/FFT of DT Pulse Signal: Sinc spectrum

60
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 6.3 P6.2: FFT Magnitude Spectrum of a CT Sine signal

Fig. 6.4 P6.2: FFT Magnitude Spectrum Analysis of a Tone Signal:


FFT resolution = 0.5 Hz, Input freq = 20 Hz

61
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 6.5 P6.2: FFT Spectrum Analysis of a Tone Signal: Aliasing


70 Hz signal aliases to 30 Hz

Fig. 6.6 P6.2: FFT magnitude spectrum of a CT Sine signal with


Gaussian noise added at SNR = -3db

62
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 6.7 P6.2: FFT magnitude Spectrum of a Tone Signal with


Gaussian noise added at SNR = -3db

Fig. 6.8 P6.2: FFT Spectrum Analysis: Spectral leakage problem


FFT resolution = 1 Hz, Input freq = 20.5 Hz

63
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

64
Department of ECE, SRKR Engineering College
DSP Laboratory

7. Design and Verification of IIR Digital Filters

Expt. No: 7 Date:

Aim: To design & verify IIR Low-pass Digital filters using Bilinear Transformation
& Impulse Invariance Techniques.

P1: To design a Butterworth Low-pass IIR digital filter using Bilinear


Transformation and verify its Magnitude & Phase characteristics.

P2: To verify a Chebyshev-I Low-pass Digital filter design using Impulse


Invariance Technique.

Software: MATLAB 7.5 (R2007b)

65
Department of ECE, SRKR Engineering College
DSP Laboratory

MATLAB Programs:

Expt-7: Design and Verification of IIR Digital Filters

Aim: To design & verify IIR Low-pass Digital filters using Bilinear
Transformation & Impulse Invariance Techniques.

P1: To design a Butterworth Low-pass IIR digital filter using Bilinear


Transformation & verify its Magnitude & Phase characteristics.
P2: To verify a Chebyshev Low-pass Digital filter design using Impulse
Invariance Technique.

Expt-7.1: Bilinear Transformation Technique

Aim: To verify a Butterworth Low-pass IIR digital filter design using


Bilinear transformation method

% If filter specs are given in Hz convert to normalized specs


% using digital freq = 2*pi*analog freq/Fs, Fs = sampling freq
% for example
% fp = 100; fs = 200; % in Hz
% Fs = 1000; % sampling freq
% wp = 2*pi*fp/Fs; ws = 2*pi*fs/Fs;

% Normalized Digital Filter Specifications


wp = 1/4*pi; % digital Passband freq
ws = 1/2*pi; % digital Stopband freq
Rp = 1; % Passband ripple in dB
As = 30; % Stopband attenuation in dB
% wp = 0.2*pi; ws = 0.6*pi; Rp = 2; As = 14;

% BLT design is independent of T


% Convert digital filter Specifications into Analog Prototype filter specs
T = 1; Fs = 1/T; % Set T=1
OmegaP = (2/T)*tan(wp/2); % Pre-warp Prototype Passband freq
OmegaS = (2/T)*tan(ws/2); % Pre-warp Prototype Stopband freq

% Analog filter design formulae


K1 = sqrt((10^(Rp/10)-1)/(10^(As/10)-1));
K = OmegaP/OmegaS;
N1 = log10(K1)/log10(K);
Nb = ceil(N1); % Butterworth filter order
OmegaC1 = OmegaP/((10^(Rp/10)-1)^(1/(2*Nb))); % analog BW prototype 3-
db cutoff
N2 = acosh(1/K1)/acosh(1/K);
Nc = ceil(N2); % Chebyshev filter order

66
Department of ECE, SRKR Engineering College
DSP Laboratory

% Analog Butterworth Prototype Filter Calculation


% [cs,ds] = afd_butt(OmegaP,OmegaS,Rp,As); % get analog filter
[cs,ds] = butter(Nb,OmegaC1,'s'); % get BW analog filter
% [cs,ds] = cheby1(Nc,Rp,OmegaP,'s'); % get Cheby-1 analog filter
% apply Bilinear transformation to get digital filter
[b,a] = bilinear(cs,ds,Fs); % BLT
% roots(b),b/b(1),[C,B,A] = dir2cas(b,a) % convert to cascade form

% Plot freq response, check IR & SR


figure, freqz(b,a);
title('Butterworth LPF: Bilinear'); % see freq resp
fvtool(b,a); title('Butterworth LPF: Bilinear'); % analyze digital filter

Expt-7.2: Impulse Invariance Technique

Aim: To verify a Chebyshev-I Low-pass IIR digital filter design using


Impulse Invariance method

% If filter specs are given in Hz convert to normalized specs


% using digital freq = 2*pi*analog_freq/Fs, Fs = sampling freq
% for example,
% fp = 100; fs = 200; % in Hz
% Fs = 1000; % sampling freq
% wp = 2*pi*fp/Fs; ws = 2*pi*fs/Fs;

% Normalized Digital Filter Specifications:


wp = 0.2*pi; % digital Passband freq
ws = 0.3*pi; % digital Stopband freq
Rp = 1; % Passband ripple in dB
As = 15; % Stopband attenuation in dB

% bs = [2]; as = [1 5 4]; T = 0.1; [b,a] = imp_invr(cs,ds,T)


% wp = 0.2*pi; ws = 0.4*pi; Rp = 3; As = 30;
% wp = 0.3*pi; ws = 0.35*pi; Rp = 1; As = 60;

% Convert digital filter Specifications into Analog Prototype filter specs


T = 1; % Set T=1
OmegaP = wp * T; % Prototype Passband freq
OmegaS = ws * T; % Prototype Stopband freq

% Analog Butterworth/Chebyshev-1 Prototype Filter Calculation:


% [cs,ds] = afd_chb1(OmegaP,OmegaS,Rp,As);
% [Nb,Wn] = buttord(OmegaP,OmegaS,Rp,As,'s'); % order

67
Department of ECE, SRKR Engineering College
DSP Laboratory

% [b,a] = butter(Nb,Wn,'s'); % AF
[Nc,Wn] = cheb1ord(OmegaP,OmegaS,Rp,As,'s'); % order
[bs,as] = cheby1(Nc,Rp,OmegaP,'s'); % AF
% figure, freqs(bs,as); % FR
% bs = [2]; as = [1 5 4]; T = 0.1;
% Print TF H(s) & Pole-Zero diagram
H1 = tf(bs,as), figure,pzmap(H1);axis equal; title('Pole-zero map: H(s)');

% Impulse Invariance transformation:


[bz,az] = impinvar(bs,as,1/T); % DF
% print TF H(z) & Pole-Zero diagram
bz(1) = 0;
H2 = tf(bz,az,T),figure,zplane(bz,az);title('Pole-zero map: H(z)');
% poles = roots(az),abs(poles)
% [b,a] = imp_invr(cs,ds,T);
% [C,B,A] = dir2par(b,a), % convert to parallel form

% Plot freq response, check IR & SR


figure, freqz(bz,az); title('Chebyshev LPF: Impulse Invariance'); % see freq resp
fvtool(bz,az); title('Chebyshev LPF: Impulse Invariance'); % analyze digital filter

68
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Waveforms:

Fig. 7.1 P7.1: Frequency Response: Magnitude & Phase of a


Digital Butterworth LP filter

Fig. 7.2 P7.1: Frequency Response: Magnitude response of a


Digital Butterworth LP filter using fvtool GUI

69
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 7.3 P7.1: Impulse Response of a DT-LTI system:


Butterworth LP filter

Fig. 7.4 P7.1: Step Response of a Butterworth LP digital filter

70
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 7.5 P7.2: Digital Chebyshev-I LP Filter Frequency Response:


Magnitude & Phase

Fig. 7.6 P7.2: Analog Chebyshev-I LP Filter H(s) Pole-Zero Diagram

71
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 7.7 P7.2: Digital Chebyshev-I LP Filter H(z) Pole-Zero Diagram

Fig. 7.8 P7.2: Digital Filter Frequency Response: Magnitude & Phase of a
Chebyshev-I LPF

72
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 7.9 P7.2: Impulse Response of a DT-LTI system:


Chebyshev-I LP filter

Fig. 7.10 P7.2: Step Response of a Chebyshev-I LP digital filter

73
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

74
Department of ECE, SRKR Engineering College
DSP Laboratory

8. Design and Verification of FIR Digital Filters using Windows

Expt. No: 8 Date:

Aim: To design & verify FIR Digital filters using Windows Technique.

P1: To verify FIR Digital low-pass Filter designs using different windows:
Rectangular, Hamming & Blackman.
P2: To verify FIR Digital low-pass Filter designs using a fixed window and
different filter lengths

Software: MATLAB 7.5 (R2007b)

75
Department of ECE, SRKR Engineering College
DSP Laboratory

MATLAB Programs:

Expt-8: Design and Verification of FIR Digital Filters using Windows

Expt-8.1: To design & verify FIR Low-pass Digital filters using Windows
Technique

Aim: To verify FIR Digital low-pass Filter designs using different windows:
Rectangular, Hamming & Blackman.

% help fir1
% b = fir1(n,Wn,window) % n = order,
% help window % rectwin, hamming,
% wintool % GUI

% If filter specs are given in Hz convert to normalized specs


% using digital freq = 2*pi*analog freq/Fs, Fs = sampling freq
% for example
% fp = 100; % in Hz
% Fs = 1000; % sampling freq
% wp = 2*pi*fp/Fs; % normalized passband edge freq

% Specifications
% M can be even or odd
wp = 0.25*pi; % normalized passband cut-off freq
M = 51; % filter length

% hd = ideal_lp(wp,M); % compute filter coeffs


% apply different windows
% w_rect = (rectwin(M))'; h1 = hd .* w_rect; % Rectangular window
% w_ham = (hamming(M))'; h2 = hd .* w_ham; % Hamming window
% w_bla = (blackman(M))'; h3 = hd .* w_bla; % Blackman window

% design with different windows


h1 = fir1(M-1,wp/pi,rectwin(M)); % M-1 = order, Wn = band-edge (0<Wn<1)
h2 = fir1(M-1,wp/pi,hamming(M));
h3 = fir1(M-1,wp/pi,blackman(M));

% freqz(h1,1); % see freq resp using freqz function


H1 = fvtool(h1,1,h2,1,h3,1); % analyze DF using filter visualization GUI tool
legend(H1,'Rect','Hamming','Blackman');
title('FIR Digital LP Filters');

76
Department of ECE, SRKR Engineering College
DSP Laboratory

Expt-8.2: Design and Verification of FIR Digital Filters using Windows

Aim: To verify FIR Digital lowpass Filter designs using a fixed window and
different filter lengths

% Extra function files required: ideal_lp,


% exist('ideal_lp'), which ideal_lp,
% help fir1
% b = fir1(n,Wn,window) % n = order, Wn = band-edge (0<Wn<1)
% help window % rectwin, hamming,
% wintool % GUI

% Specifications: M can be even or odd


wp = 0.25*pi; % normalized passband edge freq
M1 = 21; M2 = 41; M3 = 101; % filter lengths

% hd1 = ideal_lp(wp,M1); % compute filter coeffs


% hd2 = ideal_lp(wp,M2); % hd3 = ideal_lp(wp,M3);
% apply Hamming window
% w1 = window(@hamming,N);
% w_ham1 = (hamming(M1))'; h1 = hd1 .* w_ham1; % window
% w_ham2 = (hamming(M2))'; h2 = hd2 .* w_ham2;
% w_ham3 = (hamming(M3))'; h3 = hd3 .* w_ham3;

% design with different orders, Hamming window


h1 = fir1(M1-1,wp/pi,hamming(M1)); % M-1 = order, Wn = band-edge
(0<Wn<1)
h2 = fir1(M2-1,wp/pi,hamming(M2));
h3 = fir1(M3-1,wp/pi,hamming(M3));

H1 = fvtool(h1,1,h2,1,h3,1) % analyze DF using filter visualization GUI tool


% legend(H1,'[Rect=,int2str(M1)]','Hamming','Blackman')
title(['Filter lengths, M = ',int2str(M1),',',int2str(M2),',',...
int2str(M3)],'Color','r','fontsize',15);
legend(H1);

77
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Waveforms:

Fig. 8.1 P8.1: FIR digital LP filter: Frequency Response Magnitude


using Rectangular, Hamming & Blackman windows

Fig. 8.2 P8.1: FIR digital LP filter: Frequency Response Phase


using three windows: Rectangular, Hamming & Blackman

78
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 8.3 P8.1: FIR digital LP filter Impulse Response: with three
windows: Rectangular, Hamming & Blackman

Fig. 8.4 P8.1: FIR digital LP filter: Step Response with three windows:
Rectangular, Hamming & Blackman

79
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 8.5 P8.2: FIR Digital LPF: Frequency Response Magnitude with
Hamming window & three different filter lengths, N = 21, 41 101
(observe roll-off)

Fig. 8.6 P8.2: FIR Digital LPF: Frequency Response Phase with Hamming
window & three different filter lengths, N = 21, 41 101 (observe slope)

80
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 8.7 P8.2: FIR Digital LPF: Impulse Responses with Hamming
window &three different filter lengths, N = 21, 41 101 (observe delay)

Fig. 8.8 P8.2: FIR Digital LPF: Step Responses with Hamming window &
using three different filter lengths, N = 21, 41 101 (observe the delay)

81
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

82
Department of ECE, SRKR Engineering College
DSP Laboratory

9. LTI Filtering of DT Signals

Expt. No: 9 Date:

Aim: To Design, implement & verify the LTI digital filtering operation in
time and frequency domains.

Software: MATLAB 7.5 (R2007b)

83
Department of ECE, SRKR Engineering College
DSP Laboratory

MATLAB Programs:

Expt-9.1: Design a digital BP filter to reject a specific freq component,


display the signal spectrums using FFT

Aim: Design a digital filter to select/reject freq components & use FFT
for spectrum displays

% IIR BP filter to select 15 Hz component

Fs = 100; % sampling freq


t = (1:Fs)/Fs; % time axis
s1 = sin(2*pi*5*t);
s2 = sin(2*pi*15*t); s3 = sin(2*pi*30*t); % 3 freq are present
s = s1 + s2 + s3; % signal
figure, subplot(2,2,1), plot(t,s);
xlabel('Time (sec)'); title('Filter input, s(t)');

% design an IIR Elliptic digital Band Pass filter to select 15Hz component
[b,a] = ellip(4,0.1,40,[10 20]*2/Fs); % Elliptic BP digital filter
[H,w] = freqz(b,a,512); % filter frequency response
subplot(2,2,2), plot(w*Fs/(2*pi),abs(H));
xlabel('Frequency (Hz)'); title('Mag. of filter response'); grid;

sf = filter(b,a,s); % filtered signal

subplot(2,2,3), plot(t,sf); xlabel('Time (sec)');


title('Filter output'); axis([0 1 -1 1]); % ylabel('Time waveform');
S = fft(s,512); SF = fft(sf,512); % compute spectrum
w = (0:255)/256*(Fs/2); % freq axis, Hz
subplot(2,2,4), plot(w,abs([S(1:256)' SF(1:256)']));
title('Fourier Spectrum Magnitude'); grid;
xlabel('Frequency (Hz)'); legend({'Input','Output'});
% sptool

% IIR LP filter to select 5 Hz component

% FIR HP filter to select 30 Hz component

84
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Waveforms:

Fig. 9.1 P9.1: Signal Filtering using IIR Digital Filter: Elliptic Band-pass
filter to select 15 Hz freq component

85
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

86
Department of ECE, SRKR Engineering College
DSP Laboratory

10. Simulation of Up-sampling & Down-sampling Operations

Expt. No: 10 Date:

Multi-Rate Digital Signal Processing (MR-DSP)


Aim: (1) To implement the Multi-Rate DSP Operations: Up-Sampling &
Down-Sampling (2) To study the Frequency Domain effects of Up-
Sampling & Down-Sampling Operations

Software: MATLAB 7.5 (R2007b)

87
Department of ECE, SRKR Engineering College
DSP Laboratory

MATLAB Programs:

Expt-10.1: Up-Sampling by an Integer Factor, L

L = 3; % Up-sampling Factor
N = 25*1; % Input length
n = 0:N-1; % input time
m = 0:L*N-1; % output time
f1 = 0.12; % Input signal frequency
% Generate the input sinusoidal sequence
x = sin(2*pi*f1*n);
% Generate the up-sampled sequence
y = zeros(1,L*N); % zero seq
y([1:L:length(y)]) = x; % fill
% Plot the input & output sequences
figure, subplot(2,1,1), stem(n,x); title('Input sequence');
xlabel('Time index, n'); ylabel('Amplitude');
subplot(2,1,2), stem(m,y(1:end));
title(['Output sequence: Up-sampled by ', num2str(L)]);
xlabel('Time index, n'); ylabel('Amplitude');

Expt-10.2: Down-Sampling by an Integer Factor, M

M = 2; % Down-sampling Factor
N = 25; % Output length
m = 0:N*M-1; % input time
n = 0:N-1; % output time
f2 = 0.042; % Input signal frequency
% Generate the input sinusoidal sequence
x = sin(2*pi*f2*m);
% Generate the down-sampled sequence
y = x(1:M:length(x));

% Plot the input & output sequences


figure, subplot(2,1,1), stem(m,x(1:end)); title('Input Sequence');
xlabel('Time index, n'); ylabel('Amplitude');
subplot(2,1,2), stem(n,y);
title(['Output sequence: Down-sampled by ',num2str(M)]);
ylabel('Amplitude'); xlabel('Time index, n');

Expt-10.3: Effect of Up-Sampling in the Frequency Domain

% Use fir2 to create a bandlimited input sequence


freq = [0 0.45 0.5 1]; mag = [0 1 0 0]; % desired freq res
x = fir2(99, freq, mag); % Time-domain Impulse Response
88
Department of ECE, SRKR Engineering College
DSP Laboratory

% Evaluate and plot the input spectrum


[Xz,w] = freqz(x,1,512);
figure, subplot(2,1,1), plot(w/pi,abs(Xz),'LineWidth',2); grid
xlabel('\omega/\pi'); ylabel('Magnitude');
title('Input spectrum');

% Generate the up-sampled sequence


L = 3; % up-sampling factor
y = zeros(1,L*length(x));
y([1:L:length(y)]) = x;
% Evaluate and plot the output spectrum
[Yz,w] = freqz(y,1,512);
subplot(2,1,2), plot(w/pi,abs(Yz),'LineWidth',2); grid
xlabel('\omega/\pi'); ylabel('Magnitude');
title(['Output spectrum: up-sampled by ', num2str(L)]);

Expt-10.4: Effect of Down-Sampling in the Frequency Domain

% Use fir2 to create a bandlimited input sequence


freq = [0 0.42 0.48 1]; mag = [0 1 0 0]; % desired freq res
x = fir2(101, freq, mag); % Time-domain Impulse Response
% Evaluate and plot the input spectrum
[Xz,w] = freqz(x,1,512);
subplot(2,1,1), plot(w/pi,abs(Xz),'LineWidth',2); grid
xlabel('\omega/\pi'); ylabel('Magnitude');
title('Input spectrum');
% Generate the down-sampled sequence
M = 2; % down-sampling factor
y = x([1:M:length(x)]);
% Evaluate and plot the output spectrum
[Yz,w] = freqz(y,1,512);
subplot(2,1,2), plot(w/pi,abs(Yz),'LineWidth',2); grid
xlabel('\omega/\pi'); ylabel('Magnitude');
title(['Output spectrum: down-sampled by ', num2str(M)]);

89
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Waveforms:

Fig. 10.1 P10.1: Up-Sampling by an Integer Factor, L

Fig. 10.2 P10.2: Down-Sampling by an Integer Factor, M

90
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 10.3 P10.3: Effect of Up-Sampling in the Frequency Domain

Fig. 10.4 P10.4: Effect of Down-Sampling in the Frequency Domain

91
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

92
Department of ECE, SRKR Engineering College
DSP Laboratory

11. Simulation of Interpolation & Decimation Operations

Expt. No: 11 Date:

Aim: To implement & study the Multi-Rate DSP Operations: Decimation &
Interpolation

P1: Decimation & Interpolation


P2: Fractional Sampling Rate Alteration

Software: MATLAB 7.5 (R2007b)

93
Department of ECE, SRKR Engineering College
DSP Laboratory

MATLAB Programs:

Expt-11.1: Decimation Process

N = 100; % Length of input signal


M = 3; % Down-sampling factor
f1 = 0.043; f2 = 0.031; % Frequency of sinusoids
% Generate the input sequence
n = 0:N-1; % input time
x = sin(2*pi*f1*n) + sin(2*pi*f2*n);

% Generate the decimated output sequence


y = decimate(x,M,'fir'); % uses FIR decimation filter

% Plot the input & output sequences


figure, subplot(2,1,1); stem(n,x(1:N)); title('Input sequence');
xlabel('Time index, n');ylabel('Amplitude');
m = 0:N/M-1; % output time
subplot(2,1,2); stem(m,y(1:N/M));
title(['Output sequence decimation by ',num2str(M)]);
xlabel('Time index, n'); ylabel('Amplitude');

Expt-11.2: Interpolation Process

N = 100; % Length of input signal


L = 3; % Up-sampling factor
f1 = 0.043; f2 = 0.031; % Frequency of sinusoids
% Generate the input sequence
n = 0:N-1; x = sin(2*pi*f1*n) + sin(2*pi*f2*n);
% Generate the interpolated output sequence
y = interp(x,L);

% Plot the input & output sequences


figure, subplot(2,1,1); stem(n,x(1:N)); title('Input sequence');
xlabel('Time index, n'); ylabel('Amplitude');
m = 0:N*L-1; % time
subplot(2,1,2); stem(m,y(1:N*L));
title(['Output sequence Interpolation by ',num2str(L)]);
xlabel('Time index, n'); ylabel('Amplitude');

Expt-11.3: Sampling Rate Alteration by a Ratio of Two Integers -> L/M

N = 100; % Length of input signal


L = 3; % Up-sampling factor
M = 5; % Down-sampling factor
94
Department of ECE, SRKR Engineering College
DSP Laboratory

n = 0:N-1; % input time


m = 0:N*L/M-1; % output time
f1 = 0.043; f2 = 0.031; % Frequency of sinusoids

% Generate the input sequence


x = sin(2*pi*f1*n) + 1*sin(2*pi*f2*n);
% Generate the resampled output sequence
y = resample(x,L,M); % sampling rate alteration by a ratio

% Plot the input & output sequences


figure, subplot(2,1,1), stem(n,x(1:N)); title('Input sequence');
xlabel('Time index, n'); ylabel('Amplitude');
subplot(2,1,2), stem(m,y(uint8(1:N*L/M)));
title(['Output sequence Interpolation by ',num2str(L),'/',num2str(M)]);
xlabel('Time index, n'); ylabel('Amplitude');

Expt-11.4: Decimate a CT signal by a factor of four

Fs = 4000; Ts = 1/Fs; D = 3;
t = 0:Ts:1-Ts; % Time vector
x = sin(2*pi*30*t) + sin(2*pi*60*t);
y = decimate(x,D);
figure, subplot(211); stem(x(1:120)), % Original signal
axis([0 120 -2 2]); title('Original Signal');
subplot(212); stem(y(1:30)); % Decimated signal
title('Decimated Signal');

Expt-11.5: Interpolate a CT signal by a factor of four

Fs = 1000; Ts = 1/Fs; I = 4;
t = 0:Ts:1-Ts; % Time vector
x = sin(2*pi*30*t) + sin(2*pi*60*t);
y = interp(x,I);
figure, subplot(211); stem(x(1:30)); title('Original Signal');
subplot(212); stem(y(1:120)); title('Interpolated Signal');

95
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Waveforms:

Fig. 11.1 P11.1: Decimation Process

Fig. 11.2 P11.2: Interpolation Process

96
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 11.3 P11.3: Fractional Sampling Rate Alteration by a Ratio of Two


Integers: L/M = 3/5

97
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

98
Department of ECE, SRKR Engineering College
DSP Laboratory

12. Sampling Theorem, Signal Reconstruction & Aliasing

Expt. No: 12 Date:

Aim: To verify Sampling Theorem & Observe Aliasing

P1: Sampling & Reconstruction of Signals


P2: Zero-Order-Hold (ZOH) & First-Order-Hold (FOH) Reconstruction

Software: MATLAB 7.5 (R2007b)

99
Department of ECE, SRKR Engineering College
DSP Laboratory

MATLAB Programs:

Expt-12: Sampling Theorem, Signal Reconstruction & Aliasing


P1: Sampling & Reconstruction of Signals
P2: ZOH & FOH Approximation

Expt-12.1: Verification of Sampling Theorem

Aim: To verify Sampling Theorem & Observe Aliasing

% To sample and reconstruct a signal above & below Nyquist rate.


% clc; clear; close all;
% Analog Signal: x(t)=cos(4*pi*t),
% fmax = 2Hz, Nyquist rate = 4Hz
f = 2; range = 1; % set freq, amp, time range
Fs = 200; dt = 1/Fs; % to see analog plot take Fs high
t = -range:dt:range;% time
xa = cos(2*pi*f*t); % use fine interpolation grid

% Discrete-time Signal x1(n): sampled above Nyquist rate


Fs1 = 5; Ts1 = 1/Fs1;
nTs1 = -range:Ts1:range; xn1 = cos(2*pi*f*nTs1);
% Discrete-time Signal x2(n): sampled below Nyquist rate
Fs2 = 3; Ts2 = 1/Fs2;
nTs2 = -range:Ts2:range; xn2 = cos(2*pi*f*nTs2);

% Plots
% axis([min(n)-1,max(n)+1,min(y)-1,max(y)+1]);
figure('Name','Sampling theorem');
subplot(2,3,1); plot(t,xa); axis([-1 1 -1.2 1.2]); grid;
xlabel('t in sec.'); title('Analog Signal x(t)');
subplot(2,3,2); stem(nTs1,xn1,'LineWidth',2);
xlabel('n, t'); title('Discrete Signal x_1(n)');
hold on; plot(t,xa,'k:');hold off; axis([-1 1 -1.2 1.2]);grid;
subplot(2,3,3); stem(nTs2,xn2,'LineWidth',2);
xlabel('n, t'); title('Discrete Signal x_2(n)');
hold on; plot(t,xa,'k:'); hold off;axis([-1 1 -1.2 1.2]);grid;

% Analog Signal Reconstruction with Ideal Low Pass Filter


% Interpolation using sinc function (use formula)
xa1 = xn1 * sinc(Fs1*(ones(length(nTs1),1)*t-nTs1'*ones(1,length(t))));
xa2 = xn2 * sinc(Fs2*(ones(length(nTs2),1)*t-nTs2'*ones(1,length(t))));

subplot(2,3,4); plot(t,xa); xlabel('t in sec.');


title('Original x(t)'); axis([-1 1 -1.2 1.2]); grid;

100
Department of ECE, SRKR Engineering College
DSP Laboratory

subplot(2,3,5); plot(t,xa1); xlabel('t in sec.'); ylabel('x1(t)'); hold on; axis([-1 1


-1.2 1.2]); grid;
title('Reconstructed from x_1(n) using sinc interpolation');
subplot(2,3,6); plot(t,xa2); xlabel('t in sec.'); ylabel('x2(t)'); axis([-1 1 -1.2
1.2]); grid;
title('Recovery from x_2(n) using sinc (aliased)');

% Analog Signal Reconstruction with ZOH & FOH

Fs3 = 20; dt = 1/Fs3; % sample at


t2 = -range:dt:range; xa3 = cos(2*pi*f*t2); %

% Plots
figure('Name','Reconstruction');
subplot(211); stairs(t2,xa3,'r','LineWidth',2);
title('ZOH approx.of x(t)');
hold on; plot(t,xa1,'k:','LineWidth',2); hold off;
axis([-1 1 -1.2 1.2]); grid;
subplot(212); plot(t2,xa3,'r','LineWidth',2);
title('FOH approx.of x(t)');
hold on; plot(t,xa1,'k:','LineWidth',2); hold off;
axis([-1 1 -1.2 1.2]); grid; xlabel('t in sec.');
% plot(nTs2,xn2,'r');

101
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Waveforms:

Fig. 12.1 P12.1: Sampling Theorem Verification & Aliasing

Fig. 12.2 P12.1: Sampling: Signal Reconstruction with ZOH & FOH

102
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

103
Department of ECE, SRKR Engineering College
DSP Laboratory

Analysis, Code Description, Observations & Conclusions:

104
Department of ECE, SRKR Engineering College
DSP Laboratory

13. Digital Image Processing

Expt. No: 13 Date:

Aim: To Implement and Visualize the Basic Image Processing Operations

P1: Image Enhancement: Image size & display, Sampling and Quantization,
Brightness & Contrast Adjustment, Histogram & Equalization, Edge Detection,

P2: Image Filtering in Spatial/Frequency domains

P3: Image Restoration: Image De-Blurring & De-Noising

P4: Image Transforms: Fourier, DCT

Software: MATLAB 7.5 (R2007b)

105
Department of ECE, SRKR Engineering College
DSP Laboratory

Expt-13: Digital Image Processing (DIP) Experiments, 2022-23

MATLAB Programs:

%% Image Processing Toolbox


help images
% help image; % displays matrix X as an image
% load clown; image(X); colormap(map)
% help imagesc % Scale data and display as image
% help imread % read image from file
% help imshow
% help imwrite % save image to file

Expt-13.1A: Read & Display Image

% Load image
% I1 = imread('eight.tif');
% I1 = imread('XiLena.jpg'); % get image
% I1 = imread('Lena_image.bmp'); % get image
I1 = imread('Einstein.bmp'); % get original image
% imfinfo('Einstein.bmp') % Information about graphics file
figure, imshow(I1); title('Einstein image'); %axis ij;

Expt-13.1B: Image Resize

I = imread('Einstein.bmp'); % get original image


J = imresize(I,0.5); % reduce 50%
figure, imshow(I); title('Einstein image');
figure, imshow(J); title('Einstein image resized to 50%');

Expt-13.1C: Image Tool, Pixel region, Adjust contrast,

% help imtool
imtool('cameraman.tif')

106
Department of ECE, SRKR Engineering College
DSP Laboratory

Expt-13.2: Image Enhancement

Expt-13.2: Brightness & Contrast Adjustment

Expt-13.2A: Brightness adjustment by intensity scaling

% clear, clc, close all


img = im2double(imread('parrot.jpg'));
scale = 1.2;
scaledImg = scale .* img;
figure, subplot(1,2,1), imshow(img,[0,1]);
title('Original image');
subplot(1,2,2), imshow(scaledImg,[0,1]);
title('Brightness scaled image');
% imwrite(scaledImg, 'Brightness_scaled.png');

Expt-13.2B: Adjust Image Intensity

% help imadjust
I = imread('pout.tif');
J = imadjust(I);
figure, subplot(121),imshow(I),title('Low contrast image');
subplot(122),imshow(J),title('Intensity adjusted');
K = imadjust(I,[0.3 0.7],[]);
figure, imshow(K),title('Intensity adjusted');

Expt-13.2C: Gray-level thresholding

I = imread('coins.png'); imhist(I);title('Image histogram');


level = graythresh(I); % threshold
BW = im2bw(I,level); % binarize
figure, subplot(1,2,1),imshow(I);title(' Gray image');
subplot(1,2,2),imshow(BW);title('Binary image');

Expt-13.2D: Contrast adjustment by changing "gamma"


img = im2double(imread('parrot.jpg'));
gamma = 0.8;
gammaImg = img.^gamma;
figure; subplot(1,2,1),imshow(img);title('Original image');
subplot(1,2,2),imshow(gammaImg);title(['\gamma = ',num2str(gamma)]);

107
Department of ECE, SRKR Engineering College
DSP Laboratory

Expt-13.2E: Adjust Image Contrast

% help imcontrast
% I1 = imread('Einstein.bmp')
imshow('pout.tif'); % which pout.tif
% imshow('Einstein.bmp');
imcontrast(gca)

Expt-13.2F: Adjust Image Contrast

I = imread('pout.tif');
Imlimits = stretchlim(I);
J = imadjust(I,Imlimits,[]);
figure, subplot(121),imshow(I),title('Low contrast image');
subplot(122),imshow(J),title('Contrast stretched');

Expt-13.2G: Image Histogram & Equalization

% help imhist
% help histeq
% I = imread('tire.tif');
I = imread('pout.tif');
J = histeq(I); % Enhance contrast using histogram equalization
figure, subplot(211),imhist(I),title('Actual histogram');
subplot(212),imhist(J),title('Histogram equalized');
figure, subplot(121),imshow(I),title('Original image');
subplot(122),imshow(J),title('Histogram equalized');

Expt-13.2H: Edge Detection

% help edge
I = imread('circuit.tif');
BW1 = edge(I,'prewitt'); BW2 = edge(I,'canny');
figure, imshow(I),title('Original image');
figure, subplot(121),imshow(BW1),title('Prewitt edge operator');
subplot(122),imshow(BW2),title('Canny edge operator')

108
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Output Images:


Einstein image

Fig. 13.1 P13.1: Image display & Resized image

Fig. 13.2 P13.2: Image & Intensity scaling

109
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 13.3 P13.2: Image & Intensity Adjustment

Fig. 13.4 P13.2: Image Histogram & Equalized Histogram

Fig. 13.5 P13.2: Low Contrast Image & Histogram Equalization Effect

110
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 13.6 P13.2: Edge Detection using Operators

111
Department of ECE, SRKR Engineering College
DSP Laboratory

Code Description, Observations & Conclusions:

112
Department of ECE, SRKR Engineering College
DSP Laboratory

Expt-13.3: Image Filtering in Spatial/Frequency Domains

Expt-13.3A: Linear Spatial Filtering of Images using imfilter/conv2

% I = imread('coins.png');
I = imread('Einstein.bmp');
N = 11; h = ones(N,N)/(N*N); % averaging LP filter
I2 = imfilter(I,h); % 2D filtering
figure, subplot(1,2,1), imshow(I);title('Original Image');
subplot(1,2,2), imshow(I2), title('LP Filtered Image')

Expt-13.3B: 2D Image Filtering in Spatial/Frequency domains

% x = imread('Lena.bmp');
x = imread('Einstein.bmp');
f = double(x); ff = abs(fft2(f)); % 2D fft mag

% Averaging filter
L = 5; h = ones(2*L+1,2*L+1)/((2*L+1)^2); % 2D filter IR
[X,Y] = meshgrid(-L:L);
[hf,Fx,Fy] = freqz2(h,512); % 2D freq res

% Spatial domain filtering using conv2


y = conv2(f,h); % 2D spatial filtering
yf = abs(fft2(y)); % 2D fft

% Frequency domain filtering using fft2


Y2 = fft2(f).*fftshift(hf); % 2D fft multiplication
y2 = (ifft2(Y2)); % FD filtered image

figure(1);
subplot(221),imshow(x); title('Image');
subplot(2,2,2),mesh(X,Y,h*(2*L+1)^2),%axis([-10 10 -10 10 -1 2]),
title('2D Impulse resp');
subplot(223),imagesc(y); title('SD filtered image');
colormap(gray);truesize;axis off;
subplot(224),imshow(uint8(real(y2)),[])
title('FD filtered image');
% imagesc(real(y2)),colormap(gray);
% mlowv = min(min(y2)), mhighv = max(max(y2))

figure(2);
subplot(2,2,1),imagesc(fftshift(log(ff+1)));title('Spectrum image');
colormap(gray);%truesize;%axis off;

113
Department of ECE, SRKR Engineering College
DSP Laboratory

subplot(2,2,2), imagesc((log(abs(hf)+1))); title('LPF mag response');


colormap(gray);%truesize;%axis off;
subplot(2,2,3), imagesc(fftshift(log(yf+1)));
colormap(gray); truesize;axis off;
title('SD filtered spectrum');
subplot(2,2,4), imagesc(fftshift(log(abs((Y2))+1)));
title('FD filtered spectrum');
colormap(gray); truesize;axis off;

114
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Output Images:

Fig. 13.7 P13.3: LP Filtered Image

Fig. 13.8 P13.3: Image Filtering in Spatial & Frequency domains

115
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 13.9 P13.3: Image Filtering in Frequency domain: FFT images

116
Department of ECE, SRKR Engineering College
DSP Laboratory

Expt-13.4: Image Restoration: De-Blurring & De-Noising

Expt-13.4A: Image Deblurring

% a) Causes of Blurring: The blurring, or degradation, of an image can be


caused by many factors:
% Movement during the image capture process, by the camera or, when long
exposure times are used, by the subject Out-of-focus optics, use of a wide-angle
lens, atmospheric turbulence, or a short exposure time, which reduces the
number of photons captured Scattered light distortion in confocal microscopying.

% b) Deblurring Model: A blurred or degraded image can be approximately


described by this equation g = Hf + n, where g-The blurred image, H -The
distortion operator, also called the point spread function (PSF), f-The original
true image, n-Additive noise, introduced during image acquisition, that corrupts
the image

% (1): Deblurring of image by using Wiener-filter:

% I = imread('coins.png'); % get original image


I = im2double(imread('Einstein.bmp')); % get original image
[M,N] = size(I); % rows, cols

% 1) To get blurred image:


% h = ones(5,5)/25; % define 2D filter to create blurring
% h = ones(9,9)/81; % define 2D filter to create blurring
% I2 = imfilter(I,h); % 2D image filtering
% figure, subplot(121),imshow(I), title('Original Image');
% subplot(122),imshow(I2), title('Filtered (Blurred) Image'); % blurred

% 2) To get blurred image:


% using the imfilter function and predefined filter types
LEN = 31; THETA = 11;
PSF = fspecial('motion',LEN,THETA); % create PSF
Blurred = imfilter(I,PSF,'circular','conv'); % blur
var1 = 0.01; % noise var
NoisyBlurred = imnoise(Blurred,'gaussian',0,var1); % add noise

% compute root mean square error and psnr


rmse1 = sqrt( sum(sum((I-Blurred).^2))/M/N );
psnr1 = 20*log10(1/rmse1);
rmse2 = sqrt( sum(sum((I-NoisyBlurred).^2))/M/N );
psnr2 = 20*log10(1/rmse2);

117
Department of ECE, SRKR Engineering College
DSP Laboratory

% NOTE: where LEN=31 is length of the blur in pixel and THETA indicates blur

image

% Use the deconvwnr function to deblur an image using the Wiener filter.
% By using Regularized filter, Lucy-Richardson algorithm, Blind deconvolution
algorithm also we can get deblurred image

% 3) To get the deblurred image:


% Wiener filtering (deblurring)
% help deconvwnr
% wnr1 = deconvwnr(I2,PSF); %
% experiemnt with the value of nsr
% nsr = 10^(-4); % 10^-4, 10^-5 10^-6 10^-3 10^-2
% K = deconvwnr(J1, PSF, nsr);

% De-blurring using Wiener filter


wnr1 = deconvwnr(Blurred,PSF);
wnr2 = deconvwnr(NoisyBlurred,PSF,var1);
% compute rms error & psnr between original & deblurred pictures
rmse3 = sqrt( sum(sum((I-wnr1).^2))/M/N );
psnr3 = 20*log10(1/rmse3);
rmse4 = sqrt( sum(sum((I-wnr2).^2))/M/N );
psnr4 = 20*log10(1/rmse4);

% plot results
figure, subplot(131),imshow(I), title('Original Image');
subplot(132),imshow(Blurred); xlabel('Motion Blurred Image');
title(['PSNR = ', num2str(psnr1,4), ' dB']);
subplot(133),imshow(NoisyBlurred),xlabel('Blurred Image + Noise'); % blur +
noise
title(['PSNR = ', num2str(psnr2,4), ' dB']);

figure; subplot(221),imshow(Blurred);xlabel('Motion Blurred Image');


title(['PSNR = ', num2str(psnr1,4), ' dB']);
subplot(222),imshow(wnr1);xlabel('Restored, True PSF');
title(['PSNR = ', num2str(psnr3,4), ' dB']);
subplot(223),imshow(NoisyBlurred);xlabel('Blurred Image + Noise');
title(['PSNR = ', num2str(psnr2,4), ' dB']);
subplot(224),imshow(wnr2);xlabel('Restored, True PSF');
title(['PSNR = ', num2str(psnr4,4), ' dB']);

118
Department of ECE, SRKR Engineering College
DSP Laboratory

Expt-13.4B: Noisy image

% I = imread('eight.tif');
I = imread('Einstein.bmp');
J1 = imnoise(I,'gaussian',0,0.01);
J2 = imnoise(I,'salt & pepper',0.1);
J3 = imnoise(I,'speckle',0.01);
figure, subplot(221), imshow(I), title('Image')
subplot(222), imshow(J1), title('Gaussian noise')
subplot(223), imshow(J2), title('Salt & pepper')
subplot(224), imshow(J3), title('Speckle')

119
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Output Images:

Fig. 13.10 P13.4: Image degradation: Blurring & Noise

Fig. 13.11 P13.4: Image Restoration: De-blurring


Image Gaussian noise

Salt & pepper Speckle

Fig. 13.12 P13.4: Noisy Images

120
Department of ECE, SRKR Engineering College
DSP Laboratory

Expt-13.5: Image Transforms

Expt-13.5: 2D Image Transforms: Fourier, DCT (Discrete Cosine


Transform)

Expt-13.5A: FFT of Images

% close all;
x1 = imread('Lena_image.bmp'); % imshow(x1);title('Lena image')
% X1 = fft2(double(x1)); x1r = ifft2(X1);
% figure, imagesc(real(x1r));colormap(gray);title('Lena image');truesize

x2 = imread('Einstein.bmp');
f1 = double(x1); f1fm = abs(fft2(f1)); f1fp = angle(fft2(f1));
f2 = double(x2); f2fm = abs(fft2(f2)); f2fp = angle(fft2(f2));

figure(1); subplot(231),imshow(x1);title('Lena')
subplot(232), imagesc(fftshift(log(f1fm+1))); title('FFT2 mag')
colormap(gray); truesize;axis off;
subplot(233), imshow(fftshift((f1fp))); title('FFT2 phase')
colormap(gray); truesize;axis off;
subplot(234), imshow(x2);title('Einstein')
subplot(235), imagesc(fftshift(log(f2fm+1))); title('FFT2 mag')
colormap(gray); truesize;axis off;
subplot(236), imshow(fftshift((f2fp))); title('FFT2 phase')
colormap(gray); truesize;axis off;

% exchange mag & phase


Y1 = f1fm.*exp(j.*f2fp); y1 = (ifft2(Y1));
figure(2); subplot(121),imagesc((real(y1)));colormap(gray);
title('Lena mag + Einstein phase');axis off;
Y2 = f2fm.*exp(j.*f1fp); y2 = (ifft2(Y2));
subplot(122),imagesc((real(y2)));colormap(gray);
title('Einstein mag + Lena phase');truesize;axis off;

% only mag & only phase


Y3 = f1fm.*exp(j.*f1fp*0); y3 = (ifft2(Y3));
% figure(3);subplot(121),imagesc((real(y3)));colormap(gray);
figure(3); subplot(121), imshow(uint8(real(y3)));
title('Lena: Only mag'); colormap(gray);axis off;
Y4 = 1.*exp(j.*f1fp); y4 = (ifft2(Y4));
subplot(122), imagesc((real(y4))); colormap(gray);
title('Lena: Only phase'); truesize;axis off;

121
Department of ECE, SRKR Engineering College
DSP Laboratory

Expt-13.5B: DCT: Discrete Cosine Transform demo


dctdemo % run demo

Expt-13.5C: DCT of an image

% clc; clear all; close all;


% RGB = imread('autumn.tif'); % pixval = RGB(20,40,:)
% I = rgb2gray(RGB);
I = imread('Einstein.bmp'); % pixval = I(2,15)
[M,N] = size(I); % rows, cols
Npixels = M*N;
J = dct2(I); % DCT
DCT1 = log(abs(J)+1);
th = 30*1; % Threshold value below which the co-efficients are made 0
J(abs(J) < th) = 0; % DCT coefficients thresholded
K = idct2(J); % IDCT
zeros_count = sum(sum(abs(J) == 0));
count_percent = zeros_count/Npixels*100;

% Plots
figure, subplot(121), imshow(I), title('Image');
subplot(122), imshow(K,[0 255]); title('Image with DCT modified');
figure, subplot(121), imshow(DCT1,[]),colormap(jet),colorbar, title('DCT');
subplot(122), imshow(log(abs(J)+1),[]),colormap(jet),colorbar
title(sprintf('DCT coeffs thresholded at %d',th));

122
Department of ECE, SRKR Engineering College
DSP Laboratory

Results & Output Images:

Fig. 13.13 P13.5: 2D FFT of Images: Mag & Phase

Fig. 13.14 P13.5: Two images with magnitude & phase swapped

Fig. 13.15 P13.5: Only magnitude & Only phase images

123
Department of ECE, SRKR Engineering College
DSP Laboratory

Fig. 13.16 P13.5: Effect of DCT coefficient Thresholding

Fig. 13.17 P13.5: Image Compression by DCT Thresholding

124
Department of ECE, SRKR Engineering College
DSP Laboratory

Code Description, Observations & Conclusions:

125
Department of ECE, SRKR Engineering College
DSP Laboratory

Code Description, Observations & Conclusions:

126

You might also like