0% found this document useful (0 votes)
26 views

DIP Lab Manual 6IT4-21 Digital Image Processing Lab

The document is a lab manual for a Digital Image Processing Lab course at Jaipur Engineering College, focusing on familiarizing students with MATLAB. It covers essential topics such as the MATLAB workspace, variable manipulation, plotting tools, and basic matrix operations. The manual includes examples of commands, functions, and operations to be performed in MATLAB, along with references for further learning.

Uploaded by

tanishq7821
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)
26 views

DIP Lab Manual 6IT4-21 Digital Image Processing Lab

The document is a lab manual for a Digital Image Processing Lab course at Jaipur Engineering College, focusing on familiarizing students with MATLAB. It covers essential topics such as the MATLAB workspace, variable manipulation, plotting tools, and basic matrix operations. The manual includes examples of commands, functions, and operations to be performed in MATLAB, along with references for further learning.

Uploaded by

tanishq7821
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/ 58

JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE

JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Course ID: 6IT4-21


Course Title: Digital Image Processing Lab
LAB MANUAL – 1

Objective:

The objective of this lab session is to getting familiar with MATLAB. This will cover the
following topics –
1) MATLAB workspace, Command Window, Variable panel
2) Working with variables, vectors and function
3) Working with library functions.
4) Getting started with MATLAB plotting tools.

Software: MATLAB (any version higher than 2009a)

Pre-requisite: Vector, Matrix, Linear Algebra, Geometry, C, C++.

References:

[1] https://www.mathworks.com/help/matlab/learn_matlab/desktop.html
[2] https://www.mathworks.com/help/matlab/elementary-math.html
[3] https://www.mathworks.com/help/matlab/learn_matlab/matrices-and-arrays.html
[4] https://www.mathworks.com/help/matlab/functionlist.html?s_cid=doc_ftr
[5] https://www.mathworks.com/help/matlab/2-and-3d-plots.html

Page | 1
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Figure 1

The desktop includes these panels (Figure 1): [1]

• Current Folder — Access your files.


• Command Window — Enter commands at the command line, indicated by the prompt
(>>).
• Workspace — Explore data that you create or import from files.

Variables and the workspace:

Let’s start with variable.

a=2

After entering, the immediate next line will display the variable with the assigned value.

a=

And you can see that, the variable is appeared in the workplace (Figure 2 a). If you double click
on that variable icon, a panel named ‘Variables’ will popup (Figure 2 b).
Page | 2
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

MATLAB stores everything as matrix. You can note the indication of 1 x 1 double in the variable
panel. It mean a is a 1 by 1 matrix (eventually a matrix with only one element), which is double
type. By default any numerical data is double type. There are other data types as well such as uint8
(unsigned integer 8 bit), char(character), logical(boolean).

(a)

(b)
Figure
2

Note that, throughout this manual, to make it more readable, we will highlight the commands, and
the prompted output will not be highlighted. For example, the following is a command.

b=3
And the following is the immediate prompt.

b=
3

Let’s start with type casting.


Page | 3
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

a = 1a
=
1

d = logical(a)d =
1

You can see that, dwill be stored as 1 x 1 logicalvariable in the workspace.

Now, Let’s work more with variables and arithmetic operations. Let’s play with some simple
arithmetic operations. Assume that we have already have aand bin our workspace.

a+b
ans =
5

Observe that, ansis a default variable that stores the result of a + b, and it is stored in workspace.
If you simply use ansas a command, the value inside answill be prompted.

ans
ans =
5

But, we can store the result in a different variable as well.

c = a + bc =
5

c = a * bc =
6

c = b^3 % power of 3

Page | 4
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

c = 27
You can observe that, % is used for commenting in
MATLAB. There are some special variables.

pi ans
=
3.1416

c = a*pic =
6.2832

Some library functions:

Some useful library functions for trigonometric operations are shown below.

c = cos(30) % take radian as inputc =


0.1543

c = cos(2*pi)c =
1

c = cosd(30) % take degree as inputc =


0.8660

acosd(c) % inverse cosine (in degree)ans =


30.0000

You can also try sin(), tan()etc.

Page | 5
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Some other important functions are provided below.

c = mod(10,3) % remainderc =
1

c = exp(2) % exponentialc =
7.3891

d = ceil(c) % ceiling (there is floor() and round() as well)d =


8

c = log(10) %natural logarithmc =


2.3026

c = log10(10) % 10 base logarithmc =


1

There is a huge collection of functions dedicated for elementary math. You can find them here [1].

Let’s see some other useful command.


• pwd : to print the current directory
• clc : to clean command prompt history
• clear : to delete all the variables from the workspace. You can delete a particular
variable from the workspace by the clear command followed by the variable name. For
example,
clear c

Page | 6
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Using / not using semicolon:

