Introduction To Matlab - Image Processing by Dhananjay K. Theckedath
Introduction To Matlab - Image Processing by Dhananjay K. Theckedath
IMAGE PROCESSING
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
3
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath
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.
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
5
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath
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
6
Image Processing Using MATLAB codes
Dhananjay K. Theckedath
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
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
There are some standard arithmetic operators that one can use in programming
Try the following
Note: The operators ( *, / , ^ ) have their matrix counterparts ( .* , . / , .^ ). The dot before
the operator tells us that it is an element-by-element operation.
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
1. a+b
2. a*b
3. a .* b
12
Image Processing Using MATLAB codes
Dhananjay K. Theckedath
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
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.
16
Image Processing Using MATLAB codes
Dhananjay K. Theckedath
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.
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.
22
Image Processing Using MATLAB codes
Dhananjay K. Theckedath
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
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.
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.
Shown below is the table that summarizes the way MATLAB interprets the image types.
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
32
Image Processing Using MATLAB codes
Dhananjay K. Theckedath
33
Image Processing Using MATLAB Codes
Dhananjay K. Theckedath
Given below are a few commands that would directly perform filtering.
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
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
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.
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
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.
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
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
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.
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.
44
Image Processing Using MATLAB codes
Dhananjay K. Theckedath
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:
while expression
...
...
end
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
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
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
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
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.
55