Tải bản đầy đủ - 0 (trang)
Chapter 5. Modifying Pixels in a Matrix

Chapter 5. Modifying Pixels in a Matrix

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

Chapter5.ModifyingPixelsinaMatrix

5.1 COPYINGPIXELS

5.2 COPYINGANDTRANSFORMINGPICTURES

5.3 CONCEPTSSUMMARY



ChapterLearningObjectives

Themedialearninggoalsforthischapterare:

Tomirrorpictures,horizontallyorvertically.

Tocomposepicturesintooneanotherandcreatecollages.

Toblendtwopictures.

Torotatepictures.

Toscalepicturessmallerandlarger.

Thecomputersciencegoalsforthischapterare:

Tousenestedloopsforprocessingelementsofamatrix(atwo-dimensional

array).

Toinitializeandchangemultiplevariablesinaforloop.

Todevelopsomedebuggingstrategies,specifically,usingprintstatementsto

exploreexecutingcode.

Tobreaklongmethodsintosmallerpieces.



Toshowhowtoreturnavaluefromamethod.

Tousemethodoverloading.







[Page131(continued)]



5.1.CopyingPixels

WecanonlygetsofarinourimageprocessingwithgetPixels()

beforeweneedtoknowwhereapixelis.Forexample,ifwe

wanttocopyjustpartofapicturetoanotherpicture,wewill

needtoknowthexandyvaluestostartwithandendat.



5.1.1.LoopingAcrossthePixelswithaNested

Loop

Wecan'tuseasingleforloopifwewanttokeeptrackofthex

andyvaluesforapixel.Wehavetousetwoforloopsoneto

movehorizontallyacrossthecolumns,andtheothertomove

verticallytogeteverypixel.ThemethodgetPixels()didthis

insideitself,tomakeiteasiertowritesimplepicture

manipulations.Butifyouwanttoaccesseachindividualpixel,

you'llneedtousetwoloops,oneforeachdimensionofthe

picture.Theinnerloopwillbenestedinsidetheouterloop,

literally,insideitsblock.



[Page132]

Yourloopswilllooksomethinglikethis:

//loopthroughthecolumns(xdirection)