Semicolons (;) can be used after each command. If used, the output prompt will be suppressed. For
example, if you use the following command without a semicolon at the end, the output will be
prompted.

d = cos(pi)d =
-1

But, if you use the following command with a semicolon at the end, the output will not be
prompted.

d = cos(pi);

Working with vector and


matrix:

Defining a row vector –

v = [1, 2, 3, 4]

v=

1 2 3 4

You can also omit the commas (,) in between the elements. This will give you the same vector.

v = [1 2 3 4]

v=

1 2 3 4

We are going to follow this approach throughout this


manual. Now, Defining a column vector –
v = [1; 2; 3; 4]

v=

1
2
3
4

Page | 7
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Having the idea of row and column vector, now we can easily define a matrix –

M = [1 2 3 4; 5 6 7 8; 9 1 2 3]

M=
1 2 3 4
5 6 7 8
9 1 2 3

In MATLAB, the matrix element indices start from the top left corner. As we traverse right,
we go through each column. And as we traverse down, we go through each row.

1st column 4th column


| |
1st ˅ ˅
row -> 1 2 3 4
3rd 5 6 7 8
row -> 9 1 2 3

Accessing elements of a matrix:

Now let’s see how to access elements from a matrix. To access we use the following format of the
command: Matrix (which_row, which_column). For example, Let’s assume that we have matrix
M in our workspace.

m = M(1,1) % accessing 1st row, 1st column from Mm =


1

m = M(2,3) % accessing 2nd row, 3rd column from Mm =


7
You can use endto access the last element in a row or column.

M(1, end) % 1st row, last columnans =


4

Page | 8
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

M(end, end) % last row, last columnans =


3

Assigning elements of a
matrix:

M(2,2) = 99

M=
1 2 3 4
5 99 7 8
9 1 2 3

Some library functions to generate matrix:

eye(m) : Generating an identity matrix, For example, for m = 5

I = eye(5) % identity matrix of 5 x 5

I=
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

ones(m) : Generating a matrix that contains only 1 (one). For example, m = 5

I = ones(5)I =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

You can also generate matrix rather than square shape. You can use ones(m,n) to define rows
and columns. For example,

Page | 9
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

I = ones(3,5) % 3 rows and 4 columnsI =


1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Similarly,

I = zeros(3,5)

I=
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

I = rand(3,5)I =
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
0.1270 0.0975 0.9575 0.9706 0.8003

I = ceil(rand(3,2))

I=
1 1
1 1
1 1

Let’s apply matrix operations of two matrices A


