You are on page 1of 55

INTRODUCTION TO MATLAB

IMAGE PROCESSING

Compiled by Dhananjay K. Theckedath


Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

MATLAB (an acronym for MATrix LABoratory) is a special-purpose


computer program optimised to perform engineering and scientific calculations.
MATLAB is a powerful high-level language and is very easy to use. The MATLAB
library has an extensive set of predefined functions, which make it much easier compared
to languages such as FORTRAN or C.
To get stared with MATLAB, one needs to know how to manipulate and represent data.
One also needs to know how to find information about available functions and finally
how to write our own programs.
A.1 Starting MATLAB

To start MATLAB, double click on the MATLAB icon on the desktop . The main
MATLAB window (command window) with the command line prompt “>>” will appear
on screen. MATLAB is an interpreted language, which means that the instructions that
we give are interpreted by the computer directly as opposed to C in which we first need to
compile the instruction before it can be executed by the computer.
There are two ways to give instructions in MATLAB
(1) On the command line after the prompt “>>”. For example, we can directly write
>> help abs and the following details will appear on the command window.

2
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

In short, if we type an instruction, MATLAB executes it and gives us the result. We do


not use the command window to write programs. We use it only to check certain
operations.
(2) Through a script (.m file, program) or a function where a code is written in a text file
with the .m extension. These scripts contain lists of instructions. To start writing a
.m file we need to activate the editor. One way to do that is to click on the icon
shown below on the command window. The editor page pops up immediately.

3
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

This is the place where all MATLAB codes are written.


Before we proceed, we should be aware that MATLAB codes work only in their
respective directories. The default directory is C:\MATLAB6p5\work. If we want to save
programs to our directory, we need to use the cd command (the pwd command tells us
where we are presently). Another way to go to our directory is by clicking on the icon
shown and changing it to our directory. Before starting MATLAB sessions, we should
create our own directory through Windows explorer. Only if we have created our own
directory, it will be displayed as shown below.

If we write a program to modify an image, we should be sure that the program as well as
the original image is in our directory.

A.2 The Help and Look for Commands

MATLAB is made up of a huge library of commands, some of them being more


important than the others. We shall discuss some of them here.
The most important command in MATLAB is the help command. Type help on the
command line
>> help
4
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

Read what pops up on the screen. What we have here is a list of folders that are available
to us.

From here, one can start exploring. For example we could write
>> help matlab\elmat

This would give us elementary matrices and matrix manipulation functions. In a similar
manner we could check out any of the folders.
Suppose we are looking for the cosine function, type

>> help cos

5
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

The following display will appear on the command window

For image processing functions, type help images to get a list of available functions and
their brief description. >> help images.
Apart from the help command, another command that is very important is the lookfor
command.
If we are not aware of the name of the MATLAB command that we want to use (which is
usually the case), the lookfor command comes to our rescue.
For instance if we want to calculate the cosine and are not sure of the name of the
function, we simply type
>> lookfor cosine

MATLAB comes back with all the functions related to cosine

6
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

…..and many more

Looking at the list one can now type


>> help cos to get the cosine function.
Try out the lookfor command for some more functions that you can think of.
Lookfor XYZ looks for the string XYZ in the first comment line. For example, “lookfor
inverse” finds at least a 25 matches, which have the word inverse in them. Of these, one
could select the required function (say inv) and then then type >> help inv. The help and
the lookfor commands should be used together to appreciate the power of MATLAB.

A.3 Creating a (Vector) Matrix

One thing that we should never forget when working in MATLAB is that all data is
stored into matrices. A scalar (real) number is a 1 × 1 matrix while a vector is a 1 × N
matrix. Hence matrices are the basic elements of a MATLAB program. MATLAB sees

7
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

matrices as other languages see numbers. This is a big advantage while dealing with
images.
Let us try creating a few vectors (matrices). Type the following command on the
command window >> a = [1 2 3 2 4 5 3] ;

Note: The semicolon at the end of the equation ensures that the stored data is not
displayed. To display the result, do not put the semicolon
Similarly type the following line

8
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

In a similar fashion, matrices of different orders can be generated very easily.


Suppose we want to find the determinant of x. Since we do not know the command for
finding the determinant, we use the lookfor command and then use help on the specific
determinant command.

A.4 MATLAB Operators


There are a few operators in MATLAB that one ought to know

