|
CS 332
MATLAB Introduction |
|
zeros and onessum, min, max,
linspace, findhelp systemhelp to obtain information about user-defined
functionsbreak and return statementsMATLAB is an extensive technical computing environment with advanced graphics and visualization tools and a rich high-level programming language. This document introduces aspects of MATLAB that will be most useful for working with vision software in the course CS332 Visual Processing in Computer and Biological Vision Systems. To learn more about MATLAB, you can browse the extensive online help facility or peruse the books and documents available in the CS332 library in SCI S160. The CS112 syllabus page also contains daily links to pdf files of slides on topics covered here, as well as additional MATLAB facilities.
At Wellesley, MATLAB 7.4, together with some useful toolboxes that include the Image Processing Toolbox, is available on the public Macs and PCs, and on the CS Department's Linux workstations. Installation CD's are available at the Knapp Media Center that can be used to install MATLAB onto personal computers (Macs or PCs) for use on the campus network. For more information about this option, see the Wellesley Desktop Computing webpage. The MATLAB software is key-served, so there are a limited number of copies that can be used at one time. Please be sure to exit MATLAB when you are done using it! A student version of MATLAB can be purchased for $99.00 at the Mathworks website.
To start MATLAB on a public Mac, double-click on the MATLAB 7.4 icon inside the
Applications:MATLAB74
folder. Course materials, such as images and code files, can be downloaded to the Mac from the
/home/cs332/download directory on the CS file server using the
Fetch program.
When using Fetch, connect to cs.wellesley.edu
using SFTP. MATLAB code files,
which have a file extension of .m,
may be listed on the Macs with a Mathematica icon. This does not affect their
use in MATLAB.
To start MATLAB on a public PC, first select
All Programs>Academic Software>MATLAB and then the final
MATLAB R2007a icon. Course materials can be downloaded to a PC using the
WinSCP program.
Finally, to start MATLAB on a Linux workstation, enter the following command in a Unix shell window:
matlab &
The section on M-Files, scripts and directories describes how to access course materials when working directly on the Linux machines.
When you start MATLAB, a large window appears (the MATLAB desktop) that contains smaller windows that include a Command Window, Command History, Current Directory, and Workspace window (the latter two windows are shown overlaid and can be selected with tabs):

