You are on page 1of 57

Digital Signal Processing

Lab Manual
Submitted To:

Submitted By:
Name:
Registration no:
Program:
EEE 324 - Digital Signal Processing

List of Experiments
Lab 1 Introduction to the MATLAB/ Getting Started with MATLAB
Lab 2 Generation of Elementary Continuous Time Signals
Concept of Harmonics
Lab 3
Generation Of Elementary Discrete Time Signals

Lab 4 Sampling Theorem

Lab 5 Impulse response of the LTI system

Lab 6 Frequency Response of the LTI System

Lab 7 Z-Transform and Inverse Z-Transform

Lab 8 Linear Convolution

Lab 9 Discrete Time Fourier Transform- DTFT

Lab 10 Filters- Finite Impulse Response (FIR) Filter Design

Lab 11 Infinite Impulse Response (IIR) Filter Design

Lab 12 Sound Processing in MATLAB

Direct Digital Synthesis Using MATLAB and C


Lab 13
Direct Digital Synthesis Using TMS320C6713 DSK

Introduction to Digital Image Processing/ Operations on Images


Lab 14
DSP Lab 01
Introduction to MATLAB
Objectives: To Get Familiarize With MATLAB Software

MATLAB: MATLAB is a software package for high performance numerical computation and
visualization provides an interactive environment with hundreds of built in functions for technical
computation, graphics and animation. The MATLAB name stands for MATrix LABoratory produced by
Mathworks Inc., USA.

At its core ,MATLAB is essentially a set (a “toolbox”) of routines (called “m files” or “mex files”) that
reside on your computer and a window that allows you to create new variables with names (e.g. voltage
and time) and process those variables with any of those routines (e.g. plot voltage against time, find the
largest voltage, etc).

It also allows you to put a list of your processing requests together in a file and save that combined list
with a name so that you can run all of those commands in the same order at some later time. Furthermore,
it allows you to run such lists of commands such that you pass in data and/or get data back out (i.e. the list
of commands is like a function in most programming languages). Once you save a function, it becomes
part of your toolbox (i.e. it now looks to you as if it were part of the basic toolbox that you started with).
For those with computer programming backgrounds: Note that MATLAB runs as an interpretive language
(like the old BASIC). That is, it does not need to be compiled. It simply reads through each line of the
function, executes it, and then goes on to the next line. (In practice, a form of compilation occurs when
you first run a function, so that it can run faster the next time you run it.)

MATLAB Windows:

MATLAB works with through three basic windows.

Command Window: This is the main window. It is characterized by MATLAB command prompt >>
when you launch the application program MATLAB puts you in this window all commands including
those for user-written programs ,are typed in this window at the MATLAB prompt.
Graphics window: the output of all graphics commands typed in the command window are flushed to the
graphics or figure window, a separate gray window with white background colour the user can create as
many windows as the system memory will allow.

Edit window: This is where you write edit, create and save your own programs in files called M files.

Input-output: MATLAB supports interactive computation taking the input from the screen and flushing,
the output to the screen. In addition it can read input files and write output files.

Data Type: The fundamental data –type in MATLAB is the array. It encompasses several distinct data
objects- integers, real numbers, matrices, character strings, structures and cells. There is no need to
declare variables as real or complex, MATLAB automatically sets the variable to be real.

Dimensioning: Dimensioning is automatic in MATLAB. No dimension statements are required for


vectors or arrays. We can find the dimensions of an existing matrix or a vector with the size and length
commands.

Where to work in MATLAB?

All programs and commands can be entered either in the

a) Command window.

b) As an M file using Matlab editor.

Note: Save all M files in the folder 'work' in the current directory. Otherwise you have to locate the file
during compiling. Typing quit in the command prompt >> quit, will close MATLAB Development
Environment.

Basic commands in MATLAB


T = 0:1:10
This instruction indicates a vector T which as initial value 0 and final value 10 with an
increment of 1
Therefore T = [0 1 2 3 4 5 6 7 8 9 10]

F= 20:1:100

Therefore F = [20 21 22 23 24 ……… 100]

T= 0: 1/pi: 1
Therefore T= [0, 0.3183, 0.6366, 0.9549]

zeros (1, 3)
The above instruction creates a vector of one row and three columns whose values are zero
Output= [0 0 0]
zeros (2,4)
Output = 0 0 0 0 0 0 0 0

zeros (2,4)
Output = 0 0 0 0 0 0 0 0

zeros (2,4)
Output = 0 0 0 0 0 0 0 0

ones (5,2)
The above instruction creates a vector of five rows and two columns
Output = 1 1 1 1 1 1 1 1 1 1

a = [ 1 2 3] b = [4 5 6]
a.*b = [4 10 18]

If C= [2 2 2]
b.*C results in [8 10 12]

plot (t, x)
If x = [6 7 8 9]
t = [1 2 3 4]

This instruction will display a figure window which indicates the plot of x versus t.

stem (t,x) :-
This instruction will display a figure window as shown
Subplot: This function divides the figure window into rows and columns.
Subplot (2 2 1) divides the figure window into 2 rows and 2 columns 1 represent number
of the figure

Conv
Syntax: w = conv(u,v)
Description: w = conv(u,v) convolves vectors u and v. Algebraically, convolution is the same
operation as multiplying the polynomials whose coefficients are the elements of u and v.

Disp
Syntax: disp(X)

Description: disp(X) displays an array, without printing the array name. If X contains a text string,
the string is displayed. Another way to display an array on the screen is to type its name, but this
prints a leading "X=," which is not always desirable. Note that disp does not display empty arrays.

xlabel
Syntax: xlabel('string')

Description: xlabel('string') labels the x-axis of the current axes.

ylabel
Syntax : ylabel('string')

Description: ylabel('string') labels the y-axis of the current axes.

Title
Syntax : title('string')

Description: title('string') outputs the string at the top and in the centre of the current axes
grid on
Syntax : grid on
Description: grid on adds major grid lines to the current axes

FFT
FFT(X) is the discrete Fast Fourier transform (FFT) of vector X. For matrices, the FFT operation is
applied to each column. For N-D arrays, the FFT operation operates on the first non-singleton
dimension. FFT(X,N) is the N-point FFT, padded with zeros if X has less than N points and
truncated if it has more

ABS
Absolute value.
ABS(X) is the absolute value of the elements of X. When X is complex, ABS(X) is the complex
modulus (magnitude) of the elements of X.