(1) The Colon Operator “ : ”


The colon operator is used to define vectors
For example
a=1:1:10
b=1:2:10 gives us the following two vectors

We notice that the colon instruction is of the form lower limit: increment: upper limit
Another way to define vectors is to use the command zeros and ones. Type >>help ones
and >>help zeros in the command window.
9
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

>> ones(N) gives us a N × N matrix of all ones similarly >> zeros(N) gives us a N × N
matrix of all zeros.

Similarly, type the following commands on the command window and see the results.

10
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

(2) Arithmetic Operator

There are some standard arithmetic operators that one can use in programming
Try the following

Similarly try the following arithmetic operators


>> 3 ^ 4
>> 3 * 4
>> x * y
>> x / y

Note: The operators ( *, / , ^ ) have their matrix counterparts ( .* , . / , .^ ). The dot before
the operator tells us that it is an element-by-element operation.

Let us take an example

a = b =
1 2 3 2 3 4
2 3 4 4 4 4
4 3 2 4 5 6
11
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

Perform the following operations in the command window

1. a+b
2. a*b
3. a .* b

Note the difference between 2 and 3

>> a + b >> a * b >> a . * b

ans = ans = ans =


3 5 7 22 26 30 2 6 12
6 7 8 32 38 44 8 12 16
8 8 8 28 34 40 16 15 12

As stated earlier, a * b performs matrix multiplication whereas a .* b performs element by


element multiplication.

12
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

(3) Relational and Logical Operators

These operators can be found using the help command.

There are applications were we need to compare two quantities. This can be done by
using relational operators. Some of the relational operators are listed below.

13
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

Some of the Logical operators are listed below. Clicking on any of these would give us
the syntax for the commands.

14
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

(4) Martix Operators

We shall discus three operators which are used regularly in the book. The first one is the
sum operator. A better understanding of the sum command can be obtained using the help
command >> help sum.
This command gives us the sum of the vector. Type the following on the command
window.

The sum command gives us the sum only in one direction. Type the following on the
command window

15
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

The sum command adds up each column and gives us the sum in each column. To cut a
long story short, the sum command works on one-dimensional vectors.
To calculate the sum of the entire matrix (image), which as we know is a two-dimensional
vector, we need to use the sum command twice. This is written as shown sum(sum(..)).
Type the following on the command window

The above command calculates the sum of the entire matrix and gives us the result as 45.
This command could be used to calculate the total value of all the pixels in an image.

The second operator is the max and min operator. Type >> help max
The max operator gives us the maximum value of the vector while the min operator gives
us the minimum value of the vector. Just like the sum command, the max and the min
operators work only on one-dimensional vectors.

Type the following on the command window.

16
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

If we want to find the maximum or minimum of a matrix, we need to use max(max(..)) or


min(min(..)).

Type the following on the command window

Another command that is used in almost all the programs in the book is the size
command. One could study this command using >> help size.

17
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

There are times when we need to know the physical size of the matrix(image). The size
command gives us the number of rows and columns of the matrix.

This command is used to find out the size of the image. row and col are simply two
variables.

18
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

The above display simply means that the cameraman image has 256 rows and 256
columns.
Before we proceed to the next item, we need to know how the elements in a matrix are
arranged. As against what we have been using so far, in images, the x-axis is in the
vertically downward direction while the y-axis in the horizontal direction. This
convention is in accordance with the standard scanning procedure. Always keep the
directions in mind.

What is a(2, 3) ?. The answer is 4.


This understanding is important when one starts writing programs in MATLAB.
19
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

A.5 Plotting Functions

MATLAB’s extensive, device-independent plotting capabilities are one of its most


powerful features. The plot command works when it is fed with two vectors x and y
We can use the lookfor command or the help command to get a detailed description of the
plot command. Type >> help plot
Let us consider a simple example of the plotting command
The following code can either be written on the command window or as script using the
editor (to be explained later).

The output of this program would give us two figures representing the cosine and the sine
waves.

20
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

Try modifying the plots by putting labels on the x-axis and the y-axis. Use the lookfor
command to check for labels.
There are times when one needs to plot more than one figure. MATLAB is equipped with
a command called subplot to achieve this. Type >> help subplot on the command
window.

Let us take an example to make things easier.


Write the following code on the command window
21
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

The output of the program would give us the following figure

22
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

The subplot command puts all the figures together.


