Sei sulla pagina 1di 28

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !

ob" #rec$on

Matlab Primer #2 - Programming


Introduction: Although it has much of the attracti%e high&le%el functionalit" of a software 'pac$age() Matlab is most definitel" a bona-fide computer language with its own programming constructs and s"ntax* It is naturall" outside the scope and purpose of this primer centred on Matlab image processing to offer a comprehensi%e treatment of the Matlab language+* ,ather) our aim here is to offer a brief discussion -with illustrati%e examples. of the $e" programming constructs within -and features of. Matlab* !hus) our brief presentation is limited to essentials in the belief that master" of the details and finer points) as with all computer languages) will come through a combination of practice and experience* Matrices and Arrays Most introductions to the Matlab language begin with a discussion of arra"s and matrices* !his discussion is no exception* !he wa" in which Matlab defines and deals with arra"s and arra" operations is a strong distinguishing feature which allows efficient and compact code to be written so that grasping the essentials of arra" handling is one of the most important things for the new user to grasp* In fact) it is useful in the beginning to consider that every quantity (whether numeric or text) created by Matlab is simply an array2. Matlab -an amalgam of MATrix LABorator". was originall" designed specificall" to allow eas" and comprehensi%e calculation/manipulation of matrices* Mathematicall" spea$ing) we need to be aware of the distinction between matrices and arrays* As computational ob0ects) matrices are simpl" arra"s i*e* ordered rows and columns of numerical %alues* 1owe%er) matrices are a t"pe of arra" to which we attach a definite mathematical meaning and to which certain operations -e*g* matrix multiplication) transpose etc. can be meaningfull" applied* Arra"s on the other hand are often 0ust con%enient wa"s of storing and organi2ing data which can be numeric) textual or a combination of both and Matlab pro%ides man" useful wa"s of manipulating and dealing with these 3uite general arra"s* !he $e" point then is that within Matlab there is no distinction between arrays and matrices* Arra"s and matrices are identical entities and it is onl" the user who can decide if the 3uantit" he has defined is a 'matrix( in the proper mathematical sense or simpl" an arra"* In the following discussion) no attempt is therefore made to distinguish between them and it will generall" be clear from context whether a gi%en arra" is a matrix*

A comprehensi%e treatment is gi%en in Mastering Matlab) 1anselman and 4ittlefield) Prentice 1all* !he extensi%e Matlab documentation pro%ided with the software is also %er" readable and informati%e * 5 !his is not strictl" true but sufficientl" close to the truth that it will ser%e its purpose*

www*fundipboo$*com Matlab Primer 65

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

Creating arrays in Matlab !he simplest wa" of creating small arra"s in Matlab is to manuall" enter the elements in the command window) row b" row* !r" entering the commands gi%en below7

Matlab Commands <<A?@+ 5 ;A B C DE <<#?@D C BA ; 5 +E

What s !a""ening >Create a 5 x ; matrix A >Create a 5 x ; matrix #

Comments !he enclosing s#uare brac$ets indicate that the contents form an arra"* A semicolon within the brac$ets indicates the start of a new row*

A %ector is 0ust a +&D arra" 7 <<%ec?@F + +E >create ; element row %ector) %ec

8e can turn a row %ector into a column %ector) b" using the transpose operator << %ec?%ec= or) of course) transpose a 5&D arra" 7
<<A= >!ranspose A

>ma$e %ec a transposed %ersion of itself

8e can also create 9string: arra"s which contain text << alph?@=ab=A=cd=E << alph-5)5. >Create 5x5 arra" of characters >Displa" element in 5nd row) 5nd column -d.

All 2-D arrays must be rectangular or square in other words) to be a legal arra" each row in the arra" must ha%e the same number of elements ;* !he same principle applies to arra"s of higher dimension* !hus a legal ;&D arra" must comprise a 'stac$( of 5&D arra"s
;

So&called cell arra"s and structures are ad%anced data structures which can be used to circum%ent this restriction when needed* 8e must defer discussion of these data structures for later examples in the boo$ but for the impatient reader) t"ping doc struct and doc cell at the Matlab prompt for information on the basic idea and use*

www*fundipboo$*com Matlab Primer 65

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

of similar dimensions) a legal B&D arra" a group of ;&D arra"s of similar dimensions and so on* Accessing indi%idual elements in an array Indi%idual arra" elements are accessed using subscripts as follows7& Matlab Commands <<%ec-5. <<A-+)5. What s !a""ening > %ec-5. is the second element of %ec > ,eturn element in the +st row) 5nd column

8e can change or correct the %alues of arra" elements b" indexing them indi%iduall"7 <<A-+)5.?D >Set element in +st row) 5nd column to D

Arra"s can be ;&D -or ha%e e%en higher dimensionalit". 7 Matlab Commands <<C?imread-9football*0pg:.A <<C-+5H);I)+. What s !a""ening >,ead in ,G# -colour. image of football >Get , -red. %alue at gi%en pixel -?;5. Comments )ote the use o& the semi-colon a&ter Matlab command to suppress the out"ut o& the %alues o& the matri* %ariable C to the screen(

Accessing grou"s o& elements in an array ' the colon o"erator Matlab has a %er" important and powerful colon operator - : .* !his can be used to create %ectors and for subscripting arra"s* 1ere:s a couple of examples of its use in creating %ectors & Matlab Commands <<x?+7+F <<"?F7C7+FF What s !a""ening > x?@+ 5 ;J +FE Increment is + >"?@F C +F **IC +FFE Increment is C