Near the top of the main MATLAB
window is a pull-down menu with a text field labeled Current
Directory. On a Linux machine, the initial
current directory is the directory that you were connected to when executing
the matlab & command. The initial current directory is
Applications:MATLAB74 on the Macs and
C:\Program Files\MATLAB74\work on the PCs.
Unlike languages such as Java and C, MATLAB is an interactive programming environment, in which the user types single commands at a prompt in the Command Window and the commands are executed immediately. The Command History window maintains a list of all of the commands entered in the Command Window during the current session. Double-clicking on any command in the Command History window evaluates this command again. The contents of the current directory are listed in the Current Directory window in the upper left region of the MATLAB display. The Workspace window, which can be selected with a tab, lists the name, value and type of all variables currently defined in the MATLAB workspace.
The Desktop menu at the top of the main MATLAB window can be used to change
the selection of which windows appear on the display. If the MATLAB windows change their appearance
in an undesirable way, you can restore the desktop to its original appearance by selecting
Desktop Layout>Default from the Desktop menu.
When the MATLAB interpreter is waiting for a command from
the user, the command prompt >>
appears in the Command Window. Try entering the following commands that create some
variables and assign these variables to values. The printout also shows the
MATLAB response (the phrases preceded by % are comments that should not be entered):
>>
format compact % removes extra
vertical space from MATLAB printout
>>
a = 10
a =
% MATLAB prints the value
of each expression
10
>>
b = [1 2 3]
b =
1
2 3
>>
c = [4 5 6; 7 8 9]
c =
4
5 6
7
8 9
>>
d = [-1 0; 6 -7]
d =
-1
0
6 -7
>>
e = [c d]; % a semi-colon at the
end of a statement suppresses
>>
e % the printout
of its value
e =
4
5 6 -1
0
7
8 9 6
-7
>>
MATLAB was originally designed to work efficiently with
large matrices of numbers, which are common in many science and engineering
applications. The name MATLAB is derived from MATrix LABoratory. A matrix is essentially a two-dimensional
array of numbers, although operations on matrices such as multiplication follow
certain mathematical rules. A matrix with M rows and N columns is referred to as
an MxN matrix. In the above examples, the first variable, a,
is assigned to a single scalar
value that is stored in a 1x1 matrix. The variable b is assigned to a row
vector of three elements that are arranged horizontally. b
is represented as a 1x3 matrix. You can think of b as a
one-dimensional array. Brackets are used to enter the contents of a matrix, but
these brackets are not shown when the value is printed.
The variable c
is assigned to a 2x3 matrix that you can think of as a two-dimensional array.
In the assignment statement, the elements within each row are separated by
spaces and the contents of the two rows are separated by a semi-colon. You can
create a column vector in which the
elements are arranged vertically, by placing semi-colons between the successive
elements, as in the following example:
>>
f = [1; 2; 3]
f =
1
2
3
>>
The earlier assignment of the variable e
illustrates that new matrices can be formed out of
existing ones, by concatenating the parts. This assignment statement is also
terminated by a semi-colon, which suppresses the printout of the returned
value. The value of a variable can be printed by typing the name of
the variable at the command prompt.
At any time, you can enter the clc command to clear the
Command Window.
The built-in size
function returns the dimensions of a matrix:
>>
size(b) %
returns a vector containing the two dimensions, 1x3
ans =
1
3
>>
size(e)
ans =
2 5
>>
size(e,1) % returns the first
dimension
ans =
2
>>
size(e,2) % returns the second
dimension
ans =
5
>>
[rows,cols] = size(e) % assigns
dimensions to separate variables
rows =
2
cols =
3
>>
When a value is returned, but not assigned to an explicit
variable name, the value is assigned to a default variable named ans. The
built-in function length returns the length of a one-dimensional matrix,
e.g. length(e).
The elements of a 1D matrix can be accessed by specifying a single index in parentheses, while the elements of a 2D matrix can be accessed by placing two indices inside parentheses, separated by commas, as shown in the following examples:
>>
b(2)
ans
= % indices begin with 1 (not
with 0, as in Java and C)
2
>>
d(2,2)
ans =
-7
>>
d(1,2)
ans =
0
>>
d(2,2) = 10 % assigning new contents to
a matrix location
d =
-1
0
6
10
>>
d(4,4) = 3
d =
-1
0 0 0
6
10 0 0
0
0 0 0
0
0 0 3
>>
The last example shows that if a value is assigned to a matrix location that is outside the current bounds of the matrix, MATLAB automatically expands the matrix, padding it with zeros in locations where a value is not specified. When expanding the matrix, the old contents are copied to the new matrix, so this is not an efficient operation if performed many times.
zeros and onesWhen the desired size of a matrix is known in advance, it is
best to create the matrix initially using the functions zeros or ones,
as shown in the following examples:
The zeros and
ones functions can also be used
to create 3D matrices. This is illustrated in the following example, which also
shows how to access the dimensions and elements of a 3D matrix:
It is often desirable to create a range of equally spaced
numbers or access a range of indices in a matrix all at once. A range of
numbers can be specified using colon
notation. The expression a:b
denotes a sequence of consecutive numbers from a
to b, incrementing by 1. The
expression a:b:c denotes a
sequence of numbers from a to c, changing by b.
In the following examples, some sample ranges of
numbers are placed in 1D matrices:
>>
g = [2:6]
g =
2
3 4 5
6
>>
h = [3:2:11]
h =
3
5 7 9
11
>>
k = [2:-1:-3]
k =
2
1 0 -1
-2 -3
>>
m = [0.2:0.4:2.2]
m =
0.2000
0.6000 1.0000 1.4000
1.8000 2.2000
>>
The last example created a matrix of floating point numbers, and by default,
MATLAB prints these numbers with 4 digits after the decimal point.
Colon notation can be used to specify a range of indices for a matrix. Inside a
matrix reference, a single colon by itself specifies an entire row or column. The
keyword end inside a matrix
reference specifies the upper limit of a particular dimension. The following
examples illustrate these concepts:
>> e
e =
4
5 6 -1
0
7
8 9 6
-7
>> e(1,2:4)
ans
= % row 1, column
indices 2 through 4
5
6 -1
>>e (1:2,4:5)
ans
= % rows 1 and 2,
columns 4 and 5
-1 0
6
-7
>> e(:,2)
ans =
% all rows in column 2
5
8
>> e(2,:)
ans
= % all columns in
row 2
7
8 9 6
-7
>>
e(1,3:end)
ans
= % row 1, from
column 3 to the end
6
-1 0
>>
e(:,3) = 0 % assign all
rows in column 3 to zero
e =
4
5 0 -1
0
7 8 0
6 -7
>>
The contents of one matrix can be copied into another, using colon notation to specify regions of the matrices:
>>
im1 = zeros(5,5)
im1 =
0
0 0 0
0
0
0 0 0
0
0
0 0
0 0
0
0 0 0
0
0
0 0 0
0
>>
im2 = ones(3,3)
im2 =
1
1 1
1
1 1
1
1 1
>>
im1(2:4,3:5) = im2 % copy all of
im2 into im1, starting at row 2,
im1
= % column 1
of im1
0
0 0 0
0
0
0 1 1
1
0
0 1 1
1
0
0 1 1
1
0
0 0 0
0
>>
im1(4:5,1:2) = im2(1:2,1:2) % copy a
subregion of im2 into im1
im1 =
0
0 0 0 0
0
0 1 1
1
0
0 1 1
1
1
1 1 1
1
1
1 0 0
0
>>
subimage = im1(2:4,1:3) % create
a separate matrix that is a
subimage
= %
subregion of im1
0
0 1
0 0
1
1
1 0
>>
If two matrices have the same dimensions, their contents can be added, subtracted, multiplied and divided on an element-by-element basis:
>> a1 = [2 6 3; 0 4 7; 1 5 8] In each of the above examples, a new matrix was created and automatically
assigned to the temporary variable ans. To reassign a variable to
the new matrix, or assign the result to a new variable name, the expression
must be embedded in an assignment statement, e.g. a3 = a1 + a2.
Some additional built-in MATLAB functions that will come in
handy include sum, min, max, linspace and find, illustrated
in the following code:
linspace(x1,x2,n) returns
a 1D matrix containing n values
that are evenly spaced between x1
and x2:
Finally, the find
function returns the locations (indices) of values in a matrix that satisfy an input
logical expression:
The two vectors A sequence of MATLAB commands can be stored in a text file
and executed by entering the first name of the text file in the Command Window.
The file must have a filename extension of An existing M-file can be opened in the MATLAB editor in the following ways:
r and c indicate that there are
numbers between 0.33 and 0.67 at (row, column) locations (1,2), (2,3), (4,3), (1,4) and (3,4).
For more information about these and other MATLAB functions,
see the section on Using the help system. Other
built-in functions
that may appear in course software include abs, exp, sqrt, prod, mean, fix, round, rem,
sin, cos and tan.
M-Files, scripts and directories
.m
and is referred to as a script, which
is a type of M-File. Although any
text editor can be used to create an M-File, MATLAB provides its own editor
that is convenient to use. There
are three ways to open an initial editor window:
edit in the Command Window
New>M-File from the File menu in the
upper left corner of the main MATLAB window
Open... from the File menu and navigate to
the desired code file
edit command in the Command Window, for example:
edit myCodeFile
In this case, the myCodeFile.m file must be stored in the Current
Directory, or exist somewhere on MATLAB's search path described later in
this section.
Multiple files can be open in the editor at one time - the files are overlaid and can be selected by clicking on their name at the bottom of the editor window. You can type commands in the editor, and the code will be formatted automatically with indentation to make the code more readable.
To save a code file:
Save from the editor's File
menu
When a file is first created, a dialog box will appear where the name of the file can
be entered. Type the full file name (e.g. myCodeFile.m) in the text box labeled
Save As: and click on the Save button. Unless otherwise specified,
the file will be stored in the Current Directory.
Suppose a file is created, named testFile.m.
The sequence of commands in this file can then be executed by selecting Run
from the editor's Debug menu, or by entering the name
testFile in the Command Window.
A comment can be placed in an M-File by preceding the text
with %, as shown in the above
code samples. Multiple lines of text can be put in comments by surrounding the
block of text with %{ and %} placed on separate lines, as shown
in the following script:
A script is executed as if the individual commands were entered, one-by-one, in the Command Window. As a consequence, existing variables in the MATLAB workspace can be altered by a script that uses variables of the same name, and new variables created by a script will remain in the workspace after execution is complete.
In the Starting MATLAB section, it was noted that there is
a default current directory whose pathname differs on Macs, PCs and Linux
machines. The current directory can be changed in the Current Directory window.
The menu bar in this window contains an icon for navigating up one directory
level (a folder with an up-arrow, in the upper left corner), and double-clicking on a folder
displayed in the window allows you to
navigate down one level. Alternatively, you can navigate to the desired directory using
the pull-down menu labeled Current Directory: along the top menu bar, together
with the folder-and-up-arrow icon to the right of this pull-down menu. From the Command
Window, the cd
command can be used to specify a current directory. On a Linux machine, for example, the
pathname has the format shown in the following example:
When a name, such as testFile,
is entered in the Command Window, the MATLAB interpreter first checks if there
is a variable of this name in the workspace. If not, it checks whether there is
a built-in function of this name. If no built-in function exists, it looks for
an M-File in the current directory with this name as the first file name (i.e.,
testFile.m). If no such file is
found, the interpreter checks each directory in a list called the search path for a file of this name. If
no file is found on the search path, an error is generated.
The search path initially contains all of the directories
where MATLAB stores its files. The search path can be viewed by selecting
Set Path... from the File menu. This brings up a dialog box with a list of current
directories on the search path. On a Mac or PC, a new directory can be added by
clicking either the Add Folder... or Add Folder with Subfolders...
button, which brings up another dialog box that can be used to navigate to the
directory to be added to the search path. To modify the search path on a Linux
machine (this also works on PCs), first use the Current Directory window to
navigate to the directory containing the folder (directory) to be added to the
search path. Right-click on the folder and then select Add to Path
in the menu that appears. A smaller menu will appear with
the choices Current Directory, Selected folders or Selected folders and
subfolders.
On a Linux workstation, all of the directories containing course software can be added to the search path by executing the following command in the Command Window:
>> addpath(genpath('~cs332/download'));
In order to execute a script from the editor using Run
from the Debug menu, or by entering the name of the script in the Command
Window, the script file must be stored in the current directory or some other
directory listed on the search path.
When naming variables and files, it is helpful to remember
the procedure that MATLAB uses to resolve a name that appears in a script or is
entered directly in the Command Window. To determine whether a particular name
already exists, use the exist
function, which returns 0 if a name does not exist:
MATLAB has an extensive library of built-in functions that
are documented through the help
system. Just enter help or doc
followed by the name of a function:
The help
command can also be used to print information about user-defined scripts and
functions. In the case of scripts, any comments at the top of the script file
that are preceded with a % are
printed. For example, suppose the following script were stored in a file named
helpTest.m:
The comments can then be accessed through the Command Window:
>> help helpTestYou can also select MATLAB Help
from the Help menu to
access all of the online documentation.
MATLAB provides if
and switch statements for
conditionals, and for and while statements for loops. This
section introduces if and for statements. The if
statement can follow one of three patterns:
if
expression
<commands to evaluate if true>
else
<commands to evaluate if false>
end
if
expression1
<commands to evaluate if expression1 is
true>
elseif
expression2
<commands to evaluate if expression2 is
true>
elseif
expression3
<commands to evaluate if expression3 is
true>
...
else
<commands to evaluate of no other
expression is true>
end
The expressions in the above patterns are logical
expressions that can be created using the following relational operators,
similar to Java and C:
> < >= <= == ~= & | && ||
(note that == is used to test for equality - the single equals = is used only
for assignment).
The general pattern for the for
statement is:
It is common to use the colon operator or an existing 1D
matrix to specify the values for the variable that controls the number of times
that the body of the loop is executed. The following sequence of commands
illustrates the use of if and for
statements. The statements are
formatted as they would appear when entered into an M-File in the editor. Semi-colons
are typed at the end of each assignment statement so that the MATLAB output is
suppressed during execution:
Suppose the above statements were saved in an M-File named
forTest.m and then executed in the Command
Window. The final values stored in the variables randomNums,
numbers, numbers2D and sum
are shown in the following printout:
Now that you know about loops, it’s useful to know how to
terminate a runaway computation. When MATLAB is busy performing a computation,
the word Busy is printed in the
lower left corner of the full MATLAB window. The execution of any command can
be aborted by typing control-C.
When entering commands in the Command Window, there are a number of handy shortcuts available. The up-arrow and down-arrow keys cycle up and down through previously entered commands, allowing you to repeat the execution of a command. The left- and right-arrow keys move the cursor back and forth through a line to facilitate editing, and the Tab key can be used for command completion. If you type part of a command and decide not to execute this command, press the escape key to erase the line.
A final handy shortcut is that multiple commands can be typed on one line, separated by commas:
>> x = 10, y = 15, z = sqrt(x^2 + y^2)Large 2D and 3D matrices can occupy substantial memory space.
It is possible for MATLAB to run out of memory, making it impossible to do
further work. Fortunately, existing variables that are no longer needed can be
eliminated, freeing up memory space for new variables. The
who command prints the names of all
variables currently defined in the MATLAB workspace, the
whos command prints the name, size and
type of each variable, and the clear
command deletes variables from the workspace:
Executing the command clear all
deletes all variables from the workspace.
A new function can be defined in an M-File whose first filename is the same as the name of the function. The first statement in the file is a declaration line that indicates the name of the function and its inputs and outputs. This declaration line implicitly shows the format for calling the function. The generic pattern for a function definition is:
function <outputs> = <function name> (<inputs>)<inputs>
is a list of input variable names, separated by commas. Inside the body of the
function, the inputs can be accessed by name and assigned to new values. If the
function returns a single value, then <outputs>
is a single variable name. If multiple values are returned, then <outputs>
is a bracketed list of
variable names, separated by commas. Inside the body of the function, the
output variable name(s) must be assigned to the value(s) to be returned.
Consider the following function named
gaussian:
This function must be stored in a file named
gaussian.m. The follow examples show
how this function can be called:
When a function is called with a particular set of inputs, the values of these inputs are copied into the input variables specified in the declaration line of the function definition. Similarly, values returned by a function are copied into the variables specified in the function call. Local variables created within a function definition only exist during the execution of the function. The following examples illustrate a variety of function definitions and their application.
The function gaussianFun
returns a 1D matrix of samples of a Gaussian function. Its definition
illustrates the reassignment of an input variable, sigma, and use of a local variable,
xvals:
The function gaussianPlot
illustrates the format of a declaration line for a function with no inputs and
outputs. The plot function is
described in the section, 2D and 3D plotting.
The last two functions can be invoked as follows:
>> gauss = gaussianFun(4,9,2.0)The findZeros
function returns two values, a 2D matrix and a number:
An M-File that contains a new function definition can also contain the definitions of other functions that serve as helper functions, but only the main function whose name is the same as the M-File can be called directly from the Command Window or by functions in other M-Files.
help to obtain information about user-defined functionsIt was mentioned earlier that the help command can be used to obtain information about
user-defined functions. In this case, any comment lines that immediately follow
the function header and appear with a %
at the beginning of the line are printed:
It is common to place a comment immediately following the
header that illustrates how the function is invoked, so that this information
is also accessible through the help
command, for example:
A function can request input from the user with the
input function, which has a single
input that is a quoted text string that is printed as a prompt to the user. The
simplest ways to print out intermediate values during the execution of a
function are to omit the semi-colon at the end of an assignment statement, or
to create a string that contains text and variables, as illustrated in the
newGaussian function shown below. The
disp function displays in input value
without printing a variable name. In the first call to disp,
the input is an matrix of characters created by
concatenating two literal strings and a string representation of the number
stored in sigma, created with
the num2str function.
>>
gval = newGaussian(2);
enter
a value for sigma: 3.0
you
entered 3 at the prompt
the
resulting Gaussian value is
g =
0.6412
have
a nice day!
When concatenating multiple strings to print with disp,
square brackets are used to combine the components of the string. To create nicely formatted
output, explore the
sprintf and fprintf functions, similar to their
counterparts in C and C++.
break and return statementsThe execution of a break
statement inside a loop immediately terminates the loop. The execution of a
return statement anywhere in a
function immediately terminates the function.
By default, MATLAB represents numbers as double-precision floating point numbers that each require 8 bytes of storage space. A large 2D or 3D matrix of double-precision floating point numbers occupies a lot of memory space! Fortunately such precision is often not needed and MATLAB provides several other types of numbers that can be represented more compactly:
MATLAB name size (bytes)
description
uint8
1
integers 0 to 255
uint16
2
integers 0 to 65,535
uint32
4
integers 0 to 4,294,967,295
int8
1
integers -128 to 127
int16
2
integers -32,768 to 32,767
int32
4
integers -2,147,483,648 to 2,147,483,647
single
4
single-precision floating point
For each type, there is a function of the same name that
converts an input number to the desired type. In the example below, the
function uint8 is used to create
a matrix of integers of type uint8
from a matrix of numbers of type double:
The newImage
matrix can be created directly, without the intermediate image matrix, by executing the statement
newImage = uint8(200*ones(100,100)).
When printing floating point numbers of type double, MATLAB uses
scientific notation to print very large or very small numbers, as shown here:
>> number = 1230000000
number =
1.23e+009
>> number = 0.000789
number =
7.8900e-004
>>
The plot
function can be used to create 2D graphs. The essential inputs to
plot are two 1D matrices containing the
x and y coordinates of the points to be plotted. The plot function opens a graphic window called a figure window, draws axes with labels
that are scaled to fit the range of the data, and connects the points with
straight lines, as shown in the following example:

By default, the plot
function draws a new graph in the most recently opened figure window. To create
a new window, execute the figure
command. The plot function is
extremely versatile. For example, you can change the appearance and range of
the axes, adjust the appearance of the graph with different line types, symbols
and colors, add labels and legends, and display multiple graphs superimposed.
Some of these facilities are illustrated below:
xc = 0.0:0.1:2*pi;
yc = sin(xc);
yc2 = cos(xc);
plot(xc, yc, 'b-*')
hold on
plot(xc, yc2, 'r:o')
plot(linspace(0,2*pi,10), linspace(-1,1,10), 'g-.s', 'Linewidth', 2)
axis([-0.5 7.5 -1.3 1.3])
xlabel('x coords')
ylabel('y coords')
title('sample graphs')
legend('sine', 'cosine', 'line', 'Location', 'Best')
hold off

Multiple plots can be displayed within a single figure window using the
subplot command, and scatter plots can be created with the
scatter function. The contents of
figure windows can also be saved for later retrieval or insertion into
documents by selecting the Save or Save As... options from
the File menu at the top of the figure window.
3D plots can be created with the functions
plot3, scatter3, mesh
and surf. The following example
illustrates the creation of a surface plot:

Pictures with arrows can
be created with the quiver function, for example, to illustrate
how features are moving in an image:

When many figure windows are open, displaying plots or images, the memory storage for all of these windows sometimes interferes with the memory space used for numerical computations, producing erroneous results. For this reason, you should not have too many figure windows open at one time! Individual figure windows can be closed by clicking on the close button in the upper right corner of the window. All of the current windows can be closed at once by executing the following command:
>> close all
You can learn much more about all of the plotting
functions through the MATLAB help facility.
The basic MATLAB system, combined with the Image Processing Toolbox, provides many functions for reading, writing, displaying and processing 2D and 3D images. This section introduces the basic facilities that we will use extensively in CS332.
There are four types of images that are supported in MATLAB.
A binary image contains only black
and white pixels and is stored in a logical matrix of 0’s and 1’s. An indexed image is an matrix of integers in
a range from 1 to n that each represent an index into a separate colormap. The colormap is stored in an
nx3 matrix, where each row contains values for the red, green and blue
components of a particular color. Indexed images can be stored in matrices of
type uint8, uint16 or double. The colormap is always an
matrix of type double. An intensity image consists of intensity,
or gray-scale values. When displayed, an intensity image appears as a black and
white photograph. Intensity images can be stored in matrices of type uint8, uint16 or
double. Finally, an RGB image, or truecolor image, is stored
in an mxnx3 matrix. The first two dimensions represent pixel location and the
third dimension specifies the red, green and blue components for the color of
each image pixel. An RGB image can also be stored in matrices of type uint8, uint16
or double. We will primarily work with
intensity and RGB images. It is easy to convert between image types, using
functions that were mentioned briefly in the section,
Types of numbers. MATLAB also provides specific functions such
as rgb2gray that converts an RGB image into a gray-level image.
MATLAB can read and write images using many different file
formats, obtained from many different sources. The most common image file types
that we will use are JPEG, PNG and TIFF. The functions for reading and writing
images are imread and imwrite, which are defined in the
Image Processing Toolbox. Extensive information about
various image file formats and their specification can be obtained through the
help pages for these two functions.
The imread function has one
essential input that is the name of the image file to be loaded into the MATLAB
workspace. Often MATLAB can infer the type of file from its contents, so that
it is not necessary to provide any further inputs to the imread function:
The imfinfo
function prints information about the format of an image, for example, try
entering imfinfo(‘coins.png’). The
essential inputs to the imwrite
function are the image name and file name, with a file name extension that
indicates the file format to use:
By default, the image is stored in the current directory.
MATLAB provides two functions for displaying images,
imshow and imtool, which are also defined in the Image
Processing Toolbox.