and B.A = [1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9

B = [9 8 7; 6 5 4; 3 2 1]

Page | 10
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

B=
9 8 7
6 5 4
3 2 1

C = A + BC
=
10 10 10
10 10 10
10 10 10

C=A-B

C=

-8 -6 -4
-2 0 2
4 6 8

C = A * BC
=
30 24 18
84 69 54
138 114 90

C = 2*A
C=
2 4 6
8 10 12
14 16 18

C = A^2
C=
30 36 42
66 81 96
102 126 150

Q.1: Now, can you generate a matrix with random numbers greater than or equal to 1 using one
single line of command?

Page | 11
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

We can apply element wise operations. To perform that, we need to put a dot(.) in front of the
operator. For example, the following command will do element wise multiplication, that means 1st
element of A will be multiplied with the 1st element of B, 2nd of A will be multiplied with 2nd
element of B, and so on.

C = A .* B

C=
9 16 21
24 25 24
21 16 9

Q.2: Now, can you square every element of the matrix A using one single line of command?

Q.3: Also, can you square each elements of both A and B, add the squared elements of A
with the squared elements B and store them in the matrix C? (Again, using one single line of
command)

Using colon operator:

Let’s take the matrix A in previous examples.

A = [1 2 3; 4 5 6; 7 8 9]

A=
1 2 3
4 5 6
7 8 9

Say, we want to access all the columns at 1st row, that is 1, 2 and 3
c1 = A(1,:)
c1 =

1 2 3

Moreover,

c1 = A(2,:) % 2nd row, all columnsc1 =


4 5 6

Similarly, to get all rows at 3rd columns -


Page | 12
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

r1 = A(:,3)

r1 =

3
6
9
We can use colon operator to convert a matrix into a column vector.

v = A(:)

v=
1
4
7
2
5
8
3
6
9
Colon operator is very useful to access a range of elements from a matrix. To give an example,
let’s take a bigger matrix.

R = floor(rand(7)*10)

R=
1 5 0 4 1 0 0
2 9 0 0 6 2 4
6 2 5 3 2 9 1
4 7 7 1 6 1 9
3 7 9 7 6 8 0
8 3 1 3 7 5 7
5 5 5 5 4 9 8

Say, we want to access 2nd row to 5th row of 1st column.

s = R(2:5, 1)

s=

2
6
4
3
Page | 13
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Similarly,

s = R(1, 2:5) % column 2 to 5 of row 1s =


5 0 4 1

We can crop a region using the same concept. For example, row 2 to 5 and column 3 to 6.

S = R(2:5, 3:6)

S=
0 0 6 2
5 3 2 9
7 1 6 1
9 7 6 8

For better understanding, the elements of Saccessed from Rare gray-shaded below.

1 5 0 4 1 0 0
2 9 0 0 6 2 4
6 2 5 3 2 9 1
4 7 7 1 6 1 9
3 7 9 7 6 8 0
8 3 1 3 7 5 7
5 5 5 5 4 9 8

We can assign as well.

R(2:5, 3:6) = 99

R=
1 5 0 4 1 0 0
2 9 99 99 99 99 4
6 2 99 99 99 99 1
4 7 99 99 99 99 9
3 7 99 99 99 99 0
8 3 1 3 7 5 7
5 5 5 5 4 9 8

The colon operator is useful to generate a range of values. Say, we want to create a vector named
data
with values from 1 to 10.

data = 1:10
Page | 14
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

data =

1 2 3 4 5 6 7 8 9 10

data = 1:2:10 % increment by 2 stepsdata =


1 3 5 7 9

Q.4: Can you generate a vector containing 10 values stating from pi to 2*pi with equal steps in
between?

Some library function for matrix/ vector:

Transpose of Vector:

t = transpose(data)t =
1
3
5
7
9

Same thing can be done using a single quote (‘) operator.

t = data't =
1
3
5
7
9

Sorting a vector:

t = sort(data)

Page | 15
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

t=

1 3 5 7 9

Many MATLAB functions can be overloaded.

t = sort(data, 'descend')t =

9 7 5 3 1

Sum of all the elements of a vector:

k = sum(data)k =
25

Mean, median:

k = mean(data)k =
4.1429

k = median(data)k =
4

Transpose of Matrixr:

R = floor(rand(5)*10)

R=
2 2 3 5 7
6 7 4 3 0
6 2 6 4 6
1 8 8 7 4
4 8 6 8 4

r = R'

Page | 16
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

r=
2 6 6 1 4
2 7 2 8 8
3 4 6 8 6
5 3 4 7 8
7 0 6 4 4

Sorting a Matrix:

R = floor(rand(5)*10)

R=
8 4 1 8 0
0 9 8 6 2
3 1 5 3 1
2 2 5 5 1
8 1 1 4 2

By default, MATLAB sorts row-wise. That means it treats every column as an


individual vector and sort them.

s = sort(R)s =
0 1 1 3 0
2 1 1 4 1
3 2 5 5 1
8 4 5 6 2
8 9 8 8 2

However, if you want to perform colum-wise, just pass 2 as parameter.

s = sort(R,2)

s=
0 1 4 8 8
0 2 6 8 9
1 1 3 3 5
1 2 2 5 5
1 1 2 4 8

This concept works for other functions as well.

Page | 17
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Sum of Matrix:

k = sum(R) % row-wisek =
21 17 20 26 6

k = sum(R,2) % column-wisek =
21
25
13
15
16

k = sum(R(:)) %sum of all the values.k =


90

Mean of Matrix:

k = mean(R) % row-wisek =
4.2000 3.4000 4.0000 5.2000 1.2000

k = mean(R,2) % column-wisek =
4.2000
5.0000
2.6000
3.0000
3.2000

k = mean(R(:))% mean of allk =


3.6000

Page | 18
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

More functions can be found here [4].

Plotting:

Assume that, we want to plot five 2-D points. The (x, y)coordinates are (-5, -2), (6, 4),(8, -3), (9,
5) and (-1, 1). Now, let’s store this coordinate data in two vectors X and Y, where X contains all
x-coordinates and Y contains all the y-coordinates.

X = [-5 6 8 9 -1];

Y = [-2 4 -3 5 1];

To plot them, we can simply call the plot()function.

Plot(X,Y,’*’)

A window will pop up (Figure 3) showing the axis and the plotted points. Points will be plotted
with (*)as we pass this as the third parameter. These are called markers. You can use ‘.’, ‘O’, ‘o’,
‘X’,‘x’etc. as markers.
Note that, MATLAB plotting axis system follows the conventional Cartesian coordinates (Figure 4).

Figure 3

Page | 19
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Figure 4

Let’s plot y = x3equation. We define 50 points for x. Then obtain the y from y = x3equation
(Figure 5).

x = 1:50;

y = x.^3;
plot(x,y,'.')

Figure 5

Page | 20
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

We can connect the points by passing different parameter.

plot(x,y,'.-')

A hyphen after the dot means to connect the dots with a continuous line
(Figure 6). You can also change the colors of the markers.
plot(x,y,'.-r') % r stands for red.

Figure 6

MATLAB allows you to redraw on a current figure. Say, we want to plot y = (x+10)3along with
the y
= x3. That means you want to plot on top each other. In that case, we use hold oncommand to let
the figure window wait for next plotting.

x = 1:50;

y = x.^3;

plot(x,y,'.-b'); % plotting the first equationhold on; % holding


the figure to wait.

Page | 21
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

y = (x+10).^3; % deriving the y for the second equationplot(x,y,'.-r'); %


plotting the first equation
hold off; % do not wait any more

See output in figure 7a. You can introduce grid lines on the current figure (Figure 7b). To do
this, keep the current figure opened and enter the command –

grid on;

(a)

(b)
Page | 22
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Figure 7

Also, you can have multiple figures for multiple plotting. Say, we want the previous two
equations to be plotted in two different figure windows. In that case, enter figure command to
open a new figure (Figure 8).

x = 1:50;

y = x.^3;

figure; % new window


plot(x,y,'.-b');
y = (x+10).^3;

figure; % new window


plot(x,y,'.-r');

Figure
8 Another useful plotting function is bar(). For
example,
bar(x, y)

Figure 9 shows the output.

Page | 23
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Figure
9 More about MATLAB plotting is available here
[5].

[END]

Page | 24
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Course Title: Digital Image Processing Lab


LAB MANUAL – 2

Objective:

The objective of this lab session is to getting familiar with MATLAB and Image Processing
Toolbox. This will cover the following topics –
1) MATLAB scripts, m-files
2) Control statements, functions
3) Introduction to Image Processing Toolbox.