8e can also access groups of elements in an arra" b" using the colon operator to specif" the %ector indices( !r" the following 7& Matlab Commands << %ec-57;. <<#?A-+75)57;. <<C?A-+)+757;. What s !a""ening >Extract elements 5 and ; inclusi%e >Extract sub&arra" rows +& 5) columns 5&; >Extract +st and ;rd elements of +st row

www*fundipboo$*com Matlab Primer 65

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

8e can also use the colon operator to extract entire rows or columns of an arra"7& Matlab Commands <<A-7)+. <<A-5)7. What s !a""ening >Extract first column of A -ans?@+ A BE. >Extract 5nd row of A -ans?@5 ; BE.

8hen we use the colon operator along one of the arra" dimensions in this wa") we are effecti%el" allowing the index to range over the entire length of that dimension* !hus in the first example) A-7)+. means we fix the column number e3ual to + and extract all the elements in that column -i*e* the row index %aries from + up to its maximum %alue.* In the second example) A-5)7. we fix the row number e3ual to 5 and extract all the elements in that row -i*e* the column index %aries from + up to its maximum %alue.* !r" the exercise below* Primer Exercise 5*+ ,ead in the Matlab image =liftingbod"*png= -use function imread.* Extract the central CF> of the image pixels and displa" the image -use imshow.* Extract the first DB columns of the image and displa" them as a new image* Extract the rows ;; to DB inclusi%e of the image and displa" them as a new image* Concatenation o& arrays 8e can easil" concatenate -0oin together. arra"s to ma$e a larger arra"* In effect) we 0ust consider the elements of an arra" to be arrays themselves* Matlab Commands What << clearA << A?@+ 5A ; BE) #?@C DA K HE) C?@I +F ++ +5E << @A #E << @AA #E << @A #A CE s !a""ening >Clear wor$space >Create arra"s >A # are the 'columns( of new >arra"* ,esult has dimension 5xB* >A # are the 'rows( of new >arra"* ,esult has dimension Bx5* >,esult has dimension ;xB*

!he arra"s which form the elements of the concatenated arra" must be of conformable dimension i*e* the resulting arra" must be rectangular* For example) tr"ing to form the arra"s 7 << @AA CE << @A # CE

www*fundipboo$*com Matlab Primer 65

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

does not wor$ and Matlab responds with the appropriate error message
??? Error using ==> horzcat All matrices on a row in the bracketed expression must have the same number of rows.

!r" the exercises below7& Primer Exercise 5*5 ,ead in the Matlab images cameraman.tif and rice.tif -use the imread function.* Concatenate them to ma$e a single image and displa" the result -use imagesc or imsho, function.* Primer Exercise 5*; Generate the same result as in exercise 5*5* but this time using the Matlab function repmat* -Lse the Matlab help facilit" to find out how this function is used.*

Creating and +ealing With Larger Arrays Manual entr" as described abo%e is suitable onl" for relati%el" small arra"s* 4arger arra"s can be created in 5 basic wa"s* Matlab pro%ides a number of built in functions for creating and manipulating simple arra"s of arbitrar" dimension* !hese are outlined in the table 5*+ below*

www*fundipboo$*com Matlab Primer 65

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

-unction +escri"tion
2eros ones e"e repmat rand randn linspace logspace meshgrid Arra" of 2eros Arra" of ones Identit" matrix Ma$e tiled copies of input arra" ,andom arra" elements F + Mormall" distributed random arra" Nector with linear increments Nector with logarithmic increments Ma$e 5&D arra" from 5 input %ectors

.im"le e*am"le
A?2eros-B.A A?ones-B.A A?e"e-B.A A?e"e-B.A #?repmat-A)+)5.A A?rand-B.A A?randn-B.A A?linspace-F)+)+5.A A?logspace-F)+)+5.A @O)PE?meshgrid-+7+D)+7+D.A

Table 2(/: Matlab &unctions &or creating arrays #" suitable manipulation) we can create large arra"s with meaningful contents* !r" the following examples 7 Matlab Commands
<<A?randn-B. <<x?linspace-&+)+)CF.A "?x <<@O)PE?meshgrid-x)".A <<mesh-O*Q5RP*Q5. <<clearA <<A?ones-+5H.A surf-A.A <<A?imread-9rice*tif:.A <<#?repmat-A)5)5.A imshow-#.A << thresh?+FF*Srand-si2e-A..A << I?find-thresh<A.A << A-I.?FA imshow-A.

What s !a""ening
>Create normall" distributed random B x B arra"* >Ma$e %ector x of CF points linearl" spaced from &+ to + >Ma$e cop" " >Produce 5&D grid arra" for all combinations of x and "* >Surface height displa" of function OQ5RPQ5

>Generate arra" of ones) displa" as surface height* >,ead in rice image >Ma$e 5 x 5 tiled cop" and displa" >,andom arra" same si2e as A range F&+FF >Find all pixels at which random arra" is < A >Set them to 2ero and displa" modified image

Primer Exercise 5*B ,ead in the images rice.tif and cameraman.tif* Find all pixels for which the rice image has a %alue greater than that of the cameraman image and cop" the corresponding pixel %alues into the cameraman image* -Lse the Matlab function find. Displa" the result*

www*fundipboo$*com Matlab Primer 65

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

