0% found this document useful (0 votes)
30 views45 pages

Lab 1

Uploaded by

kirito001125
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views45 pages

Lab 1

Uploaded by

kirito001125
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Universiti Tunku Abdul Rahman

Faculty Lee Kong Chian Faculty of Engineering and Science


Department: Department of Mechatronics and BioMedical
Engineering
Unit Code and Name UEMB3244 Medical Imaging
Experiment No.: 1
Title of Experiment: Introduction to Medical
Laboratory Room No. and Name: Any computer lab with Matlab image processing
toolbox
Experiment Duration (hour): 3 hours
Number of Students per Group 1 student
Objectives (Optional)

Introduction

Equipment and Materials


Quantity estimation
Item Description *Item category (e.g. per set/group of
student)
MATLAB with image processing toolbox S 1 per student

*Item category
SP Sample or specimen
C Consumable Caution Statement (Optional)
CH Chemical
W Labware, glassware, tool, and Procedure
components
E Equipment Questions & Report Writing
S Software
Introduction to Matlab
UEMB3244 Medical Imaging

Practical 1
Chapter Outline
• Starting MATLAB
• Familiarization with MATLAB Desktop
• Using MATLAB as a Calculator
• Help features in MATLAB
• Elementary Math Built-in Functions
• Working with Variables
Starting MATLAB
Current MATLAB Desktop
Directory

Workspace
Command
Window

Command
History
Order of Precedence

Matrix Operators Array operators


() parentheses
' comp. transpose .' array transpose
^ power .^ array power
* multiplication .* array mult.
/ division ./ array division
\ left division
+ addition
- subtraction

(In the order of precedence – which operator will be executed first;


top to bottom = > first to last)
Elementary Math Built-in Functions
- MATLAB has a very large library of built-in
functions

How do we know the syntax for using the


following functions?

Trigonometric – cos, acos, exp, sin, asin


Exponential – log, exp, sqrt
Complex – abs, angle, conj
Discrete Maths – factor, primes, gcd

>> doc elfun


Help Features with MATLAB

You can use the MATLAB help features to


understand the syntax in using some of the
MATLAB functions if you already know the
function name

Type any of the following options at the


MATLAB Command Line:

• help function_name
• helpwin function_name
help mean
• doc function_name
Accessing the Help Browser Via the
Startup Menu
Help Browser
Creating Variables in MATLAB
Variable name Assign operator Value

>> x = 3;
>> y = 4i;
>> z = (x+y)*(x-y)
z=
25

>> t = 0.1
t=
0.1000
>> x = sin(3*t + pi/2)
x=
0.9553
Type of MATLAB Arrays
• Scalars - just single element arrays
a=[1]

• Row Vectors - separated by a blank character or a comma


b=[1 2 3 4] or b=[1,2,3,4]

• Column vectors - separated by semicolons or transpose a row vector to


column vector by apostrophe
c=[1;2;3;4] or c=[1 2 3 4]’

• MATRIX - semicolon ‘;’ to start a new line


d=[1,2,3,4 ; 5,6,7,8]
Creating Vectors and Matrices

» a=[1 2 3 4]
a = Entering a row
vector
1 2 3 4

» b=[1;2]
b = Entering a column
1 vector
2
» c=[1 2; 3 4]
c = Entering a
1 2 matrix
3 4
The Colon (:) Operator

» a=[1 2 3 4] These two


a = expressions
1 2 3 4 denote exactly
the same
vector...
» b=1:4
b =
1 2 3 4

» c=6:-2:0 The increment


c = value is the
6 4 2 0 middle
expression
Manipulating Matrices

» a=[1 2 3; 4 5 6; 7 8 9]

a=
1 2 3 a([1 2 3],3)
a(1:3,3)
4 5 6 a(:,3)
a(1,1)

7 8 9