ANGLE Phase angle.


ANGLE(H) returns the phase angles, in radians, of a matrix with complex elements

INTERP
Resample data at a higher rate using low-pass interpolation.

Y = INTERP(X,L) re-samples the sequence in vector X at L times the original sample rate. The
resulting re-sampled vector Y is L times longer, LENGTH(Y) = L*LENGTH(X).

DECIMATE
Resample data at a lower rate after low-pass filtering.

Y = DECIMATE(X,M) re-samples the sequence in vector X at 1/M times the original sample rate.
The resulting re-sampled vector Y is M times shorter,
i.e., LENGTH(Y) = CEIL(LENGTH(X)/M). By default, DECIMATE filters the data with an 8th
order Chebyshev Type I low-pass filter with cut-off frequency .8*(Fs/2)/R, before re-sampling.

Lab evaluation points:

Lab instructor Signature: Date:


DSP Lab 02
GENERATION OF ELEMENTARY CONTINUES TIME SIGNALS

Write a MATLAB program to develop some elementary continues time (CT) signals

a. Sinusoidal
b. Square
c. Complex waveform
d. Unit Step
e. Unit Ramp
f. Exponential
g. Noise

MATLAB Code:

a) Sinusoidal Waveform

clc;
clear all;
close all;
t = 0 : 0.001 : 5;
f = input ('Enter the value of frequency');
a = input ('Enter the value of amplitude');
subplot (2,1,1);
y =a*sin(2*pi*f*t);
plot (t,y,'r');
xlabel ('time');
ylabel ('amplitude');
title ('sine wave')
grid on;
b) Square Waveform
clc;
clear all;
close all;
t = 0 : 0.001 : 5;
f = input ('Enter the value of frequency');
a = input ('Enter the value of amplitude');
subplot (2,1,1);
y =a*square(2*pi*f*t);
plot (t,y,'r');
xlabel ('time');
ylabel ('amplitude');
title ('Square wave')
grid on;

c) Complex Waveform
clc;
clear all;
close all;
t = 0 : 0.001 : 5;
f = input ('Enter the value of frequency');
a = input ('Enter the value of amplitude');
subplot (2,1,1);
y = [exp((-0.2+2*i)*t)];
plot (t,y,'r');
xlabel ('time');
ylabel ('amplitude');
title ('Complex’)
grid on

d) Unit Step Waveform


clc;
clear all;
close all;
t = 0 : 0.001 : 5;
a = input ('Enter the value of amplitude');
subplot(2,1,1)
plot (t,a,'r');
xlabel ('time');
ylabel ('amplitude');
title ( 'Complex Wave')
grid on;

e) Unit Ramp Waveform


clc;
clear all;
close all;
t = 0 : 0.001 : 5;
m = input ('Enter the value of slope');
subplot (2,1,1);
y = m*t;
plot (t,y,'r');
xlabel ('time');
ylabel ('amplitude');
title ('Ramp wave')
grid on;

f) Exponential Waveform
clc;
clear all;
close all;
a=0.5;
t=0:0.1:10;
disp('EXPONENTIAL DECAYING SIGNAL');
x=a.^t;
subplot(2,1,1);
plot(t,x);
xlabel('Time');
ylabel('Amplitude');
title('Exponential Decaying Signal Response');

grid on;
g) Noise Signal
clc;
clear all;
close all;
t=0:0.001:50;
% generate the uncorrupted signal
s=2*t.*(0.9.^t);
subplot(2,1,1);
plot(t,s);
title('Uncorrupted sequence');
xlabel('Time index');
ylabel('Amplitude');

subplot(2,1,2);
x=rand(50,1);
plot(x);
title('Noise');
xlabel('Time index');
ylabel('Amplitude');
Lab evaluation points:

Lab instructor Signature: Date:


DSP Lab 03
CONCEPT OF HARMONICS
Write a MATLAB program to find the sum of sinusoidal signals and understand the
concept of harmonics.

MATLAB Code

clc;
clear all;
close all;
t=0:.01:2*pi;
%generation of sine signals%
y1=sin(t);
y2=sin(3*t)/3;
y3=sin(5*t)/5;
y4=sin(7*t)/7;
y5=sin(9*t)/9;

%y = sin(t) + sin(3*t)/3 + sin(5*t)/5 + sin(7*t)/7 + sin(9*t)/9; %

y = y1+y2+y3+y4+y5;
plot (t,y,t,y1,t,y2,t,y3,t,y4,t,y5);
legend ('y','y1','y2','y3','y4','y5');
title ('generation of sum of sinusoidal signals');
grid on;
ylabel ('---> Amplitude');
xlabel ('---> t');

Task
GENERATION OF ELEMENTARY DISCRETE TIME SIGNALS
Write a MATLAB program to develop some elementary discrete time (DT) signals

a. Sinusoidal
b. Square
c. Complex waveform
d. Unit Impulse
e. Unit Step
f. Unit Ramp
g. Exponential

MATLAB Code :