!he last example uses the powerful in&built find function and so&called linear indexing* 8e:ll discuss this function and the techni3ue of linear indexing shortl") so don:t worr" if all the last example is not completel" transparent* !hose with some pre%ious programming experience will note from the examples abo%e that there are no loop constructs -for) do) while etc. used to build and manipulate the arra"s* A feature of Matlab which distinguishes it from man" other languages is called implicit vectorisation* Mamel") if the input to a Matlab expression is a %ector or arra") Matlab $nows to e%aluate the expression at e%er" %alue of the input) producing an output that is also a %ector or arra"* A second wa" in which larger arra"s can be constructed is through use of appropriate loop constructs* !his is done in a wa" similar to most other languages* !he following example assigns the %alue + to all the elements in column +) 5 to all the elements in column 5 and so on 7 Matlab Commands
<<A?2eros-+D.A <<for i?+7+DA A-7)i. ? i*Sones-+D)+.A EndA

What s !a""ening
>Ma$e +D x +D 2ero matrix >begin for loop >#uild the columns of A >End for loop

!he next example creates an arra" that randoml" allocates %alues of F or + to the rows of an arra" b" 'flipping a coin(7 Matlab Commands
<<A?2eros-+D.A
<<for i?+7+D

What s !a""ening
>Create arra" of 2eros >Flip a coin with rand -<F*C ?? heads. >If 'heads( occurs) assign %alue + to >elements of column i >Displa" resulting arra"

if rand < F*C A-i ) 7. ?ones-+)+D. end end <<imshow-A.A

As a rule) "ou should tr" to a%oid loop constructs in Matlab where this is possible & especiall" for large arra"s* Matlab is an interpreted language and this means that loops execute slowl" compared to compiled code* 4oops are sometimes una%oidable and ha%e their place in the Matlab language and we shall sa" more about loop constructs later in this section* !he example below achieves the same purpose as the one abo%e but uses Matlab:s implicit %ectori2ation capabilities

www*fundipboo$*com Matlab Primer 65

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

Matlab Commands A?2eros-+D.A I?find-rand-+D)+.<F*C.A A-7)I.?+A

What s !a""ening >Create +Dx+D arra" of 2eros >Find indices at which +D random >numbers exceed threshold and assign >corresponding columns of A e3ual to +

Comments )ote ho, the Matlab code is %ery com"act and that the out"ut o& one &unction can directly constitute the in"ut to another 1e(g( find(rand.. etc) 2

+etermining the si0e o& arrays !he function whos onl" prints information to the screen about the si2e and t"pe of %ariables currentl" existing within the wor$space* !o determine the si2e of an arra" and actuall" assign this information to a %ariable in the wor$space) we must use the in&built size function* !he basic s"ntax is !m"n#$si%e(A) where the number of rows and columns in A are assigned to m and n respecti%el". For example 7 Matlab Commands
<<A?imread-9circuit*tif:.A dims?si2e-A.A

What s !a""ening
>,ead in image and ascertain si2e* @5HF 5K5E

1ere) dims is a 5 element row %ector containing the number of rows and number of columns* !r" the following 7 Matlab Commands
<<A?imread-9onion*png.A dims?si2e-A.

What s !a""ening
>,ead in colour image and ascertain si2e* >@+;C +IH ;E

!his time) dims is a ; element row %ector because A is an ,G# colour image and ,G# colour images are a composite of three separate 5&D images) one each for the red) green and blue components*

www*fundipboo$*com Matlab Primer 65

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

Array 3tility &unctions Matlab pro%ides some further in&built functions for arra" manipulation* Some of these are summarised in the table below 7 -unction reshape fliplr flipud tril triu rotIF 1ere are some fun examples to tr" out 7 Matlab Commands
<<A?imread-9cameraman*tif:.A imshow-A.A <<#?fliplr-A.A imshow-#. 66C?flipud-#.A imshow-C.A <<subplot-+);)+.) imshow-A.A <<subplot-+);)5.) imshow-#.A <<subplot-+););.) imshow-C.A

+escri"tion Change the shape of an arra" Trders the columns in re%erse order Trders the rows in re%erse order Extracts lower triangular part of arra" Extracts upper triangular part of arra" ,otates arra" counter&cloc$wise b" IF o

What s !a""ening
>Displa" original image matrix >Flip left&right and displa" >Flip upside&down and displa" >Displa" together in same window

Primer Exercise 5*C ,ead in the images rice.png and cameraman.tif * ,eflect the rice image about the x axis) the cameraman image about the " axis and add them together using Matlab:s ordinar" addition operator* Displa" the result using the function imshow

4elational and logical o"erators Comparison of two 3uantities is fundamental to an" language* Matlab includes all the common relational operators) summari2ed in the table below7& 4elational 5"erator U U? V? < <? ?? +escri"tion 4ess than 4ess than or e3ual to Mot e3ual to Greater than Greater than or e3ual to E3ual to

,elational operators can be used to compare two arra"s or an arra" to a scalar* !he output of all relational expressions produces logical arra"s with + where the expression is !rue and F where it is False* !hus) if A ? @ + ; 5 DE and # ? @F B ; BE) then A U # ? @F + + FE*

www*fundipboo$*com Matlab Primer 65

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

!r" the examples below 7& Matlab Commands


<< A?+A #?5A tf ? AU# <<A?@+ 5 ;EA #?@F 5 BEA tf ? A<?# <<A?;A #?@5 B F ; +EA tf ? A??#

What s !a""ening
>tf assigned %alue + because A is less than # >tf?@+ + FE & first two elements of A are <?those in # >tf?@F F F + FE because Bth element is the same as A

