Introduction

The purpose of this document is to introduce you to the use of Matlab for image processing. It presupposes basic familiarity with this program ( If you have not used Matlab before - work through the Getting Started with Matlab handout before reading any further. ) It contains the following :
  1. Three Matlab functions whose purpose is to make loading, displaying and saving images easier.
  2. Some general commands related to handling Matlab graphics and printing.
  3. Simple image processing operations that you can do with Matlab.
  4. The source code for the utility functions.
This document is intended to be read at one of the workstations in the ZOO. Try everything as you read it. It should take you less than half an hour to get through it.

The utility functions

The functions provided are : For internal storage purposes Matlab treats an image as a matrix. For example to load an image into a matrix try
img = grload('test.grl');
To find the size of the image simply type
size(img)
To display the image we can use the grdisp function. Type :
grdisp(img)
The image should now appear in a separate window. It is stored in a matrix called img which can be manipulated just like any other Matlab matrix. Changes in img will not be reflected on the display, one has to use grdisp again to view these. To save the image in a file called 'testsave.grl' type
grsave(img,'testsave.img');
You can choose to treat grload, grdisp and grsave as black boxes. The source code is given at the end of this document.

Handling graphics windows and printing

The first time you used the grdisp command Matlab opens a new window - most probably called figure 1 - to display the image in. Subsequent grdisp commands simple overwrite the image in the window. If you need to display more than one image at the same time you can use the figure command to open a new graphics window. This function has two modes of operation : The close command works in a similar fashion - close by itself closes the currently active graphics window, and close(n) closes the window containing figure n. Printing in Matlab is done using the command print. My favorite way of printing is first to print the graphics window to a postscript file and then dump the file to the printer or alternatively include this file in a Latex document. Alternatively in the ZOO workstations one can press the PrintScreen to send a copy of the current window to the default printer. To print the contents of the currently active graphics window to an encapsulated postscript file type :
print -deps myfile.ps
Type help print for more information on the print command. To make the output look nicer try looking up the commands title, xlabel, ylabel, text, grid and axes in the online help system, by typing for example help title.

Simple Image Processing Operations

This section is intended more as a tour guide to let you know of some of the facilities available - a detailed description of each of the commands used is available using the help command.

Thresholding :

To make any graylevel image into a a binary image (0,1 image) at say a threshold of half the maximum brightness value try :
maximum=max(max(img));
binimg=(img>maximum);
The max operator returns a vector if applied to a matrix and a number if applied to a vector - so to get the maximum graylevel value in a matrix it has to be applied twice. The same is true for the median, std and min functions.

Convolutions :

Matlab has facilities for both 1D and 2D convolutions as implemented in the functions conv and conv2. For example continuing on from Section 2 to get a simple edge detection mask convolved with img try :
result=conv2(img,[-1 -1 -1;-1 8 -1;-1 -1 -1],'same');

Fourier Transforms :

There are also facilities for 1D and 2D forward and inverse Fourier Transforms - try the commands fft, fft2, ifft and ifft2. The command fftshift centers the Fourier spectrum origin to the center of the image. Note that the results of these are complex and to display them one needs to decide on a reasonable representation such as for example the modulus. As an example to display the centered Fourier transform for the image in img type :
fouimg=fft2(img);
fouimg=fftshift(fouimg);
grdisp(abs(fouimg));    
The phase can be displayed by using grdisp(angle(fouimg)) and the real and imaginary parts using the real and imag operators. It is worth remembering that multiplication in the Fourier domain in the case of an equation of the form G(u,v)=F(u,v)H(u,v) would actually be implemented by element-wise multiplication of F and H using the .* operator and not normal matrix multiplication.

The Source code for the utility functions

This is included here mainly as examples of how to write Matlab function files. You are free to modify these as you please but please change the name to something else to avoid confusion.

The grdisp function

%----------------------------------------------------------------
% Function grdisp()
%    -- Xenios Papademetris papad@noodle.med.yale.edu 5th Sep 1995
%
%    -- used to display images stored as matrices
%    -- scales graylevls to 1..64 range for display within matlab
%----------------------------------------------------------------

function grdisp(img)

%----------------------------------------------------------------
% Step 1 -- Check for right number of parameters
%----------------------------------------------------------------