Software: MATLAB (any version higher than 2009a)

Pre-requisite: Basic on MATLAB, Fundamental concept of digital images, C/ C++.

Getting started with m-File:

Create a text file with .m extension. Now you can put multiple commands inside of this file and
run.

Page | 1
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Control Statements:

Sample code - 1:

A = floor(rand(5,5)*10);B =
ones(5,5)*9;
C = A + B;

[row, col] = size(C); % size() returns the dimension of a matrixD = zeros(row, col);

for i = 1:row
for j = 1:col

if i==j
D(i,j) = (C(i,j));
end

end
end

disp(D) %disp() prints a variable in command

Sample Code-2:

Sample code -1 can be done easily without control statements.

%% Same task is done without loop + if


A = floor(rand(5,5)*10);B =
ones(5,5)*9;
C = A + B;

[row, col] = size(C);

I = eye(row, col);

D = C.*I;

disp(D)

Page | 2
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Getting started with image processing toolbox:

It is convenient to keep the m-script and the image you want to work with in the same
directory. Let’s say we have cameraman.png in the same directory.

Now we will go quickly over the basic commands to get started with image processing.

I = imread('cameraman.png');

I will contain the matrix of the image. In workspace, you should see variable I with 256 x 256
unit8. That means, the image has 256 rows and 256 columns and every pixel occupies a space of
unsigned 8 bit integer. You can double click on the variable and open the Variable panel. Here,
every element is a pixel. Observe that every pixel’s intensity is in [0 -255] as there are 8 bits
assigned.

We can access pixel values just the way have access matrix eleements.

pix = I(1,1); % pixel values at (1,1)

Now,

figure; imshow(I); % it will display the image

Now let’s dig more. Try to understand the following code.

I = imread('cameraman.png');

figure; imshow(I);

[row, col] = size(I);

K = uint8(ones(row, col));

for i = 1:row
for j = 1:col
K(j,i) = I(i,j);
end
end

figure; imshow(K);

Q.1: By the way, can you do the same without a loop?

Moreover, you can write a matrix as an image formation on to you disk. For example, if we want
to save the matrix Kas an image named modified.jpg, we can use the following command.

imwrite(K, 'modified.jpg');
Page | 3
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

The image will be written on to the current


directory. There are other commands that can be
helpful.
imfinfo() :retrieve the image information
imtool(): open GUI to explore the image

R,G,B channels:

Luckily the provide cameraman.pngis a gray image. But real images are color image. In gray
image, every pixel has one value [0 - 255]. In color image, every pixel has 3 values (R, G, B) and
every one of these has the range [0 - 255].

Let’s work with a color image.

I = imread('peppers_color.jpg');

Now, in workspace you will see 512 x 512 x 3 unint8. We know the meaning, only change is –
there is a 3rd dimension which stands for R,G,B. In MATLAB, red channel is 1, green channel
is 2, and blue channel is 3.

It will be more clear if we access a pixel value. Say, we use the command –

r = I(10, 10, 1);


g = I(10, 10, 2);
b = I(10, 10, 3);

Here, rwill have the value at the row # 10, column # 10, in color channel # 1 (that means red).
gwill have the value at the row # 10, column # 10, in color channel # 2 (that means green).
bwill have the value at the row # 10, column # 10, in color channel # 3 (that means blue).

Q.2: Now, using three lines of code, can you store all the red values, all the green values and all
the blue values in three separate matrices say – R, G and B? And plot display them separately?
Hints- the colon operator can be helpful here.