Mote that comparison ta$es place on an element by element basis) returning + where the relation is satisfied and F where it is not* Mote also the difference between the relational e3ualit" -??. and the assignment operator -?.* Warning 7
88 and 8 are distinct operators( The relational o"erator 88 tests &or the e#uality o& #uantities9 the assignment o"erator 8 is used to assign the out"ut o& an o"eration to a %ariable( This is a common source o& error: es"ecially &or beginners(

Logical o"erators 4ogical operators allow us to combine or negate relational expressions* Appl"ing these operators to relational expressions also results in logical -F&+. arra"s ha%ing %alue + where the expression is !,LE and F where it is FA4SE* !he basic logical operators in Matlab are gi%en in the table below* Some examples of their use is illustrated below 7& Matlab Commands
<<A?@+ 5 ;EA #?@F 5 BEA C?@+ ; 5EA <<#<A #<C <<V- #<A #<C. <<AUC W #V?C

What s !a""ening
>Assign matrices >ans?@F F +E onl" last element of # satisfies both >conditions >ans?@+ + FE 4ogical MT! of pre%ious example >ans?@+ + +E All elements of # are different from C

Matlab Logical 5"erator


W V

+escri"tion
4ogical AMD 4ogical T, 4ogical MT!

Matlab Logical &unction


and or xor an" all isempt" ise3ual ismember

+escri"tion
4ogical AMD 4ogical T, 4ogical exclusi%e T, 4ogical !,LE if an" element is !,LE 4ogical !,LE if all elements !,LE 4ogical !,LE if matrix is empt" 4ogical !,LE if matrices are identical

www*fundipboo$*com Matlab Primer 65

+F

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

!r" some of these basic examples Matlab Commands


<< A?@+ 5 ;EA #?@F 5 BEA C?@+ ; 5EA << and-AU#)CU#. << xor-AU# ) #UC. << isempt"-find-A<B.. << an"-#<A.

What s !a""ening
>Assign matrices >4ogical AMD between logical arra"s AU# and CU#7 ans?@F F +E >Exclusi%e T, between arra"s AU# and CU#7 >ans?@+ + +E >A has no elements < B* Find function returns the empt" >arra"* isempt" tests for this* ans?+ >if an" elements of #<A returns logical true* ans?+

Mote from the last example how the output from the function find can directl" form the input to the function isempty* !his is possible in this specific case because the output from find is a single arra"/matrix and the re3uired input to isempty is also a single arra"/matrix* !he reader should consult the online help facilit" for further details of the logical functions described abo%e * Matlab -lo, Control Matlab pro%ides flow control statements in a wa" %er" similar to most other programming languages* Conditional statements where certain operations are carried out onl" if certain conditions are satisfied can be constructed in two basic wa"s & if and switch statements* I& statements Matlab supports these %ariants of the if construct & if J-statement.*** end if J-statement.*** else J-statement.*** end if J-statement.*** elseif J-statement.*** else J-statement.*** end A single example of each %ariant is sufficient to illustrate its use 7& Matlab Commands
<< d ? bQ5 & BSaScA << if dUF << disp-=warning7 discriminant negati%e) roots imag=.A << end

What s !a""ening
>Define d >#egin conditional if >Statement >End if

www*fundipboo$*com Matlab Primer 65

++

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

Matlab Commands
<< d ? bQ5 & BSaScA << if dUF << disp-=warning7 discriminant negati%e) roots imag=.A << else << disp-=TX7 roots are real) but ma" be repeated=.A << end

What s !a""ening
>#egin conditional if >single alternati%e -else. clause >End if

Matlab Commands
<<d ? bQ5 & BSaScA <<if dUF <<disp-=warning7 discriminant negati%e) roots imag=.A <<elseif d??F <<disp-=discriminant is 2ero) roots are repeated=.A <<else <<disp-=TX7 roots are real and distinct=.A <<end

What s !a""ening
>#egin conditional if >+st alternati%e -elseif. clause >4ast alternati%e -else. clause >End if

Mote no semicolon is needed to suppress output at the end of lines containing if" else" elseif or end. !he operator ?? -is e3ual to. is used for logical comparison* It is 3uite distinct from the single ? sign which assigns a value to a %ariable* Indentation of if bloc$s is not re3uired) but considered good st"le* Primer Exercise 5*D 8rite a Matlab function which ta$es a single 5&D matrix input argument -an image. and Scales the matrix so that the maximum pixel %alue is ? +* Calculates the mean pixel %alue of the scaled matrix Conditionall" prints the following strings to the monitor & 'Image is dar$( if the mean xUF*C 'Image is normal( if the mean x?F*C 'Image is bright( if the mean x<F*C !est "our function on one or two of the Matlab images to ma$e sure it operates properl"*

www*fundipboo$*com Matlab Primer 65

+5

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

.,itch-case constructs A switch&case construct is similar in basic purpose to an if construct* If a se3uence of commands must be conditionall" e%aluated based on the e3ualit" of a single common argument) a switch&case construct is often easier* 1ere is an example 7 Matlab Commands
info?imfinfo-=cameraman*tif=.A switch info*Format case Y=tif=Z disp-=[ueried file is !IF format=. case Y=0pg=)=0peg=Z disp-=[ueried file is \PG format=. end

What s !a""ening
>assign image information to structure info >switch construct depends on )ormat field >execute statement if Format ??:tif:

>execute statement if Format ??:0pg:

Comments !he Matlab function imfinfo attempts to infer the contents of the image cameraman.tif* It assigns the results to a structure called info -a structure is essentiall" a collection of numeric and string %ariables each of which can be accessed using the same basic name but a different specific field.* !"pe help struct at the Matlab prompt for further information Tne of the fields in this particular structure is the )ormat field* !he switch statement effecti%el" registers/records the string contained in the format field* !his is compared for equality with each of the strings contained within the curl" braces Y Z that are part of the case clauses* If e3ualit" occurs) the commands following the case clause are executed*