The standard syntax for the subplot command is subplot (m, n, p). The subplot command
is followed by the plotting command. We have written the command as subplot (2,2,1)
Here, 2, 2 indicates the ratio of the x and y-axis (2, 2 ensures that the each figure block is
square) while 1 indicates the figure number. In our case, subplot (2,2,1) is followed by
plot (t, p). Hence the figure t v/s p is displayed in the first block. Similarly, subplot
(2,2,2) is followed by the plot (t, q). This causes t v/s q to be displayed in the second
block and so on.
If we change all the subplot dimensions from 2,2 to 4,2 (write subplot (4,2,1)…), we
would get the figure shown below. We choose the dimensions of the subplot depending
on the number of figures that need to get into the subplot. Try out various combinations
of m and n in the subplot command and choose the dimensions that suit your needs.

Kindly study the subplot function in detail using >> help subplot.
Another command which is used for plotting one dimensional functions is the bar
command. While the plot command interpolates discrete points and gives us a continuous
representation, the bar command gives us the actual discrete figure.

23
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

Type the following on the command window

The result of the program is shown below

24
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

The bar command is used in the book while plotting the histogram of an image.
We have also used the xlabel and the ylabel command. Check what these commands do
by typing >> help xlabel on the command window.
Before we end this section on plotting, there is one more application that needs a mention.
There are times when we need to plot two graphs on the same figure (we might need to
overlap the figures). Type the following on the command window.

The above commands would give us two figures superimposed on each other. We have
used the hold on command to achieve this. The hold on command holds the current plot
and all the axis properties so that subsequent plotting commands can be added to the
existing graph. This is an important command. Type >> help hold on on the command
window and see the details. MATLAB also has the hold off command, which performs
the opposite task.

25
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

We could also change the colour of the graphs. Kindly check the plot command.
From these generalized commands, let us move to some specific Image processing
commands.

A.6 Image Processing Tool Box


Some of the important toolboxes available in MATLAB are
(1) Image processing toolbox.
(2) Signal processing toolbox
(3) Statistics toolbox
(4) Digital Signal Processing toolbox
(5) Wavelet toolbox
(6) Control system toolbox
(7) Communication toolbox

26
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

Since this is a subject of image processing, we shall spend a little time discussing some
functions available in the Image processing toolbox.
One of the important and basic functions available to us is the imread. Imread reads an
image into an array. It stores the image as a matrix. It is this property that makes
MATLAB so convenient for image processing. Use the help command to see what imread
does.
>> help imread
Try this out
a = imread(‘saturn.tif’);
This command stores the image as an array in a.
To check the size of a, simply type >>whos

The whos command gives us the number of variables used along with their size and their
class. To display this image we could use one of the many display functions available.
Type >> lookfor image One of the commonly used command is the imshow
Try this out

27
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

The output that we get is shown below. MATLAB provides us with quite a few images,
which are stored in C:\MATLAB\toolbox\images\imdemos.
We could also use our images provided we store them in our directory.

28
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

We could also use the image or imagesc command. Use the help command to study the
difference between the commands.
We have seen the imread command. What we need to remember is that this command
stores a grey image in an array as uint8 (This is a storage class). The imshow command
works well for class uint8.
One important thing to note is that arithmetic operators do not work on uint8 class.
Hence if we store the first image in im1 and the second image in im2, we cannot perform
arithmetic operations on them. Example im1 + im2 will not be accepted. To perform
arithmetic operations, we need to convert the uint8 class to class double
You don’t need to worry about this if you are using Matlab 7

Remember : To perform arithmetic operations, we need to convert the uint8 class to class
double

29
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

Most of the programs given in this book make this conversion from uint8 to double.

The Image processing toolbox supports four basic types of images


(1) Indexed images
(2) Intensity images
(3) Binary images
(4) RGB images

Shown below is the table that summarizes the way MATLAB interprets the image types.

IMAGE TYPE STORAGE CLASS INTERPRETATION


Binary Logical Image is a matrix of zeros
and ones
Indexed 1 Double Image is a matrix of
integers in the range [1, L]
Uint8 or Uint16 Image is a matrix of
integers in the range [0, L −
1]
Intensity 1 Double Image is a matrix of floating
values, typically in the
30
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