[END]

Page | 4
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

LABORATORY MANUAL

(Manual -3)

6IT4-21: Digital Image Processing Lab


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Introduction to Digital Image Processing and MATLAB

OBJECTIVES:
The objective of this lab session is
• Introduction of MATLAB
– MATLAB workspace, Command Window, Variable panel
– Working with variables, vectors and function
– Working with library functions.
• Image processing with MATLAB
– 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.
– Mirror Image generation.
– Flipped Image generation.

WHAT IS MATLAB?:
• MATLAB = Matrix Laboratory
• “MATLAB is a high-level language and interactive environment that enables you to perform
computationally inten- sive tasks faster than with traditional programming languages such as C,
C++ and Fortran.”(www.mathworks.com)
• MATLAB is an interactive, interpreted language that is designed for fast numerical matrix calculations

THE MATLAB ENVIRONMENT:


The Figure 1.1 shows the MATLAB window components:

Workspace Displays all the defined variables


Command Window To execute commands in the MATLAB environment
Command History Displays record of the commands used
File Editor Window Define your functions
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Figure 1.1: MATLAB Environment

Figure 1.2: Workspace


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Figure 1.3: Variables

WORKSPACE AND VARIABLES: :


Let’s start with variable, a = 2. After entering, the next line will display the variable with the assigned value.

a=2

And you can see that, the variable is appeared in the workplace (as in Figure 1.2). If you double click
on that variable icon, a panel named ‘Variables’ will popup (as in Figure 1.3).

MATLAB stores everything as matrix. You can note the indication of 1 × 1 double in the variable
panel. It mean a is a 1 by 1 matrix (eventually a matrix with only one element), which is double type.
By default any numerical data is double type. There are other data types as well such as uint8(unsigned
integer 8 bit), char (character), logical (boolean).

WORKING WITH VECTOR AND MATRIX:


In MATLAB, the matrix element indices start from the top left corner. As we traverse right, we go
through each column. And as we traverse down, we go through each row.

How to build a matrix?


A = [1 2 3; 4 5 6; 7 8 9];
Creates matrix A of size
3×3

Special matrices zeros(n,m),ones(n,m),rand()

Basic Operations on Matrices All operators in MATLAB are defined on matrices: +, −, ∗, ÷, ˆ,


sqrt, sin,cos, etc.
Element-wise operators are defined with a preceding dot: .∗, ./, .ˆ

Matrix Functions size(A) – size vector, sum(A) – columns sums vector, sum(sum(A)) – sum of all
the ele- ments.

Accessing elements of a matrix To access we use the following format of the command: Matrix
(which row,which column).

Assigning elements of a
matrix M (2, 2) =
99

M=
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

1 2 3 4
5 99 7 8
9 1 2 3

Question 1. Now, can you generate a matrix with random numbers greater than or equal to 1 using
one single line of command?
You can apply element wise operations. To perform that, we need to put a dot(.) in front of the
operator. For example, the following command will do element wise multiplication, that means 1st
element of A will be multiplied with the 1st element of B, 2nd of A will be multiplied with 2nd
element of B, and so on.

C = A. ∗ B
C=

9 16 21
24 25 24
21 16 9

Question 2. Now, can you square every element of the matrix A using one single line of command?

Question 3. Also, can you square each elements of both A and B, add the squared elements of A with
the squared elements B and store them in the matrix C? (Again, using one single line of command)

HOW TO DISPLAY AN IMAGE? :


To display image, use the imshow function.

Syntax imshow(A)

Description imshow(A) displays the image stored in array A.

HOW TO WRITE AN IMAGE DATA?:


Use Imwrite to write image to graphics file

Syntax imwrite(A,filename,fmt)

Example Program-code 1.1 shows how to write an image file. Figure 1.4 shows
the output.
1 a= i m re ad ( ’ p ou t . tif ’) ;
i m w r i t e ( a , gr ay ( 2 5 6 ) , ’ b . bmp ’ ) ;
2 imshow ( ’ b . bmp ’ )% imshow i s used to display image

Program 1.1: Writing image to disk uses for matrix sub-

ACCESSING THE PIXEL DATA:


There is a one-to-one correspondence between pixel coordinates and the
coordinates MATLABⓍ R

scripting. 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
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

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
A(2, 15)

returns the value of the pixel at row 2, column 15 of the image A.


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Figure 1.4: Writing image to disk file

MIRROR IMAGE GENERATION:

7 for j =c : −1: 1

1
1 k=k + 1 ;
2 end
13 end
4

15

Program 1.2: Mirror Image Generation


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Figure 1.5: Source Image and Mirrored Output

Task 1. Write a MATLAB code that reads a gray scale image and generates the flipped image of
original image. Your output should be like the one given in Figure 1.6.