Sinusoidal DT signal
clc;
clear all;
close all;
N = input('Enter Number of Samples : ');
n = 0:0.1:N;
x = sin(n);
stem (n,x);
xlabel ('Time');
ylabel ('Amplitude');
title ('Discrete Time Sine Signal');
grid on;
Square DT signal
clc;
clear all;
close all;
N = input('Enter the number of Samples:‟);
n = 0:0.1:N;
s = square(2*n);
stem (n,s);
xlabel ('time');
ylabel ('amplitude');
title ('square wave')
grid on;

Complex DT signal
clc;
clear all;
close all;
n = 0 : 0.1 : 15;
subplot (2,1,1);
y = [exp((-0.2+2*i)*n)];
stem (n,y,'r');
xlabel ('time');
ylabel ('amplitude');
title ('Discrete Time Complex wave')
grid on;
Unit Impulse DT signal
clc;
clear all;
close all;
N = input('Enter the Number of Samples: ');
n = -N:1:N;
x = [zeros(1,N) 1 zeros(1,N)];
subplot (2,1,1);
stem (n,x,'r');
xlabel ('Time');
ylabel ('Amplitude');
title ('Impulse Response');

Unit Step DT signal


clc;
clear all;
close all;
N = input(' Enter the Number of Samples : ');
n = -N:1:N;
x = [zeros(1,N) 1 ones(1,N)];
subplot (2,1,1);
stem (n,x,'r');
xlabel ('Time');
ylabel ('Amplitude');
title ('Unit Step Response');
grid on;

Unit Ramp DT signal


clc;
clear all;7
close all;
N = input('Enter Number of Samples : ');
a = input('Enter Amplitude : ');
n = 0:1:N;
x = a*n;
subplot (2,1,1);
stem (n,x,'r');
xlabel ('Time');
ylabel ('Amplitude');
title ('Unit Ramp Response');
grid on;

Exponential DT signal
clc;
clear all;
close all;
N = input('Enter Number of Samples : ');
% EXPONENTIAL DECAYING SIGNAL
a = 0.5;
n = 0:.1:N;
x = a.^n;
subplot (2,1,1);
stem (n,x,'r');
xlabel ('Time');
ylabel ('Amplitude');
title ('Exponential Decaying Signal Response');
grid on;
%EXPONENTIAL GROWING SIGNAL
subplot (2,1,2);
x = a.^-n;
stem (n,x,'r');
xlabel ('Time');
ylabel ('Amplitude');
title ('Exponential Growing Signal Response');
grid on;
Lab evaluation points:

Lab instructor Signature: Date:


DSP Lab 04
SAMPLING THEOREM

Write a MATLAB program to verify the Sampling theorem


MATLAB Code:

clear all;
close all;
clc;
tf = 0.05;
t = 0 : 0.00005 : tf;
f = input ('Enter the analog frequency,f = : ');
xt = cos (2*pi*f*t);

% Under Sampling – Sampling Frequency less than Nyquist rate => fs < 2f
fs1 = 1.3*f;
n1 = 0:1/fs1:tf;
xn = cos(2*pi*f*n1);
subplot (3,1,1);
plot (t,xt,'b',n1,xn,'r*-');
title ('Undersampling plot');
xlabel ('time');
ylabel ('Amplitude');

% Nyquist Sampling – Sampling Frequency fs = 2f


fs2 = 2*f;
n2 = 0 : 1/fs2 : tf;
xn = cos(2*pi*f*n2);
subplot (3,1,2);
plot (t,xt,'b',n2,xn,'r*-');
title ('Nyquist plot');
xlabel ('time');
ylabel ('Amplitude');

% Over Sampling – Sampling Frequency greater than Nyquist rate => fs > 2f
fs3 = 6*f;
n3 = 0 : 1/fs3 : tf;
xn = cos(2*pi*f*n3);
subplot (3,1,3);
plot (t,xt,'b',n3,xn,'r*-');
title ('Oversampling plot');
xlabel ('time');
ylabel ('Amplitude');
Lab evaluation points:

Lab instructor Signature: Date:


DSP Lab 05
IMPULSE RESPONSE OF THE LTI SYSTEM
Write a MATLAB program to find the impulse response of a LTI system defined by a
difference equation:

y(n) + 0.7y(n-1) – 0.45y(n-2) – 0.6y(n-3) = 0.8x(n) – 0.44x(n-1) + 0.36x(n-2) + 0.2x(n-3)

MATLAB Code:

clc;
clear all;
close all;
N = input ('Enter the required length of impulse response N = ');
n = 0 : N-1;
b = input ('Enter the co-efficients of x(n), b = ');
a = input ('Enter the co=efficients of y(n), a = ');
% Impulse response of the LTI system given by the difference equation
x = [1, zeros(1,N-1)];
y = impz (b,a,N);
subplot (2,1,1);
stem (n,y,‟r‟);
xlabel ('time');
ylabel ('amplitude');
title ('IMPULSE RESPONSE');
grid on;
% Pole – Zero distribution of the LTI system given by the difference equation
subplot (2,1,2);
zplane (b,a);
xlabel ('Real part');
ylabel ('Imaginary part');
title ('Poles and Zeros of H[z] in Z-plane');
grid;

Output : Enter the required length of impulse response N = 40


Enter the co-efficients of x(n), b = [0.8 -0.44 0.36 0.02]
Enter the co=efficients of y(n), a = [1 0.7 -0.45 -0.6]
Tasks!

Find out the impulse response of the following difference equation and plot the pole-zero response
of the same.
1. 0.25y(n-3) + 0.7y(n-2)+y(n) = 3x(n) – 0.9x(n-1) + 1.3x(n-2)
2. y(n) – y(n-1) = x(n) – x(n-1)

Lab evaluation points:

Lab instructor Signature: Date:


DSP Lab 06
FREQUENCY RESPONSE OF THE LTI SYSTEM
Write a MATLAB program to plot the Frequency response of a given LTI sequence:
y(n) – 5 y(n–1) = x(n) + 4 x(n–1)

MATLAB Code:

b = [1, 4]; %Numerator coefficients


a = [1, -5]; %Denominator coefficients
w = -2*pi: pi/256: 2*pi;

% Frequency Response of the LTI system


[h] = freqz(b, a, w);
subplot(2, 1, 1),
plot(w, abs(h));
xlabel ('Frequency \omega'),
ylabel ('Magnitude');
grid on;

Phase Response of the LTI system


subplot(2, 1, 2),
plot(w, angle(h));
xlabel('Frequency \omega'),
ylabel('Phase - Radians');
grid on;
Tasks !

Find out the frequency response of the following difference equations.


1. 0.25y(n-3) + 0.7y(n-2)+y(n) = 3x(n) – 0.9x(n-1) + 1.3x(n-2)
2. y(n) – y(n-1) = x(n) – x(n-1)

Lab evaluation points:

Lab instructor Signature: Date:


Lab 7
Z –TRANSFORM

The z-transform G(z) of a sequence g[n] is defined as

where z is a complex variable. The set of values of z for which the z-transform G(z) converges is
called its region of convergence (ROC). In general, the region of convergence of a z-transform of
a sequence g[n] is an annular region of the z-plane:

In the case of LTI discrete-time systems, all pertinent z-transforms are rational functions of z−1,
that is, they are ratios of two polynomials in z−1:

which can be alternately written in factored form as

The zeros of G(z) are given by z = ξr while the poles are given by z = λs. There are additional (N
− M) zeros at z = 0 (the origin in the z-plane) if N > M or additional (M − N) poles at z = 0 if N
<M.

For a sequence with a rational z-transform, the ROC of the z-transform cannot contain any poles
and is bounded by the poles.
The inverse z-transform g[n] of a z-transform G(z) is given by

where C is a counterclockwise contour encircling the point z0 in the ROC of G(z).

A rational z-transform G(z) = P(z)/D(z), where the degree of the polynomial P(z) is M and the
degree of the polynomial D(z) is N, and with distinct poles at z =λs, s = 1, 2, . . . , N, can be
expressed in a partial-fraction expansion form given by

Assuming M ≥ N.
The constants ρs in the above expression, called the residues , are given by
Evaluation of z-Transforms on Unit Circle
The function freqz can be used to evaluate the values of a rational z-transform on the unit
circle. The evaluation of Z- Transform on a unit circle leads to the Frequency Response or
Fourier Transform.

Sample Program 1
% Discrete-Time Fourier Transform Computation

% Read in the desired number of frequency samples


k = input('Number of frequency points = ');

% Read in the numerator and denominator coefficients


num = input('Numerator coefficients = ');

den = input('Denominator coefficients = ');

%Compute the frequency response/Evaluate Z transform on unit circle


w = 0:pi/(k-1):pi;
h = freqz(num, den, w);
%Plot the frequency response

subplot(2,2,1)

plot(w/pi,real(h));grid title('Real part')

xlabel('\omega/\pi'); ylabel('Amplitude'); subplot(2,2,2)

plot(w/pi,imag(h));grid title('Imaginary part')

xlabel('\omega/\pi'); ylabel('Amplitude') ;subplot(2,2,3)

plot(w/pi,abs(h));grid title('Magnitude Spectrum')

xlabel('\omega/\pi'); ylabel('Magnitude') ;subplot(2,2,4)

plot(w/pi,angle(h));grid title('Phase Spectrum')

xlabel('\omega/\pi'); ylabel('Phase, radians')

Pole Zero Plot


The pole-zero plot of a rational z-transform G(z) can be readily obtained using the function
zplane. There are two versions of this function. If the z-transform is given in the form of a
rational function , the command to use is zplane(num, den) where num and den are row
vectors containing the coefficients of the numerator and denominator polynomials of G(z) in
ascending powers of z−1. On the other hand, if the zeros and poles of G(z) are given, the
command to use is zplane(zeros, poles) where zeros and poles are column vectors. In the
pole-zero plot generated by MATLAB, the location of a pole is indicated by the symbol × and
the location of a zero is indicated by the symbol.

Rational , Factored Forms of z-transform

The function tf2zp can be used to determine the zeros and poles of a rational z-transform
G(z). The program statement to use is where num and den are
row vectors containing the coefficients of the numerator and denominator polynomials of
G(z) in ascending powers of z−1 and the output file contains the gain constant k and the
computed zeros and poles given as column vectors z and p, respectively. The reverse process
of converting a z-transform given in the form of zeros, poles, and the gain constant to a
rational form can be implemented using the function zp2tf. The program statement to use is

The factored form of the z-transform can be obtained from the zero-pole description using
the function The function computes the coefficients of each
second-order factor given as an L × 6 matrix sos where,

where the Lth row contains the coefficients of the numerator and the denominator of the Lth
second-order factor of the z-transform G(z):

Example
A z-Transform ( ) is given below.

Write a MATLAB program that take two vectors „num‟ & „den‟ that are the numerator and
denominator coefficients. Program should find the following.
a) z-Transform in the factored form
b) Pole and Zero plot
c) Partial fraction expansion of the z-transform