if nargin ~= 1	
  error('Requires one input argument e.g. grdisp(img)');
end

%----------------------------------------------------------------
% Step 2 - Scale image to make it in displayable range
%----------------------------------------------------------------

temp=img;
temp=temp-min(min(img));
temp=temp*64/(max(max(temp)));

%----------------------------------------------------------------
% Step 3 - Display Image and set colormap to grayscale
%----------------------------------------------------------------

image(temp);
colormap(gray);

%----------------------------------------------------------------



The grload function

%----------------------------------------------------------------
% Function grload()
%    -- Xenios Papademetris papad@noodle.med.yale.edu 5th Sep 1995
%
%    -- used to load images stored in the simple format (.grl) used for the 
%    -- EE445a course, this has an unsigned short magic number (29571) 
%    -- and the width and height of the image in 4-byte integers
%    -- followed by the actual data in unsigned char format
%----------------------------------------------------------------

function outimage=grload(filename)

%----------------------------------------------------------------
% Step 1 -- Check for right number of parameters
%        -- and check for valid filename
%----------------------------------------------------------------


if nargin ~= 1	
  error('Requires one input argument eg grload(filename)');
elseif nargin == 1 & isstr(filename)
  if (isempty(findstr(filename,'.'))==1)
        filename=[filename,'.grl'];
  end
end

%----------------------------------------------------------------
% Step 2 -- Open filename
%        -- Check for valid file
%----------------------------------------------------------------

handle=fopen(filename,'r');

if handle == -1
	ff=['grload::cannot open file ' , filename];
	error (ff);
end

magic=fread(handle,1,'ushort');

if magic~=29571
	ff=['grload::file ' , filename,' is not a grl file'];
	error (ff);
end

%----------------------------------------------------------------
% Step 3 -- Read width and height	
%----------------------------------------------------------------

width=fread(handle,1,'int32');
height=fread(handle,1,'int32');

%----------------------------------------------------------------
% Step 4 -- Read actual Image
%----------------------------------------------------------------

outimage=fread(handle,[height,width],'uchar');
outimage=outimage'/max(max(outimage));

%----------------------------------------------------------------
% Step 5 -- Close file
%----------------------------------------------------------------

fclose(handle);

%----------------------------------------------------------------

The grsave function

%----------------------------------------------------------------
% Function grsave()
%    -- Xenios Papademetris papad@noodle.med.yale.edu 5th Sep 1995
%
%    -- used to save images stored in the simple format (.grl) used for the 
%    -- EE445a course, this has an unsigned short magic number (29571) 
%    -- and the width and height of the image in 4-byte integers
%    -- followed by the actual data in unsigned char format
%    -- if numbers outside 0..255 it will scale to fit range
%----------------------------------------------------------------

function grsave(outimage,filename)

%----------------------------------------------------------------
% Step 1 -- Check for right number of parameters
%        -- and check for valid filename
%----------------------------------------------------------------

if nargin ~= 2
  error('Requires two input arguments grsave(img,filename)');
elseif nargin == 2 & isstr(filename)
  if (isempty(findstr(filename,'.'))==1)
        filename=[filename,'.grl'];
  end
end

handle=fopen(filename,'w');

if handle == -1	
	ff=['grsave::cannot open file ' , filename];
	error (ff);	
end

%----------------------------------------------------------------
% Step 2 -- Save Header first 
%        -- header = [ Magic Number , width , height ]
%----------------------------------------------------------------

magic=29571;
fwrite(handle,magic,'ushort');
[width height]=size(outimage);
fwrite(handle,width,'int32');
fwrite(handle,height,'int32');

%----------------------------------------------------------------
% Step 3 -- Scale image if needed to fit 8-bit range
%        -- 0..255
%----------------------------------------------------------------

temp=outimage';
if min(min(temp))<0 
	temp=temp-min(min(img));
  end

temp=temp*255/(max(max(temp)));


%----------------------------------------------------------------
% Step 4 -- Save image itself in unsigned char format
%        -- and close file
%----------------------------------------------------------------

fwrite(handle,temp,'uchar');
fclose(handle);

%----------------------------------------------------------------
Back to the top of this document.
Xenios Papademetris 16th Jan 1996, revised 24th Sep 1997.
papad@noodle.med.yale.edu