Task 2. Write a MATLAB code that will do the following:


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Figure 1.6: Source Image with Desired Output

1. Read any gray scale image.

2. Display that image.

3. Again display the image such that the pixels having intensity values below than 50 will display
as black and pixels having intensity values above than 150 will display as white. And the pixels
between these will display as it is.

REFERENCES:
• https://www.mathworks.com/help/matlab/learn matlab/desktop.html
• https://www.mathworks.com/help/matlab/elementary-math.html
• https://www.mathworks.com/help/matlab/learn matlab/matrices-and-arrays.html
• https://www.mathworks.com/help/matlab/functionlist.html?s cid=doc ftr
• https://www.mathworks.com/help/matlab/2-and-3d-plots.html
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

DIGITAL IMAGE PROCESSING LAB


MANUAL

1. Simulation and Display of an Image, Negative of an Image(Binary & Gray Scale)


2. Implementation of Relationships between Pixels
3. Implementation of Transformations of an Image
4. Contrast stretching of a low contrast image, Histogram, and Histogram Equalization
5. Display of bit planes of an Image
6. Display of FFT(1-D & 2-D) of an image
7. Computation of Mean, Standard Deviation, Correlation coefficient of the given Image
8. Implementation of Image Smoothening Filters(Mean and Median filtering of an Image)
9. Implementation of image sharpening filters and Edge Detection using Gradient Filters
10. Implementation of Image Intensity slicing technique for image enhancement
11. Canny edge detection Algorithm
12. To count the number of connected object in a given image using morphological operations.
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

1. Simulation and Display of an Image, Negative of an Image(Binary & Gray Scale)


% Red Blue and Green and Gray Components
i=imread('cancercell.jpg');
subplot(3,2,1); imshow(i); title('Original Image');

%Red Component
r=i(:,:,1);
subplot(3,2,2); imshow(r);title('Red Component');

%Green Component
g=i(:,:,2);
subplot(3,2,3); imshow(g); title('Green Component');

%Blue Component
b=i(:,:,3);
subplot(3,2,4); imshow(b); title('Blue Component');

%Color to Gray Image


rg=rgb2gray(i);
subplot(3,2,5); imshow(rg); title('Gray Image');
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

Complement, Converting and Simulation of an Image


JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

% Display color Image, find its complement and convert to gray scale
I=imread('cancercell.jpg');
subplot(2,2,1); imshow(I); subimage(I); title('Color Image');

c=imcomplement(I);
subplot(2,2,2); imshow(c); subimage(c); title('Complement of color Image');

r=rgb2gray(I);
subplot(2,2,3); imshow(r); subimage(r); title('Gray scale of color Image');

%Complement of Gray Image


b=imcomplement(r);
subplot(2,2,4); imshow(b); subimage(b); title('Complement of Gray Image');

%Simulation of an Image( Arithmetic & Logic Operation)


a=ones(40); b=zeros(40);
c=[a b;b a]; d=[b b;a a];
A=10*(c+d);
M=c.*d
; S=c-d;
D=c/4;
figure;
subplot(3,2,1); imshow(c);
subplot(3,2,2); imshow(d);
subplot(3,2,3); imshow(A);
subplot(3,2,4); imshow(M);
subplot(3,2,5); imshow(S);
subplot(3,2,6); imshow(D);
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

2. Implementation of Relationships between Pixels

Neighbour of 4,8 and Diagonal point


% To find Neighbour of a given Pixel

a=magic(5);
disp(‘a=’); disp(a);
b=input('Enter the row < size of the Matrix');
c=input(' Enter the Column < size of matrix');
disp(‘Element’); disp(a(b,c));

% 4 Point Neighbour
N4=[a(b+1,c), a(b-1,c), a(b,c+1), a(b,c-1)];
disp(‘N4=’); disp(N4);

%8 Point Neighbour
N8=[a(b+1,c), a(b-1,c), a(b,c+1), a(b,c-1), a(b+1,c+1), a(b+1,c-1), a(b-1,c-1), a(b-1,c+1)];
disp(‘N8=’); disp(N8);

%Diagonal Neighbour
ND=[ a(b+1,c+1), a(b+1,c-1), a(b-1,c-1), a(b-1,c+1)];
disp(‘ND=’); disp(ND);

Output
a=
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

Enter the row < size of the Matrix 3


Enter the Column < size of matrix 3
Element =
13
N4=
19 7 20 6
N8=
19 7 20 6 21 12 5 14
ND
=
21 12 5 14
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

3. Implementation of Transformations of an Image


%Scaling & Rotation

% Scaling (Resize)
I=imread('earcell.jpg');
subplot(2,2,1); subimage(I); title('Original Image');

s=input('Enter Scaling Factor');


j=imresize(I,s);
subplot(2,2,2); subimage(j); title('Scaled Image');