Solution
%Analysis of Z-Transforms
%Definition of numerators and denominator coefficients
num=[5 6 -44 21 32];
den=[5 13 15 18 -12];
%Conversion from rational to Factored form
[z,p,k]=tf2zp(num,den);
disp('Zeros are at');disp(z);
disp('Poles are at');disp(p);
disp('Gain Constant');disp(k); %Determination of radius of the poles radius=abs(p);
disp('Radius of the poles');disp(radius);
%Pole Zero Map using numerator and denominator coefficients
zplane(num,den)
%Conversion from factored to secomd ordered factored
sos=zp2sos(z,p,k)
disp('Second Order Sections');
disp(sos);

Results:
Zeros are at
-3.7346
1.5861 + 0.4153i
1.5861 - 0.4153i
-0.6375

Poles are at
-2.2041
-0.4165 + 1.5225i
-0.4165 - 1.5225i
0.4371

Gain constant
1

Radius of poles
2.2041
1.5784
1.5784
0.4371

Second-order sections
1.0000 4.3721 2.3809 1.0000 1.7670 -0.9633
1.0000 -3.1721 2.6881 1.0000 0.8330 2.4914

Residues
-1.0860 1.4250 - 1.1292i 1.4250 + 1.1292i 1.9028

Poles
-2.2041 -0.4165 - 1.5225i -0.4165 + 1.5225i 0.4371

Constants
-2.6667

Inverse z-Transform
The inverse g[n] of a rational z-transform G(z) can be computed using MATLAB in basically
two different ways. For finding the Inverse z-transform, it is necessary to know a priori the
ROC of G(z).
Inverse z-transform can also be computed by first converting the function to rational form
using partial fraction expansion and then looking in z-transform table.
MATLAB function to compute the partial expansion is
First Method

The function impz provides the samples of the time domain sequence, which is assumed to be
causal. There are three versions of this function:

where num and den are row vectors containing the coefficients of the numerator and
denominator polynomials of G(z) in ascending powers of z−1, L is the desired number of the
samples of the inverse transform, g is the vector containing the samples of the inverse
transform starting with the sample at n = 0, t is the length of g, and FT is the specified
sampling frequency in Hz with default value of unity.

The function can also be used to calculate the input response of a z-


transform. Where num and den represent vectors containing numerator and denominator
coefficients of z-transform.While x represents input to the filter / z-transform .The length of
output y is equal to input x. If an impulse input sequence is passed to the z-transform, the
output will be the inverse z-transform.

Sample Program 2
%Inverse Z-Transform using impz
%definition of numerator and denominator coefficients

num=[0.1+.4*i 5 .05];
den=[1 .9+0.3*i .12];

%Finding the inverse z transform of G(z) [a,b]=impz(num,den);


[a,b]=impz(num,den);
%Evaluating on Unit Circle i.e. Fourier Transform [c,d]=freqz(num,den);
[c,d]=freqz(num,den);
% Plotting of x[n] and it's fourier transform
subplot(2,2,1);
stem(b,real(a)); title('Real Part of g[n]')

xlabel('Samples'); ylabel('Magnitude'); grid on

