CSE107 Matlab Introduction
Matlab programming language and software development environment Matlab Image Processing Toolbox (IPT)
Matlab overview High performance language for technical computing Matlab = “matrix laboratory” Array based – very linear-algebra like Made by MathWorks
Matlab overview Not cheap – academic prices ~$500/seat Student version available Free from UC Merced IT? Fully functional (?) Simulink Simulation and Model-Based Design Graphical tool for connecting modules in a work-flow type environment Open source alternative Octave is a free computer program for performing numerical computations which is mostly compatible with MATLAB (source: Wikipedia)
Matlab overview Advantages Disadvantages Lots of built-in functionality especially via toolboxes Math-like Good visualization Good for learning and prototyping Disadvantages Can be slow Not free
Matlab overview Let’s take a look… Starting Matlab Windows Linux
Matlab overview Matlab desktop Command Window Workspace Browser Current Directory Command History Windows One or more Figure Windows
Matlab overview Matlab is a scripting language – interpreted Interactive Can type commands in Command Window Can run scripts (.m files) ~ programs Functions also stored in .m files
Matlab overview Editing .m files Matlab editor Any text editor Graphical Debugging Any text editor
Matlab overview Matlab help Graphical Text MathWorks website Help->Matlab Help doc <function> Text help <function> lookfor <keyword> -all MathWorks website http://www.mathworks.com/access/helpdesk/help/techdoc/
Matlab overview Can save/load workspaces and variables
Matlab overview Defining/declaring variables who whos Comments The semicolon (;) clear [all]
Matlab overview .m files containing scripts Running .m files – just type name Search path for .m files File->Set path Editing .m files: edit <filename.m> Debugging
Matlab overview intro.m
Matlab overview – data types © 2004 R. C. Gonzalez, R. E. Woods, and S. L. Eddins www.imageprocessingbook.com
Matlab overview – data types Converting between data types Ex: a = uint8(b) Double->uint8 Values < 0 mapped to 0 Values > 255 mapped to 255 Fractions discarded Be aware of this!
Matlab overview - vectors 1xN dimensional array is called a row vector Index of first element is 1 (not 0) Initialize using square brackets >> v = [1 3 5 7 9] v = 1 3 5 7 9 >> v(2) ans = 3
Matlab overview - vectors Convert row vector to column vector and vice versa using transpose operator (‘) >> w = v' w = 1 3 5 7 9
Matlab overview - vectors To access blocks of elements, use colon (:) notation >> v(1:3) ans = 1 3 5 >> v(3:end) 5 7 9
Matlab overview - vectors Indexing not restricted to contiguous elements >> v(1:2:5) ans = 1 5 9 >> v(5:-2:1) 9 5 1
Matlab overview - vectors Colon by itself returns column vector >> v(:) ans = 1 3 5 7 9
Matlab overview - vectors Can index into a vector using a vector >> v([1 4 5]) ans = 1 7 9
Matlab overview - matrices Matrices can be initialized as sequence of row vectors separated by semicolons (;) >> A = [1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9
Matlab overview - matrices Index into matrices using two indices >> A(2,3) ans = 6
Matlab overview - matrices Use colon to select rows and columns >> C3 = A(:,3) C3 = 3 6 9 >> R2 = A(2,:) R2 = 4 5 6
Matlab overview - matrices Use colon to select blocks >> T2 = A(1:2, 1:3) T2 = 1 2 3 4 5 6
Matlab overview - matrices Can also use colon for assignment >> B = A; >> B(:,3) = 0 B = 1 2 0 4 5 0 7 8 0
Matlab overview - matrices Can index using logical data types >> D = logical([1 0 0; 0 0 1; 0 0 0]) D = 1 0 0 0 0 1 0 0 0 >> A(D) ans = 1 6
Matlab overview - matrices Can use comparison operators to index >> A(B==0) ans = 3 6 9 >> E = (B==0) E = 0 0 1 >> whos E Name Size Bytes Class E 3x3 72 double array (logical) Grand total is 9 elements using 72 bytes
Matlab overview - matrices Use find function to determine indices of values satisfying condition >> [i,j] = find(B~=0); >> i' ans = 1 2 3 1 2 3 >> j' 1 1 1 2 2 2
Matlab overview - matrices Use ndims to find dimension >> d = ndims(A) d = 2
Matlab overview - matrices Use size to find sizes of dimensions >> size(T2) ans = 2 3 >> size(T2,1) 2 >> size(T2,2) 3
Matlab overview - matrices Can specify dimension for many functions >> sum(T2) ans = 5 7 9 >> sum(T2,1) >> sum(T2,2) 6 15
Matlab overview - matrices Can recurse to compute over all dimensions >> sum(sum(T2)) ans = 21
Matlab overview – standard arrays zeros(M,N) -> MxN matrix of zeros of type double ones(M,N) -> MxN matrix of ones of type double rand(M,N) -> MxN matrix of uniformly distributed random numbers in the interval [0,1] randn(M,N) -> MxN matrix of normally (Gaussian) distributed random numbers with mean 0 and variance 1
Matlab overview – standard arrays >> A = 5*ones(3,3) A = 5 5 5 >> B = rand(2,4) B = 0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185
Matlab overview - .m file programming Operators 3 types of operators Arithmetic operators that perform numeric computations Relational operators that compare operands quantitatively Logical operators that perform the functions AND, OR, and NOT
Arithmetic operators I © 2004 R. C. Gonzalez, R. E. Woods, and S. L. Eddins www.imageprocessingbook.com
Arithmetic operators II © 2004 R. C. Gonzalez, R. E. Woods, and S. L. Eddins www.imageprocessingbook.com
Relational operators © 2004 R. C. Gonzalez, R. E. Woods, and S. L. Eddins www.imageprocessingbook.com
Matlab overview - .m file programming Relational operators 1 2 3 4 5 6 7 8 9 >> B = [0 2 4; 3 5 6; 3 4 9] B = 0 2 4 3 5 6 3 4 9 >> A == B ans = 0 1 0 0 1 1 0 0 1
Important variables and constants © 2004 R. C. Gonzalez, R. E. Woods, and S. L. Eddins www.imageprocessingbook.com
Flow control statements © 2004 R. C. Gonzalez, R. E. Woods, and S. L. Eddins www.imageprocessingbook.com
IPT overview: digital image representation What’s the difference? © 2004 R. C. Gonzalez, R. E. Woods, and S. L. Eddins www.imageprocessingbook.com
IPT overview: images as matrices images as functions: images as matrices:
IPT overview: reading images Use imread() to read images from file help imread >> f = imread('hong_kong.jpg'); >> size(f) ans = 690 498 >> whos f Name Size Bytes Class f 690x498 343620 uint8 array Grand total is 343620 elements using 343620 bytes >> f(1,1) 38 >> f
IPT overview: reading images © 2004 R. C. Gonzalez, R. E. Woods, and S. L. Eddins www.imageprocessingbook.com
IPT overview: displaying images Use imshow() to display images help imshow >> imshow(f) >> imshow(f,[50 100]) Be careful about the dataype of f!
IPT overview: more on imshow help imshow IMSHOW Display image in Handle Graphics figure. IMSHOW(I) displays the grayscale image I. IMSHOW(I,[LOW HIGH]) displays the grayscale image I, specifying the display range for I in [LOW HIGH]. The value LOW (and any value less than LOW) displays as black, the value HIGH (and any value greater than HIGH) displays as white. Values in between are displayed as intermediate shades of gray, using the default number of gray levels. If you use an empty matrix ([]) for [LOW HIGH], IMSHOW uses [min(I(:)) max(I(:))]; that is, the minimum value in I is displayed as black, and the maximum value is displayed as white. IMSHOW(RGB) displays the truecolor image RGB. IMSHOW(BW) displays the binary image BW. IMSHOW displays pixels with the value 0 (zero) as black and pixels with the value 1 as white. IMSHOW(X,MAP) displays the indexed image X with the colormap MAP.
IPT overview: displaying images Use impixelinfo to examine pixel values in currently displayed image help impixelinfo figure – Open new figure window close all – Close all figure windows
IPT overview: writing images Use imwrite to write images to file help imwrite Use imfinfo to get information about image file help imfinfo Use File->Export to save a figure to file Can also save figure using command print –fno –dformat –rres filename
IPT overview: image types IPT supports four types of images Intensity images (“grayscale”) Binary images (“black and white”) Indexed images (color) RGB images (color)
IPT overview: converting between image types Be careful about how ranges are mapped: [0,255] [0,1] © 2004 R. C. Gonzalez, R. E. Woods, and S. L. Eddins www.imageprocessingbook.com
IPT overview: converting between image types >> h = uint8([25 50; 128 200]); >> g = im2double(h); >> g g = 0.0980 0.1961 0.5020 0.7843 >> f = double([-0.5 0.5; 0.75 1.5]); >> g = im2uint8(f); >> g g = 0 128 191 255
Matlab overview - .m file programming Code optimization – preallocating arrays Preallocating arrays: use zeros() for example for x=1:M f(x) = A * sin((x-1)/(2*pi)); end or f = zeros(M,1); % preallocate the array for x=1:M f(x) = A * sin((x-1)/(2*pi)); end
Matlab overview - .m file programming Code optimization – preallocating arrays sin_no_preallocate.m sin_preallocate.m
Matlab overview - .m file programming Code optimization – preallocating arrays Improves code execution time Helps reduce memory fragmentation
Matlab overview - .m file programming Code optimization – vectorizing loops Vectorizing loops: converting for and while loops to equivalent vector or matrix operations. for x=1:M f(x) = A * sin((x-1)/(2*pi)); end or x = 0:M-1; f = A * sin(x/(2*pi));
Matlab overview - .m file programming Code optimization sin_loop.m sin_vectorize.m
Matlab overview - .m file programming Interactive output I disp(argument) >> A = [1 2; 3 4]; >> disp(A); 1 2 3 4 >> sc = 'Digital Image Processing'; >> disp(sc); Digital Image Processing
Matlab overview - .m file programming Interactive output II fprintf(1,’format’,argument); >> x = 5; >> fprintf(1,'x = %.5f',x); x = 5.00000 >> fprintf(1,'x = %e',x); x = 5.000000e+000
Matlab overview - .m file programming Interactive input t = input(‘message’, ‘s’) >> t = input('Enter you data: ','s'); Enter you data: 1,2,4 >> disp(t) 1,2,4 >> class(t) ans = char >> size(t) 1 5 >> n=str2num(t) n = 1 2 4 >> class(n) double >> size(n) 1 3
Matlab overview - .m file programming Plotting help plot plot_example.m
Matlab overview - .m file programming Cell arrays Cell array: multidimensional array whose elements are copies of other arrays Allows you to mix datatypes >> c = {'gauss', [1 0; 0 1], 3} c = 'gauss' [2x2 double] [3] >> c{1} ans = gauss >> c{2} 1 0 0 1 >> c{3} 3
Matlab overview - .m file programming Structures Structures: similar to cell arrays except addressed by fields >> S.char_string = 'gauss'; >> S.matrix = [1 0; 0 1]; >> S.scalar = 3; >> S S = char_string: 'gauss' matrix: [2x2 double] scalar: 3 >> S.matrix ans = 1 0 0 1