% Rotation
K=imrotate(j,60);
subplot(2,2,3); imshow(K); title('Rotated Image 60deg');

R=imrotate(j,45);
subplot(2,2,4); imshow(R); title('Rotated Image 45deg');
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

%Display the color image and its Resized images by different methods

%Display the color


image
I=imread('embryo.jpg');
figure,
subplot(2,2,1);
subimage(I);
title('Original Image');

%Display Resized image by Bilinear method


B=imresize(I,5);
subplot(2,2,2);
subimage(B);
title('Bilinear Image');

%Display Resized image by Nearest method


C=imresize(I,5,'nearest');
subplot(2,2,3);
subimage(C);
title('Nearest Image');

%Display Resized image by Bicubic method


D=imresize(I,5,'Bicubic');
subplot(2,2,4); subimage(D);
title('Bicubic Image');
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

4. Contrast stretching of a low contrast image, Histogram, and Histogram Equalization

% Image Enhancement
I=imread('cancercell.jpg');
subplot(4,2,1); imshow(I); title('Original Image');

g=rgb2gray(I);
subplot(4,2,5); imshow(g); title('Gray Image');

J=imadjust(g,[0.3 0.7],[]);
subplot(4,2,3); imshow(J); title('Enhanced Image');

D= imadjust(I,[0.2 0.3 0; 0.6 0.7 1],[]);


subplot(4,2,4);imshow(D);title('Enhanced Image 2');

% Histogram and Histogram Equalization


subplot(4,2,7); imhist(g); title('Histogram of Gray Image');

m=histeq(g);
subplot(4,2,6); imshow(m); title('Equalized Image');
subplot(4,2,8); imhist(m); title('Histogram of Equalized Image');
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

5. Display of bit planes of an Image

i=imread('earcell.jpg');
b0=double(bitget(i,1));
b1=double(bitget(i,2));
b2=double(bitget(i,3));
b3=double(bitget(i,4));
b4=double(bitget(i,5));
b5=double(bitget(i,6));
b6=double(bitget(i,7));
b7=double(bitget(i,8));

subplot(3,3,1);imshow(i);title('Original Image');
subplot(3,3,2);subimage(b0);title('BIT PLANE 0');
subplot(3,3,3);subimage(b1);title('BIT PLANE 1');
subplot(3,3,4);subimage(b2);title('BIT PLANE 2');
subplot(3,3,5);subimage(b3);title('BIT PLANE 3');
subplot(3,3,6);subimage(b4);title('BIT PLANE 4');
subplot(3,3,7);subimage(b5);title('BIT PLANE 5');
subplot(3,3,8);subimage(b6);title('BIT PLANE 6');
subplot(3,3,9);subimage(b7);title('BIT PLANE 7');
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

6. Display of FFT(1-D & 2-D) of an image

l=im2double(imread('cancercell.jpg'));
f1=fft(l);
f2=fftshift(f1);
subplot(2,2,1); imshow(abs(f1)); title('Frequency Spectrum');
subplot(2,2,2); imshow(abs(f2)); title('Centered Spectrum');

f3=log(1+abs(f2));
subplot(2,2,3); imshow(f3);
title('log(1+abs(f2))'); l=fft2(f1);
l1=real(l);
subplot(2,2,4); imshow(l1);title(' 2-D FFT');
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

7. Computation of mean, Standard Deviation, Correlation coefficient of the given Image

i=imread('cancercell.jpg');
subplot(2,2,1); imshow(i);title('Original Image');

g=rgb2gray(i);
subplot(2,2,2); imshow(g);title('Gray Image');

c=imcrop(g);
subplot(2,2,3); imshow(c);title('Cropped Image');

m=mean2(c);disp('m'); disp(m);
s=std2(c); disp('s'); disp(s);

figure,
k=(checkerboard>0.8);
subplot(2,1,1); imshow(k); title('Image1');

k1=(checkerboard>0.5);
subplot(2,1,2); imshow(k1); title('Image2');

r=corr2(k,k1);
disp('r');disp(r);

m
74.5173

s
44.2327

r
0.5774
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