By default, the imshow
function displays the image using 256 discrete levels of gray. The number of
gray levels can be changed by providing a second integer input, e.g.
imshow(coins,64). In the case of an
8-bit image, the value 0 is normally displayed as black and 255 is displayed as
white. The imshow function can
be called with a specified range of intensities to be displayed from white to
black. For example, imshow(coins,
[50,200]) displays intensity values of 50 or less as black, and
intensities of 200 or higher as white. The values between 50 and 200 are evenly
spread over the levels of gray from black to white. imshow can also be used to display binary, indexed and
RGB images. If the input image is of type double, MATLAB assumes
that the values to be displayed range from 0.0 to 1.0. In this case, any values
below 0.0 are displayed as black, values above 1.0 are shown in white, and values
between 0.0 and 1.0 are displayed as shades of gray. Again, a different range of
intensities can be specified, e.g. imshow(newImage, [1.0, 5.0]).
Multiple images can be displayed in separate figure windows by calling the
figure function to create a new window. Keep in mind that MATLAB
can become confused if too many figure windows are open, so be sure to close
unnecessary windows, either individually or with the close all
command. Using the subplot
function, multiple images can be displayed inside a single figure window. You
can zoom in or out of an image displayed in a figure window, or change the size
of the image by changing the window size. It is also possible to add figure
annotations and print images that are displayed with imshow.
The imtool
function displays the image in a separate window called an Image Tool. The Image Tool provides
special tools for navigating around large images and inspecting small regions
of pixel values. Similar to imshow,
a particular range of intensity values can be specified when calling imtool,
e.g. imtool(coins, [50,200]). The main Image Tool window has a
menu bar that allows you to open a smaller Overview
window containing the full image, and a Pixel
Region window that displays the intensity or RGB values within small image
regions:
>> imtool(coins);

You can zoom in and out of the image to view it at different
resolutions, and navigate around the image with the mouse. The windows created with
imtool can be closed all at once by executing the following command:
>> imtool close all
The User’s Guide for the Image Processing Toolbox, available online through the Help menu and in hardcopy in the CS332 library in SCI S160, provides more detailed information about how to use the Image Tool.
Finally, we will create and display animations to view moving images using the
functions getframe and movie.
Throughout the semester, we will use a mixture of built-in functions from the basic MATLAB system, additional functions from the Image Processing Toolbox, and custom-built software for analyzing images. Most of the basic MATLAB facilities that you will use are introduced in this document, and other tools will be presented as needed.