range of [0, 1]
Uint8 or Uint16 Image is a matrix of
integers, typically in the
range of [0,255] or
[0,65535]
RGB Double Image is a m × n × 3 matrix
of floating point values in
the range [0,1]
Uint8 or Uint16 Image is a m × n × 3 matrix
of integer values in the
range [0,255] or [0,65535]

There are applications wherein we need to convert one image type to another. Given
below is a table, which lists some of the image conversion functions.

FUNCTION DESCRIPTION
gray2ind Creates a indexed image from a grey scale intensity image
im2bw Creates a binary image from a intensity image, indexed image or a RGB
image based on a luminance threshold
ind2gray Creates a grey scale intensity image from an indexed image
ind2rgb Creates a RGB image from an indexed image
mat2gray Creates a grey scale intensity image from data matrix
rgb2gray Creates a grey scale intensity image from a RGB image
rgb2ind Creates an indexed image from a RGB image

One could use the help command to understand any of the above mentioned image
conversion commands.
It is worthwhile to study the syntax of each of these conversions functions. The rgb2gray
has been used quite frequently in the book.

31
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

Given below is a simple implementation of conversion.

The results are displayed below.

32
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

The book provides a program to achieve the same result.


Apart from these commands, we shall also discus some inbuilt functions that are quite
frequently used in Image processing applications.

(1) Linear Filtering

Filtering is a technique of modifying an image. For example, filtering can be used to


enhance an image or to eliminate noise that is present in the image. Though the book
provides codes to achieve this, MATLAB has an in-built function known as imfilter,
which achieves filtering. I would personally recommend students to write their own
codes.
Type the following on the command window >> help imfilter

33
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

Given below are a few commands that would directly perform filtering.

The resulting images are shown below

34
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

The h that we chose was a low pass filter hence the second image is a blurred.

MATLAB also provides us with pre-define filters, which one could use in projects.
Type the following on the command window >> help fspecial

35
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

We shall now implement one of these pre-defined filters. Type the following commands
on the command window

The figures are given below

Another important command that is quite regularly used is the imwrite.


Check >>help imwrite. This command helps us store an array as an image. Consider this,
we have read two images and added them. Their sum is stored in a variable. This variable
can be stored as an image using the imwrite command.

36
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

The result of this program is shown below. The imwrite command commands writes the
variable im as final_image.bmp (we can give any name) and stores it in the directory
that we are working in, in this case C:\Matlab7\work.

37
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

(2) Reading Multiple Images from a Graphics File

MATLAB supports several graphics file formats, such as HDF and TIFF, which can
contain multiple images. The imread command imports only the first image from a file.
To import additional images from the file, we use the syntax supported by the file format.
Given below is the syntax for reading a series of 27 images from a TIFF file and stores
the images in a 4-Dimensional array.

(3) Image Resizing

To enlarge the size of an image, we resize the image by specifying a magnification factor
greater than one. We can use the help command >> help imresize to understand the
syntax.

38
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

Type the following on the command window

The result of these commands gives us two images shown below.

39
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

Though MATLAB has an inbuilt command to zoom the image, the book provides a
program for the same. It is advisable to write your own codes instead of using ready-made
functions.

(4) Image Rotation

Image can be rotated using the imrotate command. Type the following line on the
command window >> help imrotate.

40
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

Let us read an image and try to rotate it using the command. Type the following on the
command window

The output of these commands will give us 2 figures shown below

41
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

Though the second figure looks bigger, the size of the brick wall is the same.
There are many more commands that the Image processing toolbox provides. Spend some
time and explore them. To view all the inbuilt functions in the Image processing toolbox,
simply type help on the command window >>help. This will give us the complete list of
toolboxes. Of these we can click at images. This is shown below. There are two links that
contain the entire set of inbuilt image processing functions.

The basic commands of MATLAB have been discussed. The command window that we
have been using so far is nothing but a glorified calculator. We use the command window
to search for new commands and to try them out.
To write our own codes, the command window is not of much use. The next few pages
will help us learn the programming aspects of MATLAB. We shall discuss some of the
basic loops that would be required in programming.

42
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

A.7 Scripts and Main Programs

In MATLAB, scripts are the equivalent of main programs. These scripts are written in the
editor. We have already seen how to open the editor window (page 3). After finishing
writing the program, we save it in our directory. To run the program, we simply need to
write the name of the program in the command window without the .m extension. We can
also run the program by using the F5 key (save and run).
Let us consider the given program.

