56
การประมวลผลภาพดิจิตอลด้วย Matlab เบื องต้น

Intro 2 Digital Image

Embed Size (px)

DESCRIPTION

goog

Citation preview

  • Matlab

  • f(x,y) x y (SpatialCoordinate)

    (x,y) (Intensity)(Pixel)

    GrayLevel (MonochromeImages)

  • MonochromeandColorImages

    GrayScales GrayLevels

    0

    50

    100

    150

    200

    250

    RedGreenBlue

  • () ( Matlab)

  • imread

    imread(filename);

    I

    I=imread(filename);

    size,whos

  • matlab

    imread helpimread

  • I imshow

    imshow(I,256); imshow(I);

    [lowhigh]

    imshow(I,[100200]); 100 200

    pixval,impixelinfo

  • imwrite Syntax

    imwrite(A,filename,fmt)imwrite(X,map,filename,fmt)imwrite(...,filename)imwrite(...,Param1,Val1,Param2,Val2...)

    A myFile tif imwrite(A,myFile,tif); imwrite(A,myFile.tif); path myFile.tif

    imwrite JPEG

    imwrite(A,myFile.jpg,quality,q) q (quality) q

    0-100

  • jpeg imfinfo

    S=imfinfo(myFile10.jpg); myFile10.jpg S

    (Height Width)

    S.Height,S.Width

    ByteNum =S.Height*S.Width*S.BitDepth/8;CompressRation =ByteNum/S.FileSize

  • TIF imwrite TIF

    imwrite(A,myFile.tif,compression,parameter,resolution,[colres rowres])

    parameter={none,packbits,ccitt};,

    [colres rowres] [7272] 72 (dpi:dotperinch)

    xray resolution 200 dpi 450450 pixels [450 450]/200=[2.25 2.25] tif cb.tif [1.5 1.5] [colres rowres] = 200*[1.5 1.5]

    imwrite(A, cb.tif, compression, non, resolution [300 300])

  • Matlab Class

  • DataClass

    Matlab double unit8

  • IPT Intensityimages Binaryimages Indeximages RGBimages

    Intensityimageisadatamatrixwhosevalueshavebeenscaledtorepresent intensities.

    Pixelvaluesareofclassuint8,orclassuint16,theyhaveintegervaluesintherange[0,255]and[0,65535],respectively.

    Iftheimageisofclassdouble,thevaluesarefloatingpointnumbers,thepixelsarescaledintherange[0,1].

    } 6

  • BinaryImages AbinaryimageisalogicalarrayofOs and1s. ArrayofOs and1swhosevaluesareofdataclass,say,uint8,isnot

    consideredabinaryimageinMATLAB. Anumericarrayisconvertedtobinaryusingfunctionlogical.Thus,ifAisa

    numericarrayconsistingofOs and1s,wecreatealogicalarrayBusingthestatement

    B=logical(A); IfAcontainselementsotherthanOs and1s,useofthelogicalfunction

    convertsallnonzeroquantitiestologicalIsandallentrieswithvaluetologicalOs.Usingrelationalandlogicaloperators(seeSection2.10.2)alsocreateslogicalarrays.

    Totestifanarrayislogicalweusetheislogicalfunction:islogical(C)

    IfCisalogicalarray,thisfunctionreturnsa1.OtherwiseitreturnsaO. Logicalarrayscanbeconvertedtonumericarraysusingthedataclass

    conversionfunctions.

  • ConvertingbetweenDataClassesandImageTypes

    ThegeneralsyntaxisB=data_class_name(A);

    Wheredata_class_name isoneoftheimagedataclass Forexample,IfAisanarrayofclassuint8.Adoubleprecisionarray,B,is

    generatedbythecommandB=double(A). ThisconversionisusedroutinelythroughoutthebookbecauseMATLAB

    expectsoperandsinnumericalcomputationstobedoubleprecision,floatingpointnumbers.

    IfCisanarrayofclassdoubleinwhichallvaluesareintherange[0,255](butpossiblycontainingfractionalvalues),itcanbeconvertedtoanuint8arraywiththecommandD=uint8(C).

    Ifanarrayofclassdouble hasanyvaluesoutsidetherange[0,255]anditisconvertedtoclassuint8 inthemannerjustdescribed,MATLABconvertsto0allvaluesthatarelessthan0,andconvertsto255allvaluesthataregreaterthan255.

    Numbersinbetweenareconvertedtointegersbydiscardingtheirfractionalparts.Thus,properscalingofadoublearraysothatitselementsareintherange[0,255]isnecessarybeforeconvertingittouint8.

  • ConvertingbetweenImageClassesandTypes

    IPTprovidesspecificfunctionsthatperformthescalingnecessarytoconvertbetweenimageclassesandtypes.

    Functionim2uint8 detectsthedataclassoftheinputandperformsallthenecessaryscalingforthetoolboxtorecognizethedataasvalidimagedata.

    Forexample,considerthefollowing2x2imagefofclassdouble,whichcouldbetheresultofanintermediatecomputation:

    f=[0.50.5;0.751.5]; Performingtheconversion

    g=im2uint8(f)

    im2uint8 setsto0allvaluesintheinputthatarelessthan0,setsto255allvaluesintheinputthataregreaterthan1,andmultipliesallothervaluesby255.

    Roundingtheresultsofthemultiplicationtothenearestintegercompletestheconversion.

    Notethattheroundingbehaviorofim2uint8 isdifferentfromthedataclassconversionfunctionuint8discussedintheprevioussection,whichsimplydiscardsfractionalparts.

    g=0128191255

  • ConvertingbetweenImageClassesandTypes

    Convertinganarbitraryarrayofclassdouble toanarrayofclassdoublescaledtotherange[0,1]canbeaccomplishedbyusingfunctionmat2graywhosebasicsyntaxis

    g=mat2gray(f,[Amin,Amax]) ThespecifiedparametersAmin andAmax aresuchthatvalueslessthanAmin infbecome0ing,andvaluesgreaterthanAmax infcorrespondto1ing.

    Ex:x=mat2gray(f)g=im2uint8(x)

    X=00.5000

    0.62501.0000

    x=(f+0.5)/(1.5+0.5)

    g=0 128

    159 255

  • Functionim2double Iftheinputisofclassuint8,uint16,orlogical, functionim2double

    convertsittoclassdouble withvaluesintherange[0,1]. Iftheinputisalreadyofclassdouble,im2double returnsanarray

    thatisequaltotheinput. Forexample,ifanarrayofclassdouble resultsfromcomputations

    thatyieldvaluesoutsidetherange[0,1],inputtingthisarrayintoim2double willhavenoeffect.

    Asmentionedintheprecedingslide,adouble arrayhavingarbitraryvaluescanbeconvertedtoadouble arraywithvaluesintherange[0,1]byusingfunctionmat2gray.

    Ex:h=uint8([2550;128200]);

    Performingtheconversiong=im2double(h); g =double(h)/255;

    g=0.09800.19610.50200.7843

  • Functionim2bwg=im2bw(f,T)g f thresholdT

    g=im2bw(f),IPT T=0.5

    f uint8,f=f/255; f uint16,f=f/65535; f doubleim2bw T f g=f;

  • ArrayIndexing VectorIndexing:anarrayofdimension1Niscalledarowvector,

    whichisaccessedusingonedimensionalindexing. Thus,v(1)isthefirstelementofvectorv,v(2)itssecondelement,

    andsoforth. TheelementsofvectorsinMATLABareenclosedbysquarebrackets

    andareseparatedbyspacesorbycommas. Forexample,

    >>V=[13579]>>W=V%W V(V)

    >>A=V(1:3) A=[135]>>A=V(2:4) A=[357]>>A=V(3:end) A=[579]

  • ArrayIndexing>>W=V(:)% W=V W

    >>A=V(1:end)%A=V>>A=V(1:2:end)%A=[159] for(i=1;i>A=V(end:2,1)%A=[951] for(i=end;i>1;i=i2)>>A=V([145])%A=[179] [145]

  • MatrixIndexing

    M=[123;456;789]

    %M 3x3

    x=M(1,3)

    % x=3

    M=

    123456789

  • MatrixIndexing (Colon,:)

    c3=M(:,3)%c3= c3=M(1:3,3)

    c3

    r2=M(2,:)%r2=[456]

    S23=M(2:3,:)%% S23=M(2:3,1:3)

    S23=

    456789

  • MatrixIndexing B=M; B

    >>B=M;>>B(:,1)=0;

    end>>x=M(end,end:2:1)%x=[97]

    >>S=M([12],[23])

    B=023056089

    , ,

    , ,

    2 35 6

  • MatrixIndexing

    >>L=logical([101;100;001]);>>X=M(L)%X=[1439]

    >>A=M(:)%A=[1 47258369]

    >>X=sum(M(:))%X=45

    >>X=sum(sum(M))% sum(121518)=45

  • X peppers.png

    >>imshow(X)

    %>>imshow(X(end:1:1,:,:))

    % end:1:1

  • >>imshow(X(:,:,1))%

    imshow(I(100:end100,100:end100,:))% 100 end100%

    imshow(I(1:2:end,1:2:end,:))% 1,3,5,,end% 1,3,5,,end

  • 0 100 200 300 400 500 6000

    50

    100

    150

    200

    250

    300>>plot(X(200,:,1),'r')>>holdon>>plot(X(200,:,2),'g')>>plot(X(200,:,3),'b')

  • size matlab >>d=size(X);%d=[3845123]

    >>d=size(X,1);%d=384

    >>d=size(X,2);%d=512>>d=size(X,3);%d=3

  • zeros(M,N)generatesanMxN matrixofOs ofclassdouble>>x=zeros(2,2);%x=[00;00];

    ones(M,N)generatesanMxN matrixof1sofclassdouble.>>x=ones(2,2);%x=[11;11]

    true(M,N) generatesanMxN logicalmatrixof1s.>>x=true(2,2);%x=[11;11]

    false(M,N) generatesanMxNlogicalmatrixofOs.>>x=false(2,2);%x=[00;00]

  • magic(N) generatesanNxN "magicsquare."%MAGIC(N)isanNbyNmatrixconstructedfrom

    theintegers1throughN^2withequalrow,column,anddiagonalsums.

    ProducesvalidmagicsquaresforallN>0exceptN=2.Magicsquaresareusefularraysfortestingpurposesbecausetheyareeasytogenerateandtheirnumbersareintegers.

    >>x=magic(3)

    x=

  • rand(M,N) generatesanMxN matrixwhoseentriesareuniformlydistributedrandomnumbersintheinterval[0,1].

    randn (M,N) generatesanMxN matrixwhosenumbersarenormallydistributed(i.e.,Gaussian)randomnumberswithmean0andvariance1.

    >>x=rand(3)>>y=randn(3)

    x=

    0.81470.91340.27850.90580.63240.54690.12700.09750.9575

    y=

    2.76940.72540.20501.34990.06310.12413.03490.71471.4897

  • IntroductiontoMFunctionProgramming

    MATLABfunctionprogrammingisflexibleandparticularlyeasytolearn.

    MFiles

    Mfiles texteditor filename.m average.m andfilter.m

    Mfile Thefunctiondefinitionline TheH1line Helptext Thefunctionbody Comments

  • FunctionDefinition Thefunctiondefinitionlinehastheform

    function [outputs]=name(inputs)

    Forexample,afunctiontocomputethesumandproduct(twodifferentoutputs) oftwoimageswouldhavetheform

    function [s,p]=sumprod(f,g)

    wheref,andgaretheinputimages,sisthesumimage,andpistheproductimage.

    Thenamesumprod isarbitrarilydefined,butthewordfunctionalwaysappearsontheleft,intheformshown.

    Outputargumentsareenclosedbysquarebracketsandtheinputs areenclosedbyparentheses.Ifthefunctionhasasingleoutputargument,itisacceptabletolisttheargumentwithoutbrackets.Ifthefunctionhasnooutput,onlythewordfunctionisused,withoutbracketsorequalsign.

    Functionnamesmustbeginwithaletter,andtheremainingcharacterscanbeanycombinationofletters,numbers,andunderscores.Nospacesareallowed.MATLABdistinguishesfunctionnamesupto63characterslong.

    Functionscanbecalledatthecommandprompt;forexample,[s,p]=sumprod(f,g);

    ortheycanbeusedaselementsofotherfunctions(subfunctions).Asnotedinthepreviousparagraph,iftheoutputhasasingleargument,itisacceptabletowriteitwithoutthebrackets,asin

    y=sum(x);

  • H1line TheH1lineisthefirsttextline.Itisasinglecommentline

    thatfollowsthefunctiondefinitionline.TherecanbenoblanklinesorleadingspacesbetweentheH1lineandthefunctiondefinitionline.

    AnexampleofanH1lineis%SUMPRODComputesthesumandproductoftwoimages.

    H1lineisthefirsttextthatappearswhenaUsertypeshelpfunction_name

    attheMATLABprompt.Also,asmentionedinthatsection,typinglookforkeyworddisplaysalltheH1linescontainingthestringkeyword. Thislineprovidesimportantsummaryinformationabout

    theMfile,soitshouldbeasdescriptiveaspossible.

  • HelptextHelptext

    HelptextisatextblockthatfollowstheH1line,withoutanyblanklinesinbetweenthetwo.

    Helptextisusedtoprovidecommentsandonlinehelpforthefunction.

    Whenausertypeshelpfunction_name attheprompt,MATLABdisplaysallcommentlinesthatappearbetweenthefunctiondefinitionlineandthefirstnoncomment (executableorblank)line.

    ThehelpsystemignoresanycommentlinesthatappearaftertheHelptextblock.

  • functionbody&comment

    ThefunctionbodycontainsalltheMATLABcodethatperformscomputationsandassignsvaluestooutputarguments.

    Alllinesprecededbythesymbol"%"thatarenottheH1lineorHelptextareconsideredfunctioncommentlinesandarenotconsideredpartoftheHelptextblock.

    Itispermissibletoappendcommentstotheendofalineofcode.

  • EditMfiles Mfilescanbecreatedandeditedusinganytexteditorandsaved

    withtheextension.m inaspecifieddirectory,typicallyintheMATLABsearchpath.

    AnotherwaytocreateoreditanMfileistousetheeditfunctionattheprompt.Forexample,

    editsumprodopensforeditingthefilesumprod .m ifthefileexistsinadirectorythatisintheMATLABpathorinthecurrentdirectory.

    Ifthefilecannotbefound,MATLABgivestheusertheoptiontocreateit.

    MATLABeditorwindowhasnumerouspulldownmenusfortaskssuchassaving,viewing,anddebuggingfiles.Becauseitperformssomesimplechecksandusescolortodifferentiatebetweenvariouselementsofcode,thistexteditorisrecommendedasthetoolofchoiceforwritingandeditingMfunctions.

  • Operators

    MATLABoperatorsaregroupedintothreemaincategories: Arithmeticoperatorsthatperformnumericcomputations

    Relationaloperatorsthatcompareoperandsquantitatively

    LogicaloperatorsthatperformthefunctionsAND,OR,andNOT

  • ArithmeticOperators MATLABhastwodifferenttypesofarithmeticoperations.

    Matrixarithmeticoperationsaredefinedbytherulesoflinearalgebra. Arrayarithmeticoperationsarecarriedoutelementbyelementand

    canbeusedwithmultidimensionalarrays. Theperiod(dot)character(.)distinguishesarrayoperationsfrom

    matrixoperations. Forexample,A*Bindicatesmatrixmultiplicationinthetraditional

    sense, whereasA.*Bindicatesarraymultiplication,inthesensethatthe

    resultisanarray,thesamesizeasAandB,inwhicheachelementistheproductofcorrespondingelementsofAandB.Inotherwords,

    ifC=A.*B,thenC(I,J)=A(I,J)*B(I,J). Becausematrixandarrayoperationsarethesameforadditionand

    subtraction,thecharacterpairs.+and. arenotused.

  • Arrayandmatrix

    arithmeticoperators

  • ArithmeticoperatorsforIPT

  • Illustrationofarithmeticoperatorsandfunctionsmaxandmin.

    function[p,pmax,pmin,pn] =improd(f,g)%IMPRODComputestheproductoftwoimages.%[P,PMAX,PMIN,PN]=IMPROD(F,G)toutputstheelementby%elementproductoftwoinputimages,FandG,theproduct%maximumandminimumvalues,andanormalizedproductarraywith%valuesintherange[0,1].Theinputimagesmustbeofthesame%size.TheycanbeofclassUinta,unit16,ordouble.Theoutputs%areofclassdouble.fd =double(f);gd =double(g);p=fd.*gd;pmax =max(p(:));pmin =min(p(:));pn =mat2gray(p);

    Supposethatf=[12;34]andg=[12;21].Typingtheprecedingfunctionatthepromptresultsinthefollowingoutput:[p,pmax,pmin,pn]=improd(f,g)p=

    1464

    pmax =6

    pmin =1

    pn =00.6000

    1.00000.6000

  • Relationaloperators

    Syntax AB A=B A==B A~=B

    Relationaloperatorsperformelementbyelementcomparisonsbetweentwoarrays.

    Theyreturnalogicalarrayofthesamesize,withelementssettological1(true)wheretherelationistrue,andelementssettological0(false)whereitisnot.

    Theoperators,=useonlytherealpartoftheiroperandsforthecomparison.

    Theoperators==and~=testrealandimaginaryparts.

    >>X=5;>>X>=[123;456;7810]ans=

    111110000

  • LogicalOperator

    MATLABoffersthreetypesoflogicaloperatorsandfunctions: Elementwise operateoncorrespondingelementsoflogicalarrays.

    Bitwise operateoncorrespondingbitsofintegervaluesorarrays.

    Shortcircuit operateonscalar,logicalexpressions.

  • ElementwiseThefollowinglogicaloperatorsandfunctionsperformelementwiselogicaloperationsontheirinputstoproducealikesizedoutputarray. TheexamplesshowninthefollowingtableusevectorinputsAand

    B,where>>A=[01101];>>B=[11001];

    Operator Description Example

    & Returns1foreveryelementlocationthatistrue(nonzero)inbotharrays,and0forallotherelements.

    A&B=01001

    | Returns1foreveryelementlocationthatistrue(nonzero)ineitheroneortheother,orbotharrays,and0forallotherelements.

    A|B=11101

    ~ Complementseachelementoftheinputarray, ~A=10010

    xor Returns1foreveryelementlocationthatistrue(nonzero)inonlyonearray,and0forallotherelements.

    xor(A,B)=10100

  • BitWiseFunctions Thefollowingfunctionsperformbitwiselogicaloperationson

    nonnegativeintegerinputs.Inputsmaybescalarorinarrays.Ifinarrays,thesefunctionsproducealikesizedoutputarray.

    TheexamplesshowninthefollowingtableusescalarinputsAandB,where

    A=28;%binary11100 B=21;%binary10101

    Operator Description Example

    bitand ReturnsthebitwiseANDoftwononnegativeintegerarguments.

    bitand(A,B)=20(binary10100)

    bitor ReturnsthebitwiseORoftwononnegativeintegerarguments.

    bitor(A,B)=29(binary11101)

    Bitcmp Returnsthebitwisecomplementasannbitnumber,wherenisthesecondinputargumenttobitcmp.

    bitcmp(A,5)=3(binary00011)

    bitxor ReturnsthebitwiseexclusiveORoftwononnegativeintegerarguments.

    bitxor(A,B)=9(binary01001)

  • ShortCircuitOperatorsShortCircuitOperators ThefollowingoperatorsperformANDand ORoperationsonlogicalexpressionscontainingscalarvalues.Theyareshortcircuitoperatorsinthattheyevaluatetheirsecondoperandonlywhentheresultisnotfullydeterminedbythefirstoperand.

    Operator Description

    && Returnslogical1(true)ifbothinputsevaluatetotrue,andlogical0(false)iftheydonot.

    || Returnslogical1(true)ifeitherinput,orboth,evaluatetotrue,andlogical0(false)iftheydonot.

  • FlowControl

  • if,else,andelseif if ifexpression

    statementsend

    Theelse andelseif statementsfurtherconditionalize theifstatement. Thegeneralsyntaxisifexpression1 statements1elseif expression2 statements2else statements3end

    function av =average(A)%AVERAGEComputestheaveragevalueof%anarray.AV=AVERAGE(A)computesthe%averagevalueofinputarray,A,which%mustbea10or20array.Checkthe%validityoftheinput.(Keepinmindthat%a10arrayisaspecialcaseofa20%array.)if ndims (A)>2

    error('Thedimensionsoftheinputcannotexceed2.')end%Computetheaverageav =sum(A(:))/length(A(:));%ifAisanimage,numel (A)givesits%numberofpixels.Inthiscase,wecan%use%av =sum(A(:))/numel(A);

  • forfor Thesyntaxis

    for index=start:increment:endstatements

    end Itispossibletonesttwoormoreforloops,asfollows:

    for index1=start1:increment1:endstatements1for index2=start2:increment2:end

    statements2endadditionalloop1statements

    end Forexample,thefollowingloopexecutes11times:

    count=0;for k=0:0.1:1

    count=count+1;end

  • while Thesyntaxis

    while expressionstatements

    end Asinthecaseoffor,whileloopscanbe

    nested:while expression1

    statements1while expression2

    statements2endadditionalloop1statements

    end Forexample,thefollowingnested

    whileloopsterminate whenbothaandbhavebeenreducedto0:

    a=10;b=5;while a

    a=a1;while b

    b=b 1;end

    end

  • break,continue breakBreakterminatestheexecutionofafor orwhileloop.Whenabreak statementisencountered,executioncontinueswiththenextstatementoutsidetheloop.Innestedloops,breakexitsonlyfromtheinnermostloopthatcontainsit. continueThecontinuestatementpassescontroltothenextiterationofthefor orwhile loopinwhichitappears,skippinganyremainingstatementsinthebodyoftheloop.Innestedloops,continuepassescontroltothenextiterationoftheloopenclosingit.

  • switch

    ThisisthestatementofchoiceforcontrollingtheflowofanMfunctionbasedondifferenttypesofinputs.Thesyntaxisswitch switch_expression

    case case_expressionstatement(s)

    case {case_expression1,case_expression2,...}statement(s)

    otherwisestatement(s)

    end

  • CellArrays AcellarrayinMATLABisamultidimensionalarraywhoseelementsare

    copiesofotherarrays.Forexample,thecellarrayc={'gauss',[10;01],3}

    Toselectthecontentsofacellarrayweencloseanintegeraddressincurlybraces.Inthiscase,weobtainthefollowingresults:

    c{1}ans =

    gaussc{2}ans

    1001

    c{3}ans

    3

    Animportantpropertyofcellarraysisthattheycontaincopiesofthearguments,notpointerstothearguments.

    >>c={A,B};%AandBarematrices,andthesematriceschanged%sometimelaterinaprogram,thecontentsofcwouldnotchange.

  • StructuresStructures Structuresaresimilartocellarrays,inthesensethattheyallow

    groupingofacollectionofdissimilardataintoasinglevariable.

    However,unlikecellarrayswherecellsareaddressedbynumbers,theelementsofstructuresareaddressedbynamescalledfields.

    Dependingontheapplication,usingfieldsaddsclarityandreadabilitytoanMfunction.

    Forinstance,lettingSdenotethestructurevariableandusingthe(arbitrary)fieldnameschar_string,matrix,andscalar,thedataintheprecedingexamplecouldbeorganizedasastructurebyletting

    S.char_string ='gauss';

    S.matrix [10;01];

    S.scalar =3;