subplot(2,2,2)

stem(b,imag(a)); title('Imaginary Part of g[n]')

xlabel('Samples');
ylabel('Magnitude'); grid on

subplot(2,2,3)
plot(d/pi,abs(c))

title('Magnitude Spectrum of g[n]');


xlabel('\omega/\pi');
ylabel('Magnitude'); grid on

subplot(2,2,4)

plot(d/pi,angle(c)); title('Phase Spectrum of g[n]')


xlabel('\omega/\pi'); ylabel('Phase in radians'); grid on

Lab evaluation points:

Lab instructor Signature: Date:


DSP Lab 08
LINEAR CONVOLUTION
Write a MATLAB program to compute linear convolution of two given sequences

MATLAB Code:

Linear convolution computation

clear all;
close all;
clc;
x1 = input ('enter the first sequence ');
subplot (2,2,1);
stem (x1,'r');
ylabel ('amplitude');
title ('plot of the first sequence');
grid on;
x2 = input ('enter 2nd sequence ');
subplot (2,2,2);
stem (x2, 'r');
ylabel ('amplitude');
title ('plot of 2nd sequence');
grid on;
f = conv (x1,x2);
disp ('output of linear conv is');
disp (f);
subplot (2,2,3);
stem (f,'r');
xlabel ('time index n');
ylabel ('amplitude f');
title('linear conv of sequence');
grid on;
Lab evaluation points:

Lab instructor Signature: Date:


DSP Lab 09
DISCRETE TIME FOURIER TRANSFORM – DTFT
Write a MATLAB program to find the Discrete Time Fourier Transform (DTFT) of the
given sequence.

MATLAB Program:
% Evaluation of the DTFT
clf;
% Compute the frequency samples of the DTFT
w = -4*pi : 8*pi/511 : 4*pi;
num = [2 1];
den = [1 -0.6];
h = freqz(num, den, w);
% Plot the DTFT
subplot(4,1,1)
plot(w,real(h));
grid on;
title('Real part of H(e^{j\omega})')
xlabel('\omega /\pi');
ylabel('Amplitude');
subplot(4,1,2)
plot(w,imag(h));grid
title('Imaginary part of H(e^{j\omega})')
xlabel('\omega /\pi');
ylabel('Amplitude');
subplot(4,1,3)
plot(w,abs(h));grid
title('Magnitude Spectrum |H(e^{j\omega})|')
xlabel('\omega /\pi');
ylabel('Amplitude');
subplot(4,1,4)
plot(w,angle(h));grid
title('Phase Spectrum arg[H(e^{j\omega})]')
xlabel('\omega /\pi');
ylabel('Phase, radians');
Lab evaluation points:

Lab instructor Signature: Date:


Lab 10
Filters
Finite Impulse Response Filter

Introduction
The goal of filtering is to perform frequency-dependent alteration of a signal. A simple design
specification for a filter might be to remove noise above a certain cutoff frequency. A more
complete specification might call for a specific amount of passband ripple (Rp, in decibels),
stopband attenuation (Rs, in decibels), or transition width (Wp - Ws, in hertz). A precise
specification might ask to achieve the performance goals with the minimum filter order, call
for an arbitrary magnitude response, or require an FIR filter.

Filter Specifications in MATLAB


• Wp - Passband cutoff frequencies (normalized)
• Ws - Stopband cutoff frequencies (normalized)
• Rp - Passband ripple: deviation from maximum gain (dB) in the passband
• Rs - Stopband attenuation: deviation from 0 gain (dB) in the stopband

Window-based finite impulse response filter design


Syntax

Description
fir1 implements the classical method of windowed linear-phase FIR digital filter design. It
designs filters in standard lowpass, highpass, bandpass, and bandstop configurations. By
default the filter is normalized so that the magnitude response of the filter at the center
frequency of the passband is 0 dB.

returns row vector b containing the n+1 coefficients of an order n lowpass


FIR filter. This is a Hamming-window based, linear-phase filter with normalized cutoff
frequency Wn. The output filter coefficients, b, are ordered in descending powers of z.

Wn is a number between 0 and 1, where 1 corresponds to the Nyquist frequency.

If Wn is a two-element vector, fir1 returns a bandpass filter with passband

If Wn is a multi-element vector, fir1 returns an order n


multiband filter with bands , .

By default, the filter is scaled so that the center of the first passband has a magnitude of
exactly 1 after windowing.

specifies a filter type, where ' ' is:


'high' for a highpass filter with cutoff frequency Wn. 'stop' for a bandstop filter, if Wn = [w1
w2]. The stopband frequency range is specified by this interval.

fir1 always uses an even filter order for the highpass and bandstop configurations. This is
because for odd orders, the frequency response at the Nyquist frequency is 0, which is
inappropriate for highpass and bandstop filters. If you specify an odd-valued „n‟ fir1 will
make an increment by 1.

uses the window specified in column vector window for the


design. The vector window must be n+ 1 element long. If no window is specified, fir1 uses a
Hamming window (see hamming) of length n+1.

accepts both 'ftype' and window parameters.

) specifies whether or not the filter magnitude is normalized.


The string 'normalization' can be the following:

'scale' (default): Normalize the filter so that the magnitude response of the filter at the center
frequency of the passband is 0 dB.

'noscale': Do not normalize the filter.

The group delay of the FIR filter designed by fir1 is n/2.

Algorithm
fir1 uses the window method of FIR filter design [1]. If w(n) denotes a window, where
and the impulse response of the ideal filter is h(n), where h(n) is the inverse
Fourier transform of the ideal frequency response, then the windowed digital filter
coefficients are given by

Examples

Design a 48th-order FIR bandpass filter with passband 0.35 = w = 0.65:

Solution:
b = fir1(48,[0.35 0.65]);
freqz(b,1,512)
50

Magnitude (dB) 0

-50

-100
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency ( rad/sample)

1000
Phase (degrees)

-1000

-2000
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency ( rad/sample)

Write a MATLAB program to plot magnitude response and phase response of digital FIR
Filter using Rectangular window
a. Low pass Filter
b. High pass Filter
c. Bandpass Filter
d. Bandstop Filter

LOW PASS FIR Filter Designing

clc;
clear all;
close all;
N=input('Enter the value of N:');
wc=input('Enter cutoff frequency:');
h=fir1(N,wc/pi,rectwin(N+1));
freqz(h);