for(intx=0;x
{

//loopthroughtherows(ydirection)

for(inty=0;y
{

//getthecurrentpixelatthisxandyposition

pixel=getPixel(x,y);



//dosomethingtothecolor

//setthenewcolor

pixel.setColor(aColor);

}

}



Thiswillprocessalltheyvaluesfromtoptobottominthefirst

columnandthenalltheyvaluesinthenextcolumnandsoon

untilallthepixelsareprocessed.

Youcouldalsoprocessallthexvaluesinthetoprowandthen

allthexvaluesinthenextrowandsoonusingthis:

//loopthroughtherows(ydirection)

for(inty=0;y
{

//loopthroughthecolumns(xdirection)

for(intx=0;x
{

//getthecurrentpixelatthisxandyposition

pixel=getPixel(x,y);

//dosomethingtothecolor

//setthenewcolor

pixel.setColor(aColor);

}

}



Doesitmatterwhichwayyouprocessthepixels?Notifallyou

aretryingtodoisprocessallthepixels.Bothoftheseloopswill



processallthepixelsinapicture.

Forexample,here'sProgram13(page119),butusingexplicit

pixelreferences.



Program18.LightenthePictureUsingNested

Loops

(Thisitemisdisplayedonpages132-133intheprint

version)



/**

*Methodtolightenthecolorsinthepicture

*/

publicvoidlighten2()



[Page133]

{

Colorcolor=null;

Pixelpixel=null;

//loopthroughthecolumns(xdirection)

for(intx=0;x
{

//loopthroughtherows(ydirection)

for(inty=0;y
{

//getpixelatthexandylocation

pixel=getPixel(x,y);

//getthecurrentcolor

color=pixel.getColor();

//getalightercolor

color=color.brighter();

//setthepixelcolortothelightercolor

pixel.setColor(color);

}

}

}



Let'swalkthrough(trace)howitwouldwork.Imaginethatwe

justexecutedpicture.lighten2().

1. Thecodepicture.lighten2()executestheobjectmethodin

thePictureclasspublicvoidlighten2().Themethodis

implicitlypassedthecurrentpictureobject(youcanreferto

thecurrentpictureobjectusingthekeywordthis).

2. ThecodeColorcolor=null;andPixelpixel=null;declares

thevariablescolor(anobjectoftheColorclass)andpixel

(anobjectofthePixelclass).Bothoftheseareinitializedto

null(notreferringtoanyobjectyet).Thesevariableswillbe

neededwhenweareloopingthroughthepixels.Wecould

declaretheseintheforloopbutthentheywouldbe

redeclaredeachtimethroughtheloop.Itisbetterto

declarethemoncebeforetheloopandchangethemeach

timethroughtheloop.

3. Thecodefor(intx=0;x
variablexoftypeintwhichwillbeinitializedto0andthena

checkwillbemadetoseeifxislessthanthewidthofthe

currentPictureobject.Ifxislessthanthewidth,thenthe

bodyofthisforloopwillbeexecuted.Afterthebodyofthe

loophasbeenexecutedonetimethevalueinxwillbe

incrementedandthecontinuationconditionwillbetested

again.

4. Thecodefor(inty=0;y
variableyoftypeintwhichwillbeinitializedto0.Thetest

checksthatyislessthantheheightofthecurrentPicture

object.Ifyislessthantheheightthenthebodyofthisfor

loopwillbeexecuted.Afterthebodyhasexecutedthevalue

inywillbeincrementedandthecontinuationconditionwill

betestedagain.



[Page134]

5. Thecodepixel=getPixel(x,y);setsthevariablepixeltorefer

tothePixelobjectatthegivenxandylocationinthe

picture.

6. Thecodecolor=pixel.getColor();setsthevariablecolorto

refertotheColorobjectatthecurrentpixel.

7. Nextcomescolor=color.brighter();.Thiscreatesanew

lighter(brighter)ColorobjectbasedontheoriginalColor

objectandsetsthevariablecolortorefertothatnewColor

object.

8. Thecodepixel.setColor(color);setsthecurrentpixel'scolor

tobethelightercolor.

9. Eachtimewereachtheendoftheinnerforloop,they

valuewillbeincrementedby1andthenthevalueofywill

becomparedtotheheightofthepicture.Ifthevalueofyis

lessthantheheight,thestatementsinthebodyoftheloop

willbeexecutedagain.Ifthevalueofyisequalorgreater

thantheheight,executionwilljumptothenextstatement

(theouterloop).

10. Eachtimewereachtheendoftheouterforloopthexvalue

willbeincrementedby1andthenthevalueofxwillbe

comparedtothewidthofthepicture.Ifthexvalueisless

thanthewidthofthepicture,thecommandsintheloop

bodywillbeexecuted.Ifthevalueofxisequalorgreater

thanthewidthofthepicture,executionwillcontinueatthe

statementfollowingthebodyoftheloop.



5.1.2.MirroringaPicture

Let'sstartoutwithaninterestingeffectthatisonlyoccasionally



useful,butitisfun.Let'smirrorapicturealongitsverticalaxis.

Inotherwords,imaginethatyouhaveamirror,andyouplaceit

onapicturesothattheleftsideofthepictureshowsupinthe

mirror.That'stheeffectthatwe'regoingtoimplement.We'lldo

itinacoupleofdifferentways.

First,let'sthinkthroughwhatwe'regoingtodo.Wewantto

copythepixelinthefirstcolumnandfirstrow(0,0)tothe

pixelinthelastcolumnandfirstrow(width1,0).Wewillcopy

thepixelinthesecondcolumnandfirstrow(1,0)tothe

secondtolastcolumnandfirstrow(width2,0).Wewill

continuetodothisuntilwereachthemiddleofthepicture

(width/2).Rememberthattheindexforthelastcolumnisone

lessthanthewidthsoeachtimethroughtheloopweare

copyingfromthe(x,y)to(width1x,y).

Whatifwehaveanevennumberofpixels?Thesmallesteven

numberofpixelsistwo.ThemirrorPointwouldbe(2/2=1).The

firsttimethroughtheloopthiswouldcopyfrom(0,0)to(width

10,0)whichis(1,0).Thenxwouldincrementandtheinner

loopwouldstopsincexisn'tlessthanthemirrorPoint(Figure

5.1).



[Page135]

Figure5.1.Oncewepickamirrorpoint,wecan

justwalkxhalfwayandcopyfrom(x,y)to

(width1x,y).



Whatifwehaveanoddnumberofpixels?Wedon'twantto

copythemiddlepixel.Let'stryitwiththreepixels.The

mirrorPointwouldbe(3/2=1).Rememberthatintegerdivision

resultsinanintegerresultandthefractionalpartisthrown

away.Thefirsttimethroughtheloopthiswouldcopyfrom(0,

0)to(width10,0)whichis(2,0).Thenxwouldincrementand

theinnerloopwouldstopsincexwouldn'tbelessthanthe

mirrorPoint.

TakealookatFigure5.1toconvinceyourselfthatwe'llactually

reacheverypixel(exceptthemiddleoneifthereareanodd

numberofpixels)usingthisscheme.Here'stheactualprogram.



Program19.MirrorPixelsinaPicturealonga

VerticalLine

(Thisitemisdisplayedonpages135-136intheprint

version)



/**

*Methodtomirroraroundaverticallineinthemiddle

*ofthepicturebasedonthewidth

*/

publicvoidmirrorVertical()

{

intwidth=this.getWidth();

intmirrorPoint=width/2;

PixelleftPixel=null;

PixelrightPixel=null;

//loopthroughalltherows

for(inty=0;y
{

//loopfrom0tothemiddle(mirrorpoint)

for(intx=0;x
{

leftPixel=getPixel(x,y);



[Page136]

rightPixel=getPixel(width-1-x,y);

rightPixel.setColor(leftPixel.getColor());

}

}

}



We'duseitlikethis,andtheresultappearsinFigure5.2.

>StringfileName=

"C:/intro-prog-java/mediasources/caterpillar.jpg";

>Picturepicture=newPicture(fileName);

>picture.show();

>picture.mirrorVertical();

>picture.repaint();



Figure5.2.Originalpicture(left)andmirrored



alongtheverticalaxis(right).



Canwemirrorhorizontally?Sure!



Program20.MirrorPixelsHorizontally,Top-toBottom

(Thisitemisdisplayedonpages136-137intheprint

version)



/**

*Methodtomirroraroundahorizontallineinthemiddle

*basedontheheight.Itcopiesthetopmirroredto

*thebottom

*/

publicvoidmirrorHorizontal()

{

intheight=this.getHeight();

intmirrorPoint=height/2;

PixeltopPixel=null;

PixelbottomPixel=null;

//loopthroughthecolumns

for(intx=0;x
{

//loopfrom0tojustbeforethemirrorpoint



[Page137]

for(inty=0;y


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

Chapter 5. Modifying Pixels in a Matrix

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

×