In the example abo%e) Matlab responds with &ueried file is '() format !hus the generic form for a switch statement is switch the switch expression case a case expression corresponding statements. case another case expression otherwise corresponding statements. end !hus the corresponding group of legal Matlab statements will be executed if the case expression matches the switch expression*

www*fundipboo$*com Matlab Primer 65

+;

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

Loo" Constructs for and while for loops allow a set of statements to be executed a fixed number of times* !he s"ntax is 7 for x = array
statements..

end !he for loop basicall" wor$s b" assigning the loop %ariable x to the next column of the %ector array at each iteration* Consider the following simple for loop to sum all the integers from + to +F 7 Matlab Commands
sum?FA for i ? +7+F sum?sum R iA end cumsum-+7+F.

What s !a""ening
>Initialise sum >Create +F element arra" i?@+ 5 ;J+FE* #egin loop >Calculate cumulati%e sum >End 4oop >M#* !his is the eas" wa" to do this in MatlabJ

!hus) in this for loop the %ariable i ta$es on the next %alue in the arra" -+)5)**+F. on each successi%e iteration* !he next example shows a slightl" more ad%anced piece of code in%ol%ing some new Matlab functions & we include it now to show that the basic construction of the for loop is exactl" the same 7 Matlab Commands
A?imread-=cameraman*tif=.A #?imread-=moon*tif=.A #?imresi2e-#)si2e-A.)=bilinear=.A for i?+7si2e-A)+. r%als?rand-si2e-A)+.)+.A indices?find-r%als<F*C.A A-i)indices.?#-i)indices.A end imshow-A.A

What s !a""ening
>,ead in two images assign to arra"s a" >,esi2e # to match dimensions of A >#egin looping through columns of A >,andoml" sample for pixel locations >in columns >At selected pixel locations) cop" # >%alues into A >End loop

>Displa" modified image

!he following example creates a %ector with the first +D terms of the Fibonacci series xn+1 = xn + xn1 using a for loop* Another for loop is then used to c"clicall" permute the terms to form the rows of the image 7

www*fundipboo$*com Matlab Primer 65

+B

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

Matlab Commands
%ec?ones-+)+D.A for i?57+C %ec-iR+.?%ec-i.R%ec-i&+. end A-+)7.?%ecA for i?+7+C A-iR+)7.?@%ec-+K&i7+D. %ec-+7+D&i.E End imagesc-log-A..

What s !a""ening
>+D element %ector all ?+ >#egin 4oop >#uild Fibonacci terms >End 4oop >First column of A Fibonacci series >#egin 4oop >C"cle elements for each new col >End 4oop >Displa" on log scale

,hile loo"s !he s"ntax of the while loop is %er" simple & while expression statements end In the while loop) expression is a logical expression and the statements following are repeatedl" executed until the expression in the while statement becomes logicall" false* 1ere are a couple of simple examples 7& Matlab Commands
<<i ? 5A <<while iUH <<i ? i R 5 <<end

What s !a""ening
>Initialise i?5 >logicall" true if iUH >increment I b" 5 each iteration >End loop

!his example successi%el" generates sets of B random numbers in the inter%al F&+* !he loop stops when we obtain a set of B numbers all of which are less than F*5C* Matlab Commands
A?ones-B)+.A $?FA while an"-A. A?rand-B)+.<F*5C $?$R+A end $

What s !a""ening
>Initialise A and counter $ >False if A44 elements of A ?F >A is B element logical arra" >Element ? + if rand < F*C >Increment counter >End loop >Show final number of trials

www*fundipboo$*com Matlab Primer 65

+C

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

More on Arrays and Inde*ing 8e end this primer with an o%er%iew of some of the more ad%anced aspects of indexing into arra"s* Indexing into an arra" is a means of selecting a subset of elements from the arra"* Indexing is also closel" related to another term we mentioned in passing earl" on7 vectori%ation* Nectori2ation means using Matlab language constructs to eliminate program loops) usuall" resulting in programs that run faster and are more readable* !r" out the following examples which illustrate a number of powerful indexing techni3ues* Inde*ing ;ectors 4et=s start with the simple case of a %ector and a single subscript* !he %ector is7&
<< % ? @+D C I B 5 ++ K +BEA << %-;.

> !he subscript can be a single %alue >'Extract the > third element( ans ? I

Tr the subscript can itself be another %ector 7


<< %-@+ C DE.
> Extract the first) fifth) and sixth elements > ans ? +D 5 ++

Matlab=s colon notation - : . pro%ides an eas" wa" to extract a range of elements from %7&
<< %-;7K.
> Extract elements ; to K inclusi%e* > ans ? I B 5 ++ K

Pou can swap the two hal%es of % to ma$e a new %ector 7


<< %5 ? %-@C7H +7BE. > Extract and swap the hal%es of % > %5 ? 5 ++ K +B +D C I B

!he special end operator is an eas" short&hand wa" to refer to the last element of % &
<< %-end.
> Extract the last element > ans ? +B

!he end operator can be used in a range


%-C7end.
> Extract elements C to last inclusi%e > ans ? 5 ++ K +B

Pou can e%en do arithmetic using end


%-57end&+. > Extract second to penultimate element > ans ? C I B 5 ++ K

www*fundipboo$*com Matlab Primer 65

+D

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

!he colon operator is %er" powerful and can be used to achie%e a %ariet" of effects 7
<< %-+757end.
>extract e%er" $&th element $?5 here > ans ? +D I 5 K