N=10
F=0.1
0

Magnitude (dB)
-20

-40

-60

-80
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency ( rad/sample)

100
Phase (degrees)

-100

-200
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency ( rad/sample)

HIGH PASS FIR Filter Designing

clc;
clear all;
close all;
N=input('Enter the value of N:');
wc=input('Enter cutoff frequency:');
h=fir1(N,wc/pi, „high‟,rectwin(N+1));
freqz(h);

0
Magnitude (dB)

-2

-4

-6

-8
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency ( rad/sample)

0
Phase (degrees)

-50

-100

-150

-200
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency ( rad/sample)

Band Pass Filtering


clc;
clear all;
close all;
N=input('Enter the value of N:');
wc=input('Enter cutoff frequency:');
h=fir1(N,wc/pi,rectwin(N+1));
freqz(h);

N=28
Frequency = [0.3*pi 0.7*pi]

50
Magnitude (dB)

-50

-100
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency ( rad/sample)

500
Phase (degrees)

-500

-1000

-1500
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency ( rad/sample)

Band stop filtering

clc;
clear all;
close all;
N=input('Enter the value of N:');
wc=input('Enter cutoff frequency:');
h=fir1(N,wc/pi, „stop‟,rectwin(N+1));
freqz(h);
50

Magnitude (dB)
0

-50

-100
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency ( rad/sample)

0
Phase (degrees)

-500

-1000

-1500
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
Normalized Frequency ( rad/sample)

Lab evaluation points:

Lab instructor Signature: Date:


Lab 11
IIR Filters
IIR FILTER DESIGN USING FDATOOL
OBJECTIVES:

 To create a better understanding of the role of poles and zeros in a filter


 To design IIR filters using pole-zero placement method using FDAtool

DISCUSSION:
Infinite Impulse Response (IIR) filters are a special class of digital filters which have poles,
although they may or may not have zeros. The key to the characteristics of IIR filters is, of
course, the location of poles and zeros on the z-plane. Therefore, in this lab, the objective is
to improve your understanding of the role of poles and zeros in a digital filter.

Zeros are the roots of the numerator of the pulse transfer function H(z). A Finite Impulse
Response (FIR) filter always has zeros, but an IIR filter may or may have zeros. As the name
suggests, zeros reduce the strength of the signal. For example, a zero placed at 0 Hz
frequency in a digital filter will attenuate the signal at 0 Hz as it passes through the filter.
Such a filter will have a high pass characteristic since the low frequency will be attenuated by
the zero. This has been illustrated in Figure 2 using FDAtool.

Poles are the roots of the denominator of the pulse transfer function. Whereas an IIR filter
always has poles, an FIR filter never has them. A pole is used to provide amplification to the
signal as it passes through the filter. For example, a pole placed at 0 Hz frequency in a digital
filter will amplify the signal at 0 Hz as it passes through the filter. Such a filter will have a
low pass characteristic since the low frequency will be amplify by the pole. This has been
illustrated in Figure 3.

FDA Tool
Signal Processing Toolbox™ software provides the Filter Design and Analysis tool
(FDATool) that lets you design a filter.

Syntax
fdatool

Description
opens the Filter Design and Analysis Tool (FDATool). Use this tool to

 Design filters
 Analyze filters
 Modify existing filter designs

You may access FDA tool by typing the on command prompt window or
alternatively you go to start menu of MATLAB then Toolboxes then DSP systems and finally
Filter Design and Analysis Tool ( ).
A GUI will be open like as depicted in the following figure.

You are required to implement the following task using FDA Tool.
Task 1
Determine the lowest order of a digital IIR lowpass filter of Butterworth, Type 1 Chebyshev,
Type 2 Chebyshev, and elliptic. The specifications are as follows: sampling rate of 40 kHz,
passband edge frequency of 4 kHz, stopband edge frequency of 8 kHz, passband ripple of 0.5
dB, and a minimum stopband attenuation of 40 dB.

Task 2
Determine the lowest order of a digital IIR highpass filter of Butterworth, Type 1
Chebyshev, Type 2 Chebyshev, and elliptic.. The specifications are as follows: sampling rate
of 3,500 Hz, passband edge frequency of 1,050 Hz, stopband edge frequency of 600 Hz,
passband ripple of 1 dB, and a minimum stopband attenuation of 50 dB.

Task 3
Determine the lowest order of a digital IIR bandstop filter of Butterworth, Type 1 Chebyshev,
Type 2 Chebyshev, and elliptic The specifications are as follows: sampling rate of 12 kHz,
passband edge frequencies at 2.1 kHz and 4.5 kHz, stopband edge frequencies at 2.7 kHz and
3.9 kHz, passband ripple of 0.6 dB, and a minimum stopband attenuation of 45 dB.
Fig. 1: Magnitude response without poles and zeros

Fig. 2: Magnitude response with a zero at DC.

Lab evaluation points:

Lab instructor Signature: Date:

Page 45
Lab 12
Sound Processing in MATLAB

What is digital sound data?

Getting some pre-recorded sound files (digital sound data)

 You will first need the following sound files. Right click on these and choose “Save
Link As…” and put these in a folder and make sure you use the pull down menu
option File
files in your correct working directory.

road.wav
hootie.wav
lunch.au
flute.wav
tenorsax.wav
mutedtrumpet.wav

Loading Sound files into MATLAB

Page 46
 We want to read the digital sound data from the .wav file into an array in our
MATLAB workspace. We can then listen to it, plot it, manipulate, etc. Use the
following command at the MATLAB prompt:

[road,fs]=wavread('road.wav'); % loads “the long and winding road” clip

 The array road now contains the stereo sound data and fs is the sampling
frequency. This data is sampled at the same rate as that on a music CD (fs=44,100
samples/second).

 See the size of road: size(road)

 The left and right channel signals are the two columns of the road array:

left=road(:,1);
right=road(:,2);

 Let‟s plot the left data versus time. Note that the plot will look solid because there
are so many data points and the screen resolution can‟t show them all. This picture
shows you where the signal is strong and weak over time.

time=(1/44100)*length(left);
t=linspace(0,time,length(left));
plot(t,left)
xlabel('time (sec)');
ylabel('relative signal strength')

 Let‟s plot a small portion so you can see some details