a(2:3,1:2)
Boolean Indexing
Boolean Operators >> Mass = [-2 10 NaN 30 -11 Inf 31];
= = equal to >> each_pos = Mass>=0
each_pos =
> greater than 0 1 0 1 0 1 1
< less than >> all_pos = all(Mass>=0)
all_pos =
~ not
0
& and >> pos_fin = (Mass>=0)&(isfinite(Mass))
| or pos_fin =
0 1 0 1 0 0 1
isempty() >> good_mass = Mass(pos_fin)
isfinite(), etc. . . . good_mass =
10 30 31
any()
all()
1 = TRUE
0 = FALSE
>> bool_ops
Strings as Variables
- A string is an array of characters and can include letters, digits, other
symbols and spaces
- Created using single quote delimiter (')

>> str = 'Hi there,'


str =
Hi there,
>> str2 = 'Isn''t MATLAB great?'
str2 =
Isn't MATLAB great?

- Each character is a separate matrix element (16 bits of memory per


character)

str = H i t h e r e , 1x9 vector

- Indexing same as for numeric arrays


MATLAB Workspace Browser and Array
Editor

How do I locate my
• The MATLAB Workspace Browser allows you to access variables created in
to the data or variables created in the current MATLAB?
MATLAB session.
• By selecting the Workspace tab or use the functions
who and whos.
• The MATLAB Array Editor is use to view and edit a
visual representation of variables in the workspace.

Workspace
Commands for Managing Variables

MATLAB Function Usage


cd/pwd, ls/dir Navigating directories
what Displays files in a directory (grouped by type)
! Invoke DOS commands from MATLAB
clear Remove function or variable from memory
clear X Y Z Remove only variables X,Y & Z from memory
who, whos List workspace variables
size Returns the size of a matrix (rows and columns)
Basic Plotting
>> x=-5:5;
>> y=x.^2;
>> plot(x,y,'-')
>> hold on
>> plot(x,25-y,'r-o')
>> hold off

Note: Please refer to help plot for how to plot using


different line types, plot symbols and colors.
Subplots
SUBPLOT- display multiple axes in the same figure window
subplot(#rows, #cols, index) >> subplot(2,2,1);
>> plot(1:10)

>> subplot(2,2,2)
>> x = 0:.1:2*pi;
>> plot(x,sin(x))

>> subplot(2,2,3)
>> x = 0:.1:2*pi;
>> plot(x,exp(-x),'r')

>> subplot(2,2,4)
>> subplotex >> plot(peaks)
Images
>> a = magic(4) Use row 2 of
a = colormap for
16 2 3 13 pixel (1,2)
5 11 10 8
9 7 6 12
4 14 15 1
>> image(a);
>> map = hsv(16)
map =
1.0000 0 0
1.0000 0.3750 0 Row 2
1.0000 0.7500 0 .....
>> colormap(map)
Built-in colormap
Colormap
Colormap Name
Name Color
Color Scale
Scale Old built-in
colormap
parula
parula
jet
jet
hsv
hsv
hot
hot
cool
cool
spring
spring
summer
summer
autumn
autumn
winter
winter
gray
gray
bone
bone
copper
copper
pink
pink
lines
lines
colorcube
colorcube
prism
prism
flag
flag
white
white
Example: Images and Colormaps

The MathWorks

>> load cape


>> image(X)
>> colormap(map)
OR
>> imshow(X,map)
M-Files: Scripts and Functions
• M-files allow batch execution of a list of legal MATLAB statements.
• Scripts
• Executed line-by-line
• Variables created in the current workspace (base workspace if called from the
command line)
• Functions
• The first line starts with the word function
• Can accept input arguments and return output arguments
• Variables created in the function’s workspace
Structure of a Function M-file
Keyword: function Function Name (same as file name .m)
Output Argument(s) Input Argument(s)

function y = mymean(x)
%MYMEAN Average or mean value.
% For vectors, MYMEAN(x) returns the mean value.
Online Help
% For matrices, MYMEAN(x) is a row vector
% containing the mean value of each column.
[m,n] = size(x);
if m == 1
MATLAB
Code m = n;
end
y = sum(x)/m;
Sample Problem 4: Area of Triangle
The area, A, of a triangle with sides of length a, b and c is given by:

A = √ s (s – a)(s – b)(s – c) ,
where s = (a + b + c)/2.

Write a MATLAB function that will accept the values a, b and c as


inputs and return the value of A as output.

Tips :
(a) Decide on the name of function. Ex: myarea.m
(b) First line of the file must have the format
function [list of outputs] = function_name (list of inputs)
(c) Document the function (using %)
(d) Finally, include the code that defines the function
Comparison between Script Files and
Function Files
Similarities and Differences between the two files:

➢ Both files are saved with the extension .m


➢ The first line in a function file is the function definition line
➢ The variables in a function file are local. The variables in a script file
are recognized in the Command Window
➢ Script files can use variables that have been defined in the workspace
➢ Script files contains a sequence of MATLAB commands, also called a
program
➢ Function files can accept data through input arguments and can return
data through output arguments
➢ When a function file is saved, the name of the file should be the same
as the name of the function
Logical Control Programming
Constructs
• Works on conditional statements
• Short-circuited in MATLAB - once a condition is true, or case
matched, the sequence terminates
• switch-case statements are more efficient than if-elseif
statements when working with strings
if s == ‘1’ switch s
k=1;j=1; case ‘1'
elseif s == ‘2’ k=1;j=1;
k=1;j=2; case ‘2’
else k=1;j=2;
errordlg('Undefined key') otherwise
end errordlg('Undefined key')
end
Exercise: Calculating Worker’s Pay

A worker is paid accordingly to his hourly wage up


to 40 hours, and thereafter 50% more for overtime.

Write a script file to compute the pay. The program


asks the user to enter the number of hours and the
hourly wage, then displays the pay.

t = input('Enter the number of hours worked: '); Matlab codes


to get inputs
h = input('Enter the hourly wage in RM: '); from the user
Solution: Calculating Worker’s Pay

t = input('Enter the number of hours worked: ');


h = input('Enter the hourly wage in RM: ');

Pay = t*h;
if t>40
Pay = Pay + (t-40)*.50*h
end
sprintf('The worker''s pay is RM %5.2f \r ',Pay);
Iterative Loops
• Similar to other programming languages
• for -- Repeats loop a set number of times (based on index)
• while -- Repeats loop until logical condition returns FALSE

N = 10; I=1; N=10;


for N = 1:1:10 while I < N
I(N)= 1/N I=I+1;
end end

disp('I is equal to N after


increment process in while
loop')
Exercise- loop iterations
• Write a script to display a “Hello World!!!” for 50
times using for loop

• Write a script to display a “Hello World!!!” for 50


times using while loop
Image Types
• Four basic types of images are supported in MATLAB
• Binary images: {0, 1}
• Intensity images: [0, 1], uint8, or uint16
• Indexed images: m-by-3 colormap matrix
• RGB images: m-by-n-by-3 matrix
Image Types: MATLAB Data Types
• A wide array of different data types exist in MATLAB, but only a
subset of the data types are used to represent images in MATLAB.

Image data types


Image Types: File Formats
Format Name Variants Image Type
Windows 1-, 4-, 8-, 16-, 24-, and 32-bit RGB
Bitmap (BMP) uncompressed images and 4- and 8-bit Indexed
run-length encoded (RLE) images
Joint Any JPEG image including image type RGB
Photographic (grayscale or RGB), bitdepth, and Intensity
Experts Group compression information
(JPG, JPEG) (lossy/lossless)
Portable 1-, 2-, 4-, 8-, and 16-bit grayscale RGB
Network images; 8- and 16-bit indexed images; Intensity
Graphics (PNG) and 24- and 48-bit RGB images
Indexed
Tagged Image 1-, 8-, and 24-bit uncompressed RGB
File Format (TIF, images; 1-, 8-, and 24-bit images with Intensity
TIFF) packbits compression; 1-bit images
with CCITT compression; and 16-bit Indexed
grayscale, 16-bit indexed, and 48-bit
RGB images
Overview: How Images are
Represented in MATLAB
Image Type Indexed Intensity Binary RGB

Image is an M-by-N Image is an M-by-N Not Applicable Image is an


array of integers in the array of floating- (Image is an M-by- M-by-N-by-3
range [1,P]. point values. The N logical array array of
conventional containing only 0's floating-point
double Colormap is a P-by-3 dynamic range is and 1's). values in the
Data array of floating-point [0,1]. range [0,1].
values in the range [0,1].

Image is an M-by-N Image is an M-by-N Not Applicable. Image is an


array of integers in the array of unsigned 8- M-by-N-by-3
range [0,P-1]. Where P bit or 16-bit integers. array of
8
is no greater than 2 The conventional floating-point
16
uint8 or (256) or 2 (65536). dynamic range is values in the
uint16 [0,255] or [0,65535]. range [0,255]
Data Colormap is a P-by-3 or [0,65535].
array of floating-point
values in the range [0,1].
Image Types: Binary Images
• In a binary image, each pixel assumes one of two discrete values: zero
(off) and one (on).
Image Types: Intensity Images
• An intensity image only consists of one matrix, I, whose values
represent intensities within some range, for example [0, 1] or uint8.
Image Types: Indexed Images
• An indexed image consists of a data matrix, X, and a colormap matrix,
map.
Image Types: RGB Images
• RGB image is stored in MATLAB as an m-by-n-by-3 data where each
m-by-n page defines red, green and blue color components for each
pixel.
Importing and Exporting Images in MATLAB
Command line
• imfinfo - Returns info about graphics file.
• imread - Read image from graphics file.
• imwrite - Write image to graphics file.

Graphical user interface


• uiimport - Starts the Import Wizard.
>> imfinfo('canoe.tif')
>> [X,map] = imread('canoe.tif');
Displaying Images
• imtool - Display image in Image Viewer.
• imshow - Display image.
• image - Create and display image object (MATLAB).
• imagesc - Scale data and display as image (MATLAB).
• colorbar - Display colorbar (MATLAB).
• colormap - Sets the color map of the image (MATLAB).
• montage - Display multiple image frames.
• truesize - Adjust display size of image.
• warp - Display image as texture-mapped surface.
>> imtool(X,map);
% or
>> imshow(X,map);
>> colorbar
Displaying Multiple Images
• An example of displaying multiple image frames as
a rectangular montage.
>> load mri
>> montage(D,map);

Note: The montage


function requires the
image to be m-by-n-
by-1-by-k for binary,
intensity, and indexed
images, and
m-by-n-by-3-by-k
for RGB images.
Further reading
• https://www.mathworks.com/help/matlab/getting-started-with-
matlab.html (Matlab official site, a very useful place to learn about the
basics.)

• https://web.stanford.edu/class/ee254/software/getstart.pdf

• https://uk.mathworks.com/help/images/ (Image Processing Toolbox of


Matlab)

• https://www.mathworks.com/help/matlab/images_btfntr_-1.html
(working with images in Matlab)

You might also like