%-end7&+7+.

> ,e%erse the order of elements >ans ? +B K ++ 5 B I C +D

#" using an indexing expression on the left side of the e3ual sign) "ou can replace certain elements of the %ector*7&
<< %-@5 ; BE. ? @+F +C 5FE
> ,eplace selected elements of % >% ? +D +F +C 5F 5 ++

K +B

Lsuall" the number of elements on the right must be the same as the number of elements referred to b" the indexing expression on the left* Pou can alwa"s) howe%er) use a scalar on the right side*
<<%-@5 ;E. ? ;F
> ,eplace second and third elements b" ;F >% ? +D ;F ;F 5F 5 ++ K + B

!his form of indexed assignment is called scalar expansion* Inde*ing Arrays ,ith T,o .ubscri"ts Mow consider indexing into an arra"* 8e=ll use a magic s3uare for our experiments*
<<A ? magic-B. >Create a B x >B magic s3uare using in&built >function magic

Most often) indexing in arra"s is done using two subscripts & one for the rows and one for the columns* !he simplest form 0ust pic$s out a single element 7
<<A-5)B. > Extract the element in row 5) column B > ans ? H

More generall") one or both of the row and column subscripts can be %ectors*
<<A-57B)+75. >Extract rows 5 to B) columns + to 5

www*fundipboo$*com Matlab Primer 65

+K

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

A single semi&colon - : . in a subscript position is short&hand notation for *+,end] and is often used to select entire rows or columns*
<< A-;)7. > Extract third row > ans ? I K D +5 > Extract last column > ans ? +; H +5 +

<< A-7)end.

!he diagram below illustrates a tric$ier use of two-subscript indexing* !he expression A-@5 ; BE) @+ 5 BE. does MT! extract elements A-5)+.) A-;)5. and A-B)B. as one might) at first glance thin$) but rather extracts the elements shown on the right 7

.electing scattered elements &rom an array Suppose "ou do want to extract the -5)+.) -;)5.) and -B)B. elements from A ^ As we ha%e 0ust shown) the expression A-@5 ; BE) @+ 5 BE. doesn:t do this* !here is often confusion o%er how to select scattered elements from an arra"* !o do this re3uires the use of linear indexing and that brings us to our next topic* Linear Inde*ing 8e begin with a 3uestion* 8hat exactl" does this expression A-+B. do ^ 8hen "ou index into the arra" A using onl" one subscript) MATLAB treats A as if its elements were strung out in a long column vector by going down the columns consecutively" as in 7 +D C I J**
www*fundipboo$*com Matlab Primer 65

+H

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

H +5 + !he expression A-+B. simpl" extracts the +Bth element of the implicit column %ector* 1ere are the elements of the matrix A along with their linear indices in the top left corner of each s3uare7&

!he linear index of each element is shown in the upper left* From the diagram "ou can see that A-+B. is the same as A-5)B. i*e* -inear index $ (column number . +) x (number of rows in array) / row number !he single subscript can be a %ector containing more than one linear index) as in7
<<A-@D +5 +CE. >Extract 'linear( elements D)+5)+C >ans ? ++ +C +5

4et:s consider again the problem of extracting 0ust the -5)+.) -;)5.) and -B)B. elements of A* Pou can use linear indexing to extract those elements7
<<A-@5 K +DE. >ans ? C K +

www*fundipboo$*com Matlab Primer 65

+I

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

It:s eas" to see the corresponding linear indices for this example) but how do we compute linear indices in general ^ pro%ides a function called sub ind that pro%ides the appropriate linear indices corresponding to the gi%en row and column subscripts
<<idx ? sub5ind-si2e-A.) @5 ; BE) @+ 5 BE. <<A-idx. > idx ? 5 K +D >displa" %alues referenced b" these indices >ans ? C K +

!he in&built Matlab function ind sub does precisel" the re%erse) pro%iding the row and column indices gi%en the linear index and the si2e of the arra"* The find &unction !he find function was introduced earlier but is %er" useful and so deser%es special mention* It can be used to extract the indices of all those elements of an arra" satisf"ing a stated condition* For example) consider first creating a %ector 7&
<< clearA A?+7+FA i?find-A<C. > i ? @D K H I +FE

It can also be used on 5&D arra"s to return the row-column indices 7


<< clearA A?@+ 5 ;A F + 5A &+ + +EA @i)0E?find-AU?F. > i?@5 ;E 0?@+ +E

Tr it can extract the linear indices of the 5&D arra" 7&


<< i?find-AU?F. > i?@5 ;E

In the following example we ta$e two images A and # -of e3ual si2e. and compare them on a pixel b" pixel basis to see whether image A has the greater intensit"* If so) we cop" the %alue in A to #*
A?imread-=cameraman*tif=.A #?imread-=rice*png=.A I?find-A<#.A #-I.?A-I.A imshow-#.A >,ead in images >get linear indices for A<#* Cop" o%er original*

Logical Inde*ing Another indexing %ariation) logical indexing) has pro%ed to be both useful and expressi%e* In logical indexing) "ou use a single) logical arra" for the matrix subscript* Matlab extracts the matrix elements corresponding to the non2ero %alues of the logical arra"* !he output is alwa"s in the form of a column %ector* For example) A-A < +5. extracts all the elements of A that are greater than +5*

www*fundipboo$*com Matlab Primer 65

5F

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

<<A-A < +5.

>ans ? +D +B +C +; -as column %ector.