This program is saved as test.m


We run this program by simply writing test in the command window (>> test) or by
pressing the F5 key (save and run).

43
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

The final result, n_factorial is displayed since we did not put the semi-colon after
n_factorial in the program.

We shall now discuss some of the basic loops used in programming

(1) The for loop


The for loop is a loop that executes a block of statements a specified number of
times. The for loop has the form
for index = expression
Statement 1
...
Statement n
end
In MATLAB, every loop has to end with an end command
The for loop is used in almost all the programs that are presented in the book.
Type the following on the command window >> help for

44
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

Let us take an example of the for loop.


The program given below uses the input command. This command is similar to the scanf
command used in C. The % sign is used to comment the statement. The line following the
% sign (green colour) is not executed.

Use the help command to check what the input command does >> help input

45
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

(2) if statement
The general form of the IF statement is
if expression
Statements
elseif expression
Statements
else
Statements
end

Type >> help if on the command window to understand the syntax better.
Let us consider an example of an if statement. In the program given below, the if
statement is nested within the for loop. We have used an additional command called size.
This is a very important command as it gives us the size of the variable under study. Use
the help command to check its details.
The result of the program is shown in a separate window.

46
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

Result:

(3) While loop


The while loop, like the for loop, is a block of statements that is repeated indefinitely
as long as some condition is satisfied. Check this by typing >>help while on the
command window

while expression
...
...
end

If the expression is true, the code block gets executed.

These basic loops help us develop complex programs. Let us take a simple program,
which is used to threshold an image. We use the for loop and the if loop.

47
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

The program is stored as test.m in C:\MATLAB7\work. Note: You should make it a habit
of storing the images and your programs in your own directory. Also make sure that the
command window points to your directory (Refer page 4).
As stated earlier, you could run this program either by typing test on the command
window (>> test) or by simply pressing the F5 key (save and run).
The moment you do that, the command window asks you to enter the value of the
threshold (due to the input command used in the program). In this case, we have entered
the value =100 (you could take a different value)

48
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

The two figures that one would get are shown below

(4) Functions

Creating functions is an efficient way of writing programs. MATLAB has a whole set of
inbuilt functions like the ones discussed so far. MATLAB also gives us the luxury of
creating our own functions. Once written, we simply need to call them in the main
program. All that we need to be careful about is the directory. The function and the
main program have to be in the same directory.
49
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

Once the function is written simply type the following on the command window

We can could use any variable (instead of q )

50
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

If you type >> help threshold on the command window, it would give us the following
display

These are the same comments that were typed in the function !!
We can use this threshold function in any other program as long as both the programs
belong to the same directory, that’s right, in the same directory ! Given below is a
program called test. The threshold function is called through this program.
We can run this program either by pressing F5 (save and run) or by typing test on the
command window

51
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

(5) Debugging a Program

An important advantage of MATLAB lies in its debugging prowess. MATLAB not only
tells us the error but also tells us the kind of error and the line where it occurs.
Consider the following code

When we run this program, we get an error message (red colour) on the command
window.

Lets take another example. We shall consider a thersholding program and deliberately
introduce some errors in it and then see how to rectify it.

52
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

When we run this program, the following screen appears in front of us

We can now take the mouse pointer to test at 11 and click (11 tells us the line on which
the error is !). This action will directly take us to the editor window and to the line where
the error is. All that we would now have to do is change u to y.

53
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath

We can also start the debugging mode by typing the following command
>> dbstop if error This command will stop for error
>> dbstop if warning This command will stop for warnings.
You could use the help command to get details
>> help dbstop if error
Alternately, we could go to the editor and set the options and breakpoints where we want
them to be.
We can learn a lot about important functions using the demo provided by MATLAB. We
can run the demo by writing >> demo on the command window

This would give us the window shown below

54
Image Processing Using MATLAB codes
Dhananjay K. Theckedath

Click on MATLAB, Toolboxes and Blocksets to get a wealth of information. The Image
acquisition and Image processing demo folders are sitting inside the main Toolbox folder.

This discussion on MATLAB has hopefully helped you get a feel of the things that could
be achieved. It should be noted that this Introduction should not be taken as a substitute to
a standard book on MATLAB. It would be a good idea to use a proper MATLAB book to
get a command over the language.

Wish you happy programming.

55

You might also like