time=(1/44100)*2000;
t=linspace(0,time,2000);
plot(t,left(1:2000))
xlabel('time (sec)');
ylabel('relative signal strength')

 Let‟s listen to the data (plug in your headphones). Click on the speaker icon in the
lower right hand corner of your screen to adjust the volume. Enter these commands
below one at a time. Wait until the sound stops from one command before you enter
another sound command!

soundsc(left,fs) % plays left channel as mono

soundsc(right,fs) % plays right channel mono (sound nearly the same)

soundsc(road,fs) % plays stereo (ahhh…)

Page 47
 Another audio format is the .au file format. These files are read in using

[lunch,fs2]=auread('lunch.au');

soundsc(lunch,fs2);

 To save an array as a .wav file, use wavwrite( ). Use auwrite( ) for .au format output.

Let’s Mess With the Signal


(perform digital signal processing)

Reverse Playing

 To play the sound backwards, we simply reverse the order of the numbers in the
arrays. Let‟s experiment with a small array. Type in the following commands:

y=[1;2;3;4;5]
y2=flipud(y)

 Note that flipud stands for flip upside-down which flips your array y and stores the
inverted array in a new array called y2.

 Now let's try it on one of our sound arrays:

left2=flipud(left);
soundsc(left2,fs)

Digital Delay Experiment 1:

 Now let's add an echo to our sound data by adding to each sound sample, the sample
from a previous time:

leftout=left; % set up a new array, same size as old one


N=10000; % delay amount N/44100 seconds
for n=N+1:length(left)
leftout(n)=left(n)+left(n-N); % approximately ¼ second echo
end

 Note that these arrays are large and it may take some time for the processing to be
completed. Compare the input and output by typing the following after the cursor
returns, indicating that the processing is done:

soundsc(left,fs) % original

% Wait until the sound stops before moving to next sound command

Page 48
soundsc(leftout,fs) % signal with new echo

 This program first sets the output to be the input. This is simply a quick way to
initialize the output array to the proper size (makes it operate faster). The loop starts
at n=10001 and goes up to the full length of our array left. The output is the sum of
the input at sample time n plus the input at sample time n-10000 (10000 samples ago,
10000/44100 seconds ago since the samples are spaced by 1/44100 seconds). Try
some different delay amounts.

 Try it in stereo and we will echo left-to-right and right-to-left!

out=road; % set up a new array, same size as old one


N=10000; % delay amount N/44100 seconds
for n=N+1:length(road)
out(n,1)=road(n,1)+road(n-N,2); % echo right-to-left!
out(n,2)=road(n,2)+road(n-N,1); % echo left-to-right!
end

soundsc(road,fs) % original

soundsc(out,fs) % echo

Digital Delay Experiment 2:

 Try the following variation on this theme, which keeps adding to the signal itself
from 1000 samples ago slightly softened (multiplied by 0.8). Note that for this sound
data the samples are spaced by T=1/8192 sec (fs2=8192 samples/sec).

[lunch,fs2]=auread('lunch.au');

out=lunch; % set up a new array, same size as old one


N=1000; % delay amount N/8192 seconds
for n=N+1:length(lunch)
out(n)=.8*out(n-N)+lunch(n); % recursive echo
end

soundsc(out,fs2) % echo

 This echo process is like looking into a mirror and seeing a mirror with a reflection of
the first mirror, etc! The echo goes on forever, but gets slightly quieter each time.

Digital Tone Control

 The following program (or “digital filter”) is designed to soften high frequency
components from the signal (treble). It retains the low frequency components

Page 49
(bass). Applying this digital filter has the same effect as turning down the treble tone
control on your stereo. The design of this code is not so obvious. The Electrical
Engineering students will learn more about this type of frequency selective digital
filtering in ECE334 Discrete Signals and Systems.

[hootie,fs]=wavread('hootie.wav'); % loads Hootie


out=hootie;

for n=2:length(hootie)

out(n,1)=.9*out(n-1,1)+hootie(n,1); % left
out(n,2)=.9*out(n-1,2)+hootie(n,2); % right

end

 Compare the input and output as before. Note that the modified signal sounds
muffled in comparison to the input data. This is because the high frequency
components have been suppressed in the output.

soundsc(hootie,fs) % original

soundsc(out,fs) % low pass filtered

 A small change in our digital filter allows us to boost high frequencies and suppress
low frequencies:

out=hootie;

for n=2:length(hootie)

out(n,1)=hootie(n,1)-hootie(n-1,1); % left
out(n,2)=hootie(n,2)-hootie(n-1,2); % right

end

soundsc(out,fs) % high pass filtered

Changing the Speed

 The sampling frequency fs tells us how much time goes between each sample
(T=1/fs). If we play the song with more or less time between samples than was
originally there when recorded, the speed will seem off, producing interesting
effects...

soundsc(hootie,fs/1.5) % How slow can you go?

Page 50
soundsc(hootie,fs*1.5) % The Chimpmonks!

Removing (Minimizing) Vocals

 In most popular music recordings, the vocal track is the same on the left and right
channels (or very similar). The volume of the various instruments aremore unevenly
distributed between the two channels. Since the voice is the same on both channels,
what would happen if we subtract one channel from the other and listen to the result?

soundsc(left,fs); % Original left channel

soundsc(left-right,fs); % Long and winding road, virtually no vocal

Notice the voice is virtually eliminated…

 Try it with Hootie…

soundsc(hootie(:,1),fs); % Original left channel

soundsc(hootie(:,1)-hootie(:,2),fs); % Hootie, reduced vocal

 You still hear some vocal here because this song uses a stereo reverberation effect
and the echo moves back and forth between left and right channels (like our stereo
delay above). This makes the voice unequal from left to right channels.

Lab evaluation points:

Lab instructor Signature: Date:

Page 51
Lab 13
DIRECT DIGITAL SYNTHESIS USING MATLAB AND C

DIRECT DIGITAL SYNTHESIS USING TMS320C6713 DSK


OBJECTIVES:

To generate a sinusoidal analog output waveform using a table – lookup method.


To illustrate some of the features of CCS for editing source files, building a project,
accessing the code generation tools, and running a program on the C6713 processor.

DISCUSSION:
We will generate a sine wave using C.
CODE
Code for the program in MATLAB

f = 1000; % desired fundamental freq Fs =


8000; % sampling freq

N = Fs/f; % find number of samples within one period n =


0:N-1; % generate time vector for one period

x = sin(2*pi*f/Fs*n) % generate DT signal for LUT