Man" Matlab functions that start with ]is] -isnan! isreal! isempty..) return logical arra"s and are %er" useful for logical indexing* For example) "ou could replace all the MaMsB in an arra" with another %alue b" using a combination of isnan) logical indexing) and scalar expansion* !o replace all MaM elements of the matrix # with 2ero) use7&
<< #?F*/linspace-C)F)D. << #-isnan-#.. ? F

Tr "ou could replace all the spaces in a string matrix str with underscores7&
<<str?=A stitch in time= <<str-isspace-str.. ? =_=

4ogical indexing is closel" related to the find function* !he expression A-A < C. is e3ui%alent to A-find-A < C..* 8hich form "ou use is mostl" a matter of st"le and "our sense of the readabilit" of "our code) but it also depends on whether or not "ou need the actual index %alues for something else in the computation* For example) suppose "ou want to temporaril" replace MaM %alues with 2eros) perform some computation) and then put the MaM %alues bac$ in their original locations* In this example) the computation is two&dimensional filtering using filter * Pou do it li$e this 7&
<<nan_locations ? find-isnan-A..A <<A-nan_locations. ? FA <<A ? filter5-ones-;);.) A.A <<A-nan_locations. ? MaMA

!he Matlab indexing %ariants illustrated abo%e gi%e "ou a feel for wa"s we can create compact and efficient code* Pou will certainl" not need them all right awa" but learning to include these techni3ues and related functions in "our Matlab programs helps to write and create efficient) readable) %ectori2ed code*

MaM is the I*E*E*E* representation for Mot&a&number* A MaM results from mathematicall" undefined operations such as F/F or inf/inf* An" arithmetic operation in%ol%ing a MaM and a legal mathematical entit" results in a MaM* !he" ca) howe%er) sometimes be useful to identif" and/or label locations at which data is missing* www*fundipboo$*com Matlab Primer 65

5+

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

-urther !el" in Learning Matlab In this brief introduction) we ha%e tried to gi%e an indication and some simple examples of some of Matlab:s $e" programming constructs hopefull" enough to get "ou off the ground* !here are now man" good core Matlab boo$s -non image processing specific. and a significant amount of web&based material specificall" aimed at helping users de%elop their $nowledge of the Matlab language and we refer the reader to a selected sub&set of this material on the boo$ website -with these primers.* 8e must also ma$e mention of the excellent on&line help resources and comprehensi%e documentation a%ailable to Matlab users* In the authors= experience it is clearl" written) well organi2ed and both 3uic$ and eas" to use it almost -but we hope not 3uite. ma$es the these two supporting Matlab primers for this boo$ superfluous* 8e hasten to recommend this material to the reader* As a rather $een DIPer) I cannot help but compare programming in Matlab with underta$ing some tas$ of ph"sical construction such as building a house* It is a simple but accurate analog"* #uilding a basic house can actuall" be done with a bare minimum of essential tools but it tends to be long&winded and hard wor$* I ha%e often had the experience of beginning or e%en completing a particular tas$ in building or carpentr" onl" then to disco%er that there is actuall" a much easier wa" to do it) gi%en the right tool and approach* If onl" one had $nown beforehand) how much time and effort could ha%e been sa%ed ` I loo$ upon the basic $nowledge of %ariable t"pes) arra"s and indexing and $e" programming constructs such as for and while loops) conditional if clauses etc that we ha%e discussed as the essential tools* 1owe%er) man" of Matlab:s in&built functions are %er" much a$in to specialist tools the" ma$e eas" that which is much harder if "ou tr" to do it all "ourself* !hese da"s) when I am in a hardware store) I often 0ust browse the tool section to see what:s a%ailable 0ust in case I should e%er encounter a future 0ob which could ma$e good use of some specialist tool I encounter* In this spirit) we finish this %er" brief introduction b" pro%iding the reader with a selected but large list -b" categor". of Matlab functions together with a brief description of their purpose* Please browse at "our leisure* !he completel" comprehensi%e list is) of course) a%ailable in Matlab:s documentation and the help facilit"* !his is a boo$ about image processing so) finall") note that the specialist functions associated with the 0atlab image processing toolbox are not yet gi%en here* !he use of man" of these specialist image processing functions is discussed and demonstrated in the remaining chapters of this boo$* A comprehensi%e list of functions a%ailable is a%ailable in the 0atlab image processing toolbox documentation.

www*fundipboo$*com Matlab Primer 65

55

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

<L<M<)TA4= MAT4IC<. Matlab &unction zeros ones eye repmat rand randn linspace logspace fre"space meshgrid accumarray BA.IC A44A= I)-54MATI5) size length ndims numel disp isempty ise"ual ise"ualwithe"ualnans M3LTI-+IM<).I5)AL A44A= -3)CTI5). ndgrid permute ipermute shiftdim circshift s"ueeze Generate arra"s for M&D functions and interpolation Permute arra" dimensions In%erse permute arra" dimensions Shift dimensions Shift arra" circularl" ,emo%e singleton dimensions Si2e of arra" 4ength of %ector Mumber of dimensions Mumber of elements Displa" matrix or text !rue for empt" arra" !rue if arra"s numericall" e3ual !rue if arra"s numericall" e3ual +escri"tion aeros arra" Tnes arra" Identit" matrix ,eplicate and tile arra" Lniforml" distributed random numbers Mormall" distributed random numbers 4inearl" spaced %ector 4og spaced %ector Fre3uenc" spacing for fre3uenc" response O and P arra"s for ;&D plots Construct an arra" with accumulation

www*fundipboo$*com Matlab Primer 65

5;

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

