CPSC 425: Computer Vision

Homework 1: Introduction to Matlab

Instructor: David Lowe

This assignment involves self-directed study to learn the basics of Matlab for computer vision. There is nothing to hand in and no marks will be given. You should aim to complete this assignment by Tuesday, January 23, 2007.

The assignment

Go to one of the undergraduate computers and start Matlab. To start Matlab from a Unix shell use one of the following:
matlab &            % This starts the standard desktop version
                    % The optional "&" spins matlab off as separate process

matlab -nodesktop   % Command line interface, useful for remote access
                    %   or running inside emacs
quit                % Quits command-line interface
Warning: Expect Matlab to take some time to start as it's a large system. The Department of Computer Science provides concurrent, networked licences for Matlab and (separately) for the Image Processing Toolbox. It is possible, during periods of peak demand, that the maximum number of licensed seats is reached.

Matlab's own getting started tutorial

As a first step, start Matlab (the standard desktop version) and select “MATLAB help” under the Help menu. Go through all the sections under “Getting started.” As you read, try typing and executing the examples in Matlab to see how they work. This will take several hours, but provides an excellent first introduction. You can skip some of the details, such as details of plotting, but you should know where to go back for help if you need it later.

You can also read the same documentation from the Matlab documentation site but it is much better to read it when you can execute the examples interactively.

Other ways to get online help:

   help function    % Gives help on function
   doc function     % Jumps to help documentation on function
   type function    % Shows source code for function

Quick review

Once you have finished Matlab's own tutorial, the following can be cut-and-paste into the Matlab Command Window to remind you of their function:
% Entering matrices
A = [ 1, 2, 3 ]         % produces a row vector
B = [ 1 2 3 ]' 	        % commas are redundant, "'" - operator gives transpose
1:10			% a:b is a short form for [ a, a + 1, ..., b ]
1:0.2:3			% a:i:b specifies use of an increment i

% Some special matrix building functions
zeros(2, 3)		% Matrix of zeros
ones(4, 2)		% Ones
eye(5)			% Identity matrix
rand(10,2)		% 10x2 matrix of random numbers in range [0,1]

% Indexing matrix elements
C = rand(6,8)           % Create (a test) array of random numbers
C(3, 2)			% single elements are obtained in the obvious way
C(:, 2)			% colon gives an entire column...
C(2, :)			% ...or row
C(:)                    % appends all columns into a single column vector (useful!)
C(2:4, 5:7)		% vectors can be used to index sub-matrices
C(1:2:end, :)           % select every second row ("end" is last element)

% Matrix operations
D = [1 2 3];            % Create a couple of test vectors
E = [1 0 -1];           % NOTE: the semi-colon suppresess Matlab output
D + E                   % Vector addition
D + 100			% Scalars can be added to each element
D * E'                  % Inner (i.e., dot) product
D' * E                  % Outer product (is a matrix)
D .* E                  % Use the "." to specify element-wise operations
[1:10] .^ 2		% Square each number from 1 to 10
F = rand(5,3)           % Create (another test) array of random numbers
sum(F)                  % Sum columns of F
sum(F(:))               % Sum all the elements in F
help elfun		% List of all elementary math functions
                        % (trigonometric, exponential, complex, rounding and remainder)

% Plotting and Printing
X = 1:10;               % Create values for X (i.e., horizontal) axis
Y = X .^ 2;             % Create values for Y (i.e., vertical) axis
plot(X, Y);		% "plot" can plot 2D data in many convenient ways
figure;                 % Start a new figure window (otherwise previous figure is replaced)
plot(X, Y, 'r+');	% Uses red "+"s as markers
figure;                 % Start a new figure window (otherwise previous figure is replaced)
X = [-6:0.1:6]';        % Create new values for X (note transpose operator)
Y = [sin(X), 2 * cos(X), 3 * abs(cos(X))]; plot(Y);  % Create and plot 3 functions at once
doc plot		% Look here for details

% Writing your own functions
% Using your favorite text editor, place the following 2 lines into a file
%   called test.m in current directory:
function r = test(m)
    r = [m m];         % Append two copies of the matrix m
% Now you can call the function from Matlab. (Matlab can use any *.m file in
%   the current directory or other directories you place in its path)
test([1 2; 3 4])

Saving transcript to a file

The following appends Command Window interaction to a file. This is useful for handing in Matlab results in assignments.
diary file.txt  % Save (i.e., append) command interaction to file.txt
diary off       % Stop saving

Images in Matlab

We use functions from the Matlab Image Processing Toolbox. Among other things, this provides a simpler interface to display images. All of the following could also be done in basic Matlab using standard routines.

The “imread” function reads an image from a file. The file location is specified relative to current directory or by giving its full path. Matlab can read most common image file formats, such as tif, jpg, and ppm. The imread function returns the image in an 8-bit format. Most other Matlab commands require floats, so the first step is usually to convert to double.

im = imread('cameraman.tif');  % This image is already available in Matlab
                               % NOTE: the semi-colon suppresess Matlab output
                               %       (helpful since "im" here is 256x256)
im2 = im2double(im);           % Convert to double for processing
%im2 = rgb2gray(im2);          % [Optional for color image] convert to grayscale
imshow(im2);                   % Display the image

im3 = im2 + 0.2;               % Make image brighter
imshow(im3);
imwrite(im3, 'bright.jpg');    % Writes to file (file extension defines output format)

box = ones(5,5);               % Create simple 5x5 box filter
box = box / sum(box(:));       % Normalize filter elements to sum to 1
im4 = conv2(im2, box, 'same'); % Convolve with image and keep size 'same'
imshow(im4);                   % View blurred image


Email David Lowe with corrections or suggested improvements to this page.