plot(n,x) % check/verify

Code for the program in C

//sine generation with DIP switch control #include

"dsk6713_aic23.h" //codec support

Uint32 fs = DSK6713_AIC23_FREQ_8KHZ; //set sampling rate


#define N 8

short loopindex = 0; //table index short

gain = 10; //gain factor

short sine_table[N]= {0,707,1000,707,0, -707,0,-1000, -707}; //sine values

void main()

Page 52
short currentvalue;

comm_poll(); //init DSK,codec,McBSP

DSK6713_LED_init(); //init LED from BSL

DSK6713_DIP_init(); //init DIP from BSL

while(1) //infinite loop

if(DSK6713_DIP_get(0)==0) //if DIP #0 pressed

DSK6713_LED_toggle(0); //turn LED #0 ON

currentvalue = sine_table[loopindex++];

output_left_sample(currentvalue*gain); //output

if (loopindex==N) loopindex=0; //reset index

else DSK6713_LED_off(0); //else turn LED #0 OFF

} //end of while(1)

printf("");

} //end of main operation

Program Description
The operation of program is as follows. An array, sine_table , of eight 16 - bit signed integers is
declared and initialized to contain eight samples of exactly one cycle of a sinusoid.

1. The program statement while(1) within the function main() creates an infinite loop.
Within that loop, the state of DIP switch #0 is tested and if it is pressed down, LED #0
is switched on and a sample from the lookup table is output.

3. If DIP switch #0 is not pressed down then LED #0 is switched off. As long as DIP
switch #0 is pressed down, sample values read from the array sine_table will be output
and a sinusoidal analog output waveform will be generated via the HEADPHONE
socket.
4. Each time a sample value is read from the array sine_table , multiplied by the value of

Page 53
the variable gain , and written to the codec, the index, loopindex , into the array is
incremented and when its value exceeds the allowable range for the array (
LOOPLENGTH - 1 ), it is reset to zero.

5. Each time the function output_left_sample() , defined in source file C6713dskinit.c , is


called to output a sample value, it waits until the codec, initialized by the function
comm_poll() to output samples at a rate of 8 kHz, is ready for the next sample. In this
way, once DIP switch #0 has been pressed down it will be tested at a rate of 8 kHz. The
sampling rate at which the codec operates is set by the program statement
Uint32 fs = DSK6713_AIC23_FREQ_8KHZ;

6. One cycle of the sinusoidal analog output waveform corresponds to eight output
samples and hence the frequency of the sinusoidal analog output waveform is equal to
the codec sampling rate (8 kHz) divided by eight, that is, 1 kHz.

PROCEDURE

The procedure is specified in the previous labs.

Select File→ Load Program in order to load sine8_LED.out. It should be stored in the folder
“c:\CCStudio_v3.1\MyProjects\sine8_LED\Debug”. Select Debug→ Run. When DIP switch #0
is pressed down, and the pair of headphones connected to the HEADPHONE socket, you should
listen a sine-wave tone.

LAB TASKS:

Lab Task 1:
Changing the Frequency of the Generated Sinusoid

There are several different ways in which the frequency of the sinusoid generated by
program sine8_LED.c can be altered.

Change the AIC23 codec sampling frequency from 8 kHz to 16 kHz by changing the line that
reads Uint32 fs = DSK6713_AIC23_FREQ_8KHZ; to read Uint32 fs =
DSK6713_AIC23_FREQ_16KHZ; Rebuild (use incremental build) the project, load and run the
new executable file,

How much should be the frequency of the generated sinusoid?

Lab Task 2:

Page 54
Change the number of samples stored in the lookup table to four. By changing the lines that read

#define LOOPLENGTH 8

short sine_table[LOOPLENGTH]={0,707,1000,707,0, -707,0,-1000, -707};


to read
#define LOOPLENGTH 4
short sine_table[LOOPLENGTH]={0,1000,0, -1000};

How much should be the frequency of the generated sinusoid (assuming an 8 -


kHz sampling frequency)?

Lab evaluation points:

Lab instructor Signature: Date:

Page 55
Lab 14
Introduction to Digital Image Processing/ Operations on Images
Lab Objectives:
This objective of this lab is to understand
 How to read an image in MATLAB.
 How to show an image in MATLAB.
 How to access Image Pixels in MATLAB.
 How to write Image in MATLAB.
 How to convert an image to gray scale or binary image in MATLAB
Reading an Image
To import an image from any supported graphics image file format, in any of the supported bit
depths, use the imread function.

Syntax
𝐴= (“ . ”)

Description
𝐴 reads a greyscale or color image from the file specified by the
string filename, where the string fmt specifies the format of the file. If the file is not in the
current directory or in a directory in the MATLAB path, specify the full pathname of the location
on your system.

Display an Image
To display an iamge, use the “imshow” function.

Syntax
𝐴

Description
𝐴 displays the image stored in array A.

Writing Image Data


function is used to write image data to graphics file

Syntax
𝐴

Example:
a=imread('pout.tif');

Page 56
imwrite(a,gray(256),'b.bmp');
imshow('b.bmp')% imshow is used to display image

How to get number of rows and columns of image


Function size gives the rows and columns dimension of image
[r,c]=size(a)
Accessing the Pixel data
There is a one-to-one correspondence between pixel coordinates and the coordinates MATLAB®
uses for matrix subscripting. This correspondence makes the relationship between an image's
data matrix and the way the image is displayed easy to understand. For example, the data for the
pixel in the fifth row, second column is stored in the matrix element (5,2). You use normal
MATLAB matrix subscripting to access values of individual pixels. For example, the MATLAB
code 𝐴 will return the value of the pixel at row 2, column 15 of the image A.

Image conversion from color to gray scale


To convert the image from color to gray scale function rgb2gray is used.

Syntax

Description
Colored image is a three dimensional entity. There are three matrix of a color image each for
gray value of specific color (red, green and blue). Function rgb2gary converts three dimensional
images to two dimensional gray images. Gray images have single gray level values and defined
with single matrix.

Image conversion to binary image


To convert an image (color or gray scale) to binary image function rgb2gray is used.

Syntax

Description
Color and gray scale images has range of values for a pixel but in binary image a pixel may have
one of the two values i.e. black or white. Function im2bw use thru-holding to convert the gray
value/values of a pixel to binary value.
Lab evaluation points:

Lab instructor Signature: Date:

Page 57

You might also like