MAT4I> MA)IP3LATI5) cat reshape diag bl#diag tril triu fliplr flipud flipdim rot$% & find end sub ind ind sub A44A= 3TILIT= -3)CTI5). compan gallery hadamard han#el hilb in'hilb magic pascal rosser toeplitz 'ander wil#inson Companion matrix 1igham test matrices* 1adamard matrix* 1an$el matrix* 1ilbert matrix* In%erse 1ilbert matrix* Magic s3uare* Pascal matrix* eigen%alue test matrix* !oeplit2 matrix* Nandermonde matrix* 8il$inson=s eigen%alue test matrix 4ast index 4inear index from multiple subscripts Concatenate arra"s Change si2e Diagonal matrices and diagonals of matrix #loc$ diagonal concatenation Extract lower triangular part Extract upper triangular part Flip matrix in left/right direction Flip matrix in up/down direction Flip matrix along specified dimension ,otate matrix IF degrees ,egularl" spaced %ector and index into matrix Find indices of non2ero elements

www*fundipboo$*com Matlab Primer 65

5B

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

.P<CIAL ;A4IABL<. A)+ C5).TA)T. ans e"s realma* realmi "i i: ? in& )a) I)T<4P5LATI5) A)+ @4I++I)@ pchip interp( interp(" interpft interp interp) interpn griddata griddata) griddatan .PLI)< I)T<4P5LATI5) spline pp'al Cubic spline interpolation* E%aluate piecewise pol"nomial* +&D interpolation -table loo$up.* [uic$ +&D linear interpolation +&D interpolation using FF! method 5&D interpolation -table loo$up.* ;&D interpolation -table loo$up.* M&D interpolation -table loo$up.* Data gridding and surface fitting* Data gridding and h"per&surface fitting for ;&dimensional data* Data gridding and h"per&surface fitting -dimension <? 5.* +&D interpolation -table loo$up.* Most recent answer Floating point relati%e accurac" 4argest positi%e floating point number Smallest positi%e floating point number ;*+B+CI5DC;CHIK Imaginar" unit Infinit" Mot&a&Mumber

www*fundipboo$*com Matlab Primer 65

5C

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

@<5M<T4IC A)AL=.I. delaunay delaunay) delaunayn dsearch dsearchn tsearch tsearchn con'hull con'hulln 'oronoi 'oronoin inpolygon rectint polyarea P5L=)5MIAL. roots poly poly'al poly'alm residue polyfit polyder polyint con' decon' Find pol"nomial roots* Con%ert roots to pol"nomial* E%aluate pol"nomial* E%aluate pol"nomial with matrix argument* Partial&fraction expansion -residues.* Fit pol"nomial to data* Differentiate pol"nomial* Integrate pol"nomial anal"ticall"* Multipl" pol"nomials* Di%ide pol"nomials* Delauna" triangulation* ;_D Delauna" tessellation* M_D Delauna" tessellation* Search Delauna" triangulation for nearest point* Search M_D Delauna" tessellation for nearest point* Closest triangle search* M_D closest triangle search* Con%ex hull* M_D con%ex hull* Noronoi diagram* M_D Noronoi diagram* !rue for points inside pol"gonal region* ,ectangle intersection area* Area of pol"gon*

www*fundipboo$*com Matlab Primer 65

5D

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on

MAT4I> A)AL=.I. norm normest ran# det trace null orth rref subspace LI)<A4 <A3ATI5). * and + linsol'e in' rcond cond condest normest( chol cholinc lu luinc "r ls"nonneg pin' lsco' 4inear e3uation solutionA use ]help slash]* 4inear e3uation solution with extra control* Matrix in%erse* 4APACX reciprocal condition estimator Condition in%ersion* number with respect to Matrix or %ector norm* Estimate the matrix 5 norm* Matrix ran$* Determinant* Sum of diagonal elements* Mull space* Trthogonali2ation* ,educed row echelon form* Angle between two subspaces*

+_norm condition number estimate* +_norm estimate* Choles$" factori2ation* Incomplete Choles$" factori2ation* 4L factori2ation* Incomplete 4L factori2ation* Trthogonal 4inear least s3uares with nonnegati%it" constraints* Pseudoin%erse* 4east s3uares with $nown co%ariance*

www*fundipboo$*com Matlab Primer 65

5K

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !ob" #rec$on <I@<);AL3<. A)+ .I)@3LA4 ;AL3<.

eig s'd gs'd eigs s'ds poly polyeig condeig hess "z ord"z schur ordschur

Eigen%alues and eigen%ectors* Singular %alue decomposition* Generali2ed singular %alue decomposition* A few eigen%alues* A few singular %ales* Characteristic pol"nomial* Pol"nomial eigen%alue problem* Condition number eigen%alues* 1essenberg form* [a factori2ation eigen%alues* ,eordering of factori2ation* ,eordering of decomposition* for generali2ed in [a with respect to

eigen%alues

Schur decomposition* eigen%alues in Schur

-ACT54IBATI5) 3TILITI<. e,pm logm s"rtm funm "rdelete "rinsert rsf csf cdf rdf balance planerot cholupdate "rupdate Matrix exponential* Matrix logarithm* Matrix s3uare root* E%aluate general matrix function* Delete a column or row from [, factori2ation* Insert a column factori2ation* or row into [,

,eal bloc$ diagonal form to complex diagonal form* Complex diagonal form to real bloc$ diagonal form* Diagonal scaling to impro%e eigen%alue accurac"*

Gi%ens plane rotation* ran$ + update to Choles$" factori2ation* ran$ + update to [, factori2ation*

www*fundipboo$*com Matlab Primer 65

5H

Potrebbero piacerti anche