Tải bản đầy đủ - 0 (trang)
Chapter 4. Modifying Pictures Using Loops

Chapter 4. Modifying Pictures Using Loops

Tải bản đầy đủ - 0trang

Chapter4.ModifyingPicturesUsing

Loops

4.1 HOWPICTURESAREENCODED

4.2 MANIPULATINGPICTURES

4.3 CHANGINGCOLORVALUES

4.4 CONCEPTSSUMMARY



ChapterLearningObjectives

Themedialearninggoalsforthischapterare:

Tounderstandhowimagesaredigitizedbytakingadvantageoflimitsinhuman

vision.

Toidentifydifferentmodelsforcolor,includingRGB,themostcommononefor

computers.

Tomanipulatecolorvaluesinpictures,likeincreasingordecreasingredvalues.

Toconvertacolorpicturetograyscale,usingmorethanonemethod.

Toconvertacolorpicturetoitsnegativerepresentation.

Thecomputersciencegoalsforthischapterare:

Tointroducearrays.

Towriteobjectmethods.



Todoiterationwithwhileandforloops.

Tointroducecomments.

Tounderstandthescopeofavariablename.

Tointroducebreakingamethodintosmallermethods.







[Page76(continued)]



4.1.HowPicturesareEncoded

Pictures(images,graphics)areanimportantpartofanymedia

communication.Inthischapter,wediscusshowpicturesare

representedonacomputer(mostlyasbitmapimageseachdot

orpixelisrepresentedseparately)andhowtheycanbe

manipulated.

Picturesaretwo-dimensionalarraysofpixels(whichisshortfor

pictureelement).Inthissection,eachofthesetermswillbe

described.

Forourpurposes,apictureisanimagestoredinaJPEGfile.

JPEGisaninternationalstandardforhowtostoreimageswith

highqualitybutinlittlespace.JPEGisalossycompression

format.Thatmeansthatitiscompressed,madesmaller,but

notwith100%ofthequalityoftheoriginalformat.Typically,

though,whatgetsthrownawayisstuffthatyoudon'tseeor

don'tnoticeanyway.Formostpurposes,aJPEGimageworks

fine.



[Page77]

IfwewanttowriteprogramstomanipulateJPEGimageswe

needtounderstandhowtheyarestoredanddisplayed.Todo

thisweneedtounderstandarrays,matrices,pixels,andcolor.

Anarrayisasequenceofelements,eachwithanindexnumber

associatedwithit(Figure4.1).Thefirstelementinanarrayis

atindex0,thesecondatindex1,thethirdatindex2,andso

on.Thelastelementofthearraywillalwaysbeatthelengthof

thearrayminusone.Anarraywithfiveelementswillhaveits

lastelementatindex4.



Figure4.1.Adepictionofthefirstfiveelements

inanarray.



Itmaysoundstrangetosaythatthefirstelementofanarrayis

atindex0buttheindexisbasedonthedistancefromthe

beginningofthearraytotheelement.Sincethefirstitemofthe

arrayisatthebeginningofthearraythedistanceis0.Whyis

theindexbasedonthedistance?Arrayvaluesarestoredone

aftertheotherinmemory.Thismakesiteasytofindany

elementofthearraybymultiplyingthesizeofeachelementby

theindexandaddingittotheaddressofthebeginningofthe

array.Ifyouarelookingfortheelementatindex3inanarray

andthesizeofeachelementis4byteslongandthearray

startsatmemorylocation26thenthe3rdelementisat(3*4

+26=12+26=38).

Everytimeyoujoinaline(queue)ofpeople,youarein

somethinglikeanarray.Allyouusuallycareaboutishowfar

youarefromthefrontoftheline.Ifyouareatthefrontofthe

line,thenthatisindex0(youarenext).Ifyouarethesecond

oneinline,thenyouareatindex1(thereisonepersoninfront

ofyou).Ifyouarethethirdpersoninline,thenyouareat

index2(therearetwopeopleinfrontofyou).

Arraysareagreatwaytostorelotsofdataofthesametype.

Youwouldn'twanttocreateadifferentvariableforeverypixel

inapicturewhentherearehundredsofthousandsofpixelsina

picture.Insteadyouuseanarrayofpixels.Youstillneedaway

torefertoaparticularpixel,soweuseanindexforthat.You

canaccesselementsofanarrayinJavausingarrayName[index].



Forexample,toaccessthefirstelementinanarrayvariable

namedpixelsusepixels[0].Toaccessthesecondelementuse

pixels[1].Toaccessthethirdelementusepixels[2].Youcanget

thenumberofitemsinanarrayusingarrayName.length.So,to

accessthelastelementinthearrayusearrayName[arrayName.length

-1].

TodeclareanarrayinJavayouspecifythetypeandthenuse

openandclosesquarebracketsfollowedbyanameforthe

array.



[Page78]

>double[]grades;

>System.out.println(grades);

null



oryoucouldhavespecifiedthesquarebracketsafterthe

variablename:

>doublegrades[];

>System.out.println(grades);

null



Theabovecodedeclaresanarrayofdoubleswiththename

grades.Noticethoughthatthisjustdeclaredanobject

referenceandsetittonull.Itdidn'tcreatethearray.InJava

youcancreateanarrayandspecifythevaluesforitatthe

sametime:

>double[]gradeArray={80,90.5,88,92,94.5};

>System.out.println(gradeArray.length);

5



>System.out.println(gradeArray[0]);