8. Implementation of Image Smoothening Filters(Mean and Median filtering of an


Image)
% Median Filters
I=imread('nuron.jpg');
K = rgb2gray(I);
J= imnoise(K ,'salt &
pepper',0.05); f= medfilt2(J,[3,3]);
f1=medfilt2(J,[10,10]);

subplot(3,2,1); imshow(I); title('Original Image');


subplot(3,2,2); imshow(K); title('Gray Image');
subplot(3,2,3); imshow(J); title('Noise added Image');
subplot(3,2,4); imshow(f); title('3x3 Image');
subplot(3,2,5); imshow(f1); title('10x10 Image');

%Mean Filter and Average Filter


figure;
i=imread('nuron.jpg');
g=rgb2gray(i);
g1=fspecial('average',[3 3]);
b1 = imfilter(g,g1);
subplot(2,2,1); imshow(i); title('Original Image');
subplot(2,2,2); imshow(g); title('Gray Image');
subplot(2,2,3); imshow(b1); title('3x3 Image');
g2= fspecial('average',[10 10]);
b2=imfilter(g,g2);
subplot(2,2,4); imshow(b2); title('10x10 Image');

%Implementation of filter using Convolution


figure;
I= imread('earcell.jpg');
I=I(:,:,1); subplot(2,2,1); imshow(I); title('Original Image');

a=[0.001 0.001 0.001; 0.001 0.001 0.001; 0.001 0.001 0.001];


R=conv2(a,I);
subplot(2,2,2); imshow(R); title('Filtered Image');

b=[0.005 0.005 0.005; 0.005 0.005 0.005; 0.005 0.005 0.005];


R1=conv2(b,I);
subplot(2,2,3); imshow(R1); title('Filtered Image 2');
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

9. Implementation of image sharpening filters and Edge Detection using Gradient


Filters

i=imread('cancercell.jpg');
subplot(4,2,1); imshow(i);
title('Original Image');

g=rgb2gray(i);
subplot(4,2,2); imshow(g); title('Gray Image');

f=fspecial('laplacian',0.05);
im=imfilter(g,f);
subplot(4,2,3); imshow(im); title('Laplacian ');

s=edge(g, 'sobel');
subplot(4,2,4); imshow(s); title('Sobel');

p=edge(g, 'prewitt');
subplot(4,2,5); imshow(p); title('Prewitt');

r=edge(g, 'roberts');
subplot(4,2,6); imshow(r); title('Roberts');

[BW,thresh,gv,gh]=edge(g,'sobel',[],'horizontal');
[BW1,thresh1,gv1,gh1]=edge(g,'sobel',[],'vertical');

subplot(4,2,7); imshow(BW); title('Sobel Horizontal');


subplot(4,2,8);
imshow(BW); title('Sobel Vertical');
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

10. Implementation of Image Intensity slicing technique for image enhancement

i=imread('earcell.jpg');
subplot(3,2,1);imshow(i); title(‘Original Image’);
l=im2double(i);

level=graythresh(l);
BW = im2bw(l,level);
subplot(3,2,2); imshow(BW); title('Image graythresh');

level1=0.2*BW;
subplot(3,2,3); imshow(level1); title('0.2 Slice');

level2=0.4*BW;
subplot(3,2,4); imshow(level2);title('0.4 Slice');

level3=0.6*BW;
subplot(3,2,5); imshow(level3);title('0.6 Slice');

level4=0.8*BW;
subplot(3,2,6); imshow(level4); title('0.8 Slice');
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

11. Canny edge detection Algorithm

i= imread('cancercell.jpg');
g=rgb2gray(i);
subplot(2,2,1); imshow(i); title('Original Image');
subplot(2,2,2); imshow(g); title('Gray Image');
c=edge(g,'canny');
subplot(2,2,3); imshow(c); title('Canny output');
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

12. To count the number of connected object in a given image using morphological operations.

SOFTWARE REQUIRED-MATLAB 7.12.0 (R2011a)


THEORY- Connected-component labeling (alternatively connected-component analysis, blob
extraction, region labeling, blob discovery, or region extraction) is an algorithmic application of graph
theory, where subsets of connected components are uniquely labeled based on a given heuristic.
Connected-component labeling is not to be confused withsegmentation.
Connected-component labeling is used in computer vision to detect connected regions in binary digital
images, although color images and data with higher dimensionality can also be processed.[1][2] When
integrated into an image recognition system or human-computer interaction interface, connected
component labeling can operate on a variety of information.[3][4] Blob extraction is generally performed on
the resulting binary image from a thresholding step. Blobs may be counted, filtered, and tracked.
Blob extraction is related to but distinct from blob detection.

MATLAB CODE-
clc;
clear all;
close all;
i=imread('coins.png');
i=im2bw(i);
% i=[0 0 1 0 1;1 1 1 0 0;0 0 0 1 1;1 1 1 1 0;1 0 0 1 0;0 1 0 1 0];
[m n]=size(i);
b=[0 1 0;1 1 1;0 1 0];
label=zeros(m, n);
a=i;
p=find(a==1);
p=p(1);
N=0;
while(~isempty(p))
N=N+1;
p=p(1);
x=false([m, n]);
x(p)=1;
y=a&(imdilate(x,b));
while(~isequal(x,y))

x=y;
y=a&imdilate(x,b);
end
pos=find(y==1);
a(pos)=0;
label(pos)=N;
p=find(a==1);
end
% imtool(label);
K=label(1:m,1:n);
K=label2rgb(K);
figure;
imshow(K);
display(N);
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE
JECRC Campus, Shri Ram Ki Nangal, Via-Vatika,Jaipur

RESULT
N=16

You might also like