80.0

>System.out.println(gradeArray[4]);

94.5



MakingitWorkTip:UsingDotNotationforPublic

Fields

NoticethattherearenoparenthesesfollowingarrayName.length.Thisis

becauselengthisnotamethodbutapublicfield(data).Publicfields

canbeaccessedusingdotnotationobjectName.fieldName.Methods

alwayshaveparenthesisafterthemethodnameevenifthereareno

inputparameters,suchasFileChooser.pickAFile().



Atwo-dimensionalarrayisamatrix.Amatrixisacollectionof

elementsarrangedinbothahorizontalandverticalsequence.

Forone-dimensionalarrays,youwouldtalkaboutanelementat

indexi,thatisarray[i].Fortwo-dimensionalarrays,youcantalk

aboutanelementatrowrandcolumnc,thatis,matrix[r][c].

Thisiscalledrow-majororder.

HaveyoueverplayedthegameBattleshipTM?Ifyouhave,then

youhadtospecifyboththerowandcolumnofyourguess(B3).ThismeansrowBandcolumn3(Figure4.2).Haveyouever

gonetoaplay?Usuallyyourtickethasarowandseatnumber.

Thesearebothexamplesofrow-majortwo-dimensionalarrays.



Figure4.2.Thetop-leftcornerofaBattleship

guessboardwithamissatB-3.

(Thisitemisdisplayedonpage79intheprintversion)



Anotherwaytospecifyalocationinatwo-dimensionalarrayis

column-majororderwhichspecifiesthecolumnfirstandthen

therow:matrix[c][r].Thisishowwenormallytalkabout

picturesbyusinganxforthehorizontallocationandayforthe

verticallocationsuchasmatrix[x][y].Picturedataisrepresented

asacolumn-majortwo-dimensionalarray.

Javaactuallycreatesmultidimensionalarraysasarraysof

arrays.Whenyouhaveatwo-dimensionalarray,thefirstindex

isthelocationintheouterarray,andthesecondisthelocation

intheinnerarray.Youcanthinkoftheouterarrayaseitherthe

rowsorthecolumns.SoJavaisn'trow-majororcolumn-major,

butyouwillcreateandworkwithyourarraysineitherrowmajororcolumn-majorfashion(Figure4.3).Justbesuretobe

consistent.



[Page79]

Figure4.3.Picturinga2Darrayasrow-majoror

column-major.



InFigure4.4,youseeanexamplematrix.Usingcolumn-major

orderforthecoordinates(0,0)(horizontal,vertical),you'llfind

thematrixelementwhosevalueis15.Theelementat(1,1)is

7,(2,1)is43,and(3,1)is23.Wewilloftenrefertothese

coordinatesas(x,y)(horizontal,vertical).



Figure4.4.Anexamplematrix(two-dimensional

array)ofnumbers.



What'sstoredateachelementinthepictureisapixel.The

word"pixel"isshortfor"pictureelement."It'sliterallyadot,

andtheoverallpictureismadeupoflotsofthesedots.Have

youevertakenamagnifyingglasstoviewpicturesina

newspaperormagazine,ortoatelevisionorevenyourown

computermonitor?Figure4.5wasgeneratedbycapturingasan



imagethetop-leftpartoftheDrJavawindowandthen

magnifyingit600%.It'smadeupofmany,manydots.When

youlookatthepictureinthemagazineoronthetelevision,it

doesn'tlooklikeit'sbrokenupintomillionsofdiscretespots,

butitis.



[Page80]

Figure4.5.Upper-leftcorneroftheDrJava

windowwithaportionmagnified600%.



[Viewfullsizeimage]



Youcangetasimilarviewofindividualpixelsusingthepicture

explorer,whichisdiscussedlaterinthischapter.Thepicture

explorerallowsyoutozoomapictureupto500%sothateach

individualpixelisvisible(Figure4.6).



Figure4.6.Imageshowninthepictureexplorer:

100%imageonleftand500%onright(close-up

ofthebranchoverthemountain).



[Viewfullsizeimage]



Ourhumansensorapparatuscan'tdistinguish(without

magnificationorotherspecialequipment)thesmallbitsinthe

whole.Humanshavelowvisualacuitywedon'tseeasmuch

detailas,say,aneagle.Weactuallyhavemorethanonekindof

visionsysteminuseinourbrainandoureyes.Oursystemfor

processingcolorisdifferentthanoursystemforprocessing

black-and-white(orluminance).Weactuallypickupluminance

detailbetterwiththesidesofoureyesthanthecenterofour

eyes.That'sanevolutionaryadvantagebecauseitallowsyouto

pickoutthesabertoothtigersneakinguponyoufromtheside.



[Page81]

Thelackofresolutioninhumanvisioniswhatmakesitpossible

todigitizepictures.Animalsthatperceivegreaterdetailsthan

humans(e.g.,eaglesorcats)mayactuallyseetheindividual

pixels.Webreakupthepictureintosmallerelements(pixels),

butthereareenoughofthemandtheyaresmallenoughthat

thepicturedoesn'tlookchoppywhenviewedfromanormal

viewingdistance.Ifyoucanseetheeffectsofthedigitization

(e.g.,lineshavesharpedges,youseelittlerectanglesinsome

spots),wecallthatpixelizationtheeffectwhenthedigitization

processbecomesobvious.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 4. Modifying Pictures Using Loops

Tải bản đầy đủ ngay(0 tr)

×