Tải bản đầy đủ - 0 (trang)
Chapter 14. Encoding, Manipulating, and Creating Movies

Chapter 14. Encoding, Manipulating, and Creating Movies

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

Chapter14.Encoding,Manipulating,and

CreatingMovies

14.1 GENERATINGFRAME-BASEDANIMATIONS

14.2 WORKINGWITHVIDEOFRAMES

14.3 CONCEPTSSUMMARY



ChapterLearningObjectives

Themedialearninggoalsforthischapterare:

Tocreateframe-basedanimationswithsimplegeometricshapes,text,and

images.

Todospecialeffectslikefade-outandchromakeyinmovies.

Thecomputersciencegoalsforthischapterare:

Toexplainwhymoviestakesomuchspacetostore.

Toaddparameterstomethodstomakethemmorereusable.

Toreuseearliermethodstomakemovies.



Movies(video)areactuallyverysimpletomanipulate.Theyare

aseriesofpictures(frames).Youneedtobeconcernedwiththe

framerate(thenumberofframespersecond),butit'smostly

justthingsyou'veseenbefore.We'regoingtousetheterm



moviestorefergenericallytoanimations(motiongenerated

entirelybygraphicaldrawings)andvideo(motiongeneratedby

somekindofphotographicprocess).

Whatmakesmoviesworkisafeatureofourvisualsystem

calledpersistenceofvision.Wedonotseeeverychangethat

happensintheworld.Forexample,youdon'ttypicallyseeyour

eyesblink,eventhoughtheydoitquiteoften(typically20

timesaminute).Oureyesretainanimageforashortperiodof

time.

Ifweseeonerelatedpictureafteranotherfastenough,oureye

retainstheimageandourbrainseescontinuousmotion.Ifthe

picturesaren'trelated,ourbrainreportsamontage,acollection

ofdisparate(thoughperhapsthematicallyconnected)images.

Werefertothis16framespersecond(fps)asthelowerbound

forthesensationofmotion.

Earlysilentpictureswere16fps.Motionpicturesstandardized

on24fpstomakesoundsmoother.(Everwonderwhysilent

picturesoftenlookfastandjerky?Thinkaboutwhathappens

whenyouscaleupapictureorsoundthat'sexactlywhat

happensifyouplaya16fpsmovieat24fps.)Digitalvideo

(e.g.,videocameras)captureat30fps.Howhighisuseful?

TherearesomeU.S.AirForceexperimentssuggestingthat

pilotscanrecognizeablurboflightintheshapeofanaircraft

(andfigureoutwhatkinditis)in1/200ofasecond!Video

gameplayerssaythattheycandiscernadifferencebetween30

fpsvideoand60fpsvideo.



[Page485]

Moviesarechallengingtoworkwithbecauseoftheamountand

speedofdatainvolved.Real-timeprocessingofvideo(e.g.,

doingsomemodificationtoeachframeasitcomesinorgoes

out)ishardbecausewhateverprocessingyoudohastofitinto

1/30ofasecond!Let'sdothemathforhowmanybytesare



neededtorecordvideo:

Onesecondof640x480framesizeimagesat30fps

means30(frames)*640*480(pixels)=9,216,000pixels.

At24-bitcolor(onebyteforeachofR,G,andB),that's

27,648,000bytes,or27megabytespersecond.

Fora90-minutefeaturefilm,that's90*60*27,648,000=

149,299,200,000bytes149gigabytes.

Digitalmoviesarealmostalwaysstoredinacompressed

format.ADVDonlystores6.47gigabytes,soevenonaDVD

themovieiscompressed.MovieformatstandardslikeMPEG,

QuickTime,andAVIareallcompressedmovieformats.They

don'trecordeveryframetheyrecordkeyframesandthen

recorddifferencesbetweenoneframeandthenext.TheJMV

formatisslightlydifferentit'safileofJPEGimages,soevery

frameisthere,buteveryframeiscompressed.

AnMPEGmovieisreallyjustanMPEGimagesequencemerged

withanMPEG(likeMP3)audiofile.We'regoingtofollowthat

leadandnotdealwithsoundhere.Thetoolsdescribedinthe

nextsectioncancreatemovieswithsound,buttherealtrickof

processingmoviesishandlingallthoseimages.That'swhat

we'regoingtofocusonhere.



[Page485(continued)]



14.1.GeneratingFrame-BasedAnimations

Tomakemovies,we'regoingtocreateaseriesofJPEGframes

anddisplaythem.WehaveincludedaclassFrameSequencerwhich

willhelpyougeneratetheframes.TheclassFrameSequenceralso

createsanobjectoftheclassMoviePlayertodisplaytheframes.

TheMediaToolsapplicationontheCDcanreassembleJPEG

framesintoaJMVmovie.YoucanalsousetoolssuchasApple's

QuickTimePro(http://www.apple.com/quicktime)or

ImageMagick(http://www.imagemagick.org/),whichcanalso

createQuickTime,MPEG,orAVImoviesfromindividualframes

(andgoinreverseburstamovieintoabunchofframes).

We'llplaceallofourframesinasingledirectory,andnumber

themsothatthetoolsknowhowtoreassemblethemintoa

movieintherightorder.We'llliterallynameourfiles

frame0001.jpg,frame0002.jpg,andsoonwithleadingzeros,sothat

thefilesareinorderwhenplacedinalphabeticalorder.

Here'sourfirstmovie-generatingprogram,whichsimplymoves

aredrectangledowndiagonally(Figure14.1).Wehavecreated

anewclassMovieMakertoholdthemethodsthatmakemovies.



Figure14.1.Afewframesfromthefirstmovie:

Movingarectangle.

(Thisitemisdisplayedonpage487intheprintversion)



[Page486]

Program130.SimpleMotionofaRectangle



importjava.awt.*;

/**

*Classtocreateframesforamovie

*@authorBarbEricson

*/

publicclassMovieMaker{

/**

*Methodtomakeamoviethathasarectanglemoving

*around

*@paramdirectorythedirectorytoputthemovie

*frames

*/

publicvoidmakeRectangleMovie(Stringdirectory)

{

intframesPerSec=30;

Picturep=null;

Graphicsg=null;

FrameSequencerframeSequencer=

newFrameSequencer(directory);

//loopthroughthefirstsecond

for(inti=0;i
{

//drawafilledrectangle

p=newPicture(640,480);

g=p.getGraphics();

g.setColor(Color.RED);

g.fillRect(i*10,i*5,50,50);

//addframetosequencer

frameSequencer.addFrame(p);

}

//replaythemovie

frameSequencer.show();

frameSequencer.replay(framesPerSec);

}



//mainfortesting

publicstaticvoidmain(String[]args)

{

MovieMakermovieMaker=newMovieMaker();

Stringdir="c:/intro-prog-java/movies/rectangle/";

movieMaker.makeRectangleMovie(dir);

}

}



[Page487]

Youcanchangethedirectorythatwillholdthecreatedmovie

framesfromwhatisspecifiedasthedirvariableinthemain

method.CompileandrunthemainmethodfortheclassMovieMaker.

Youshouldseetherectanglemoveasshownin(Figure14.1).



DebuggingTip:OutofMemoryError

Workingwiththenumberofpicturesyouhaveinamoviecancause

Javatorunoutofmemoryandyoucangetanoutofmemoryerror

(java.lang.OutOfMemoryError).WhentheJavaVirtualMachinestartsitsets

asidesomememorytoworkinandithasalimitofhowmuchtotalit

canuse.YoucanchangethisbyaddingsomeargumentsfortheJava

VirtualMachinewhenyoustartit.InDrJavayoudothisbyclickingon

EDIT,thenPREFERENCES,whichwilldisplaythePREFERENCES

WINDOW.ClickonMISCELLANEOUSunderCATEGORIESontheleft,

andthenenter-Xmx512m-Xms128mtosetthemaximumamountofmemory

to512megabytesandthestartingmemoryto128megabytes.Then

clickonOK.Itmayaskifyoureallyaresurethatyouwanttodothis,

andyoushouldsayOK.ClickonRESETtohavethenewsettingsaffect

theINTERACTIONSPANE.

YoucanactuallysetthemaximumtomoreRAMmemorythanyou

have.Itwillsavesomeoftheitemsinmemorytodiskandbringthem

backinwhentheyareneeded.Thisiscalledvirtualmemory.

Youcanalsodothisusingthecommand-linetoolsfromSun:

java-Xmx512m-Xms128mMovieMaker



Thekeypartofthisrecipeistheg.fillRect(i*10,i*5,50,50);.

EachtimethroughtheloopwecreateanewPictureobjectand

thendrawtherectangleatanewpositioninthePicturebased

onthevalueoftheloopindex.WhenweaddthePictureobject

totheFrameSequencerobject,itwillwriteouttheframetothe

directory.Itwillalsodisplaythecurrentframeusinga

MoviePlayerobject.

HerearethefirstfivevaluesinthecalltothefillRectmethod:

g.fillRect(0,0,50,50);//iis0

g.fillRect(10,5,50,50);//iis1



g.fillRect(20,10,50,50);//iis2

g.fillRect(30,15,50,50);//iis3

g.fillRect(40,20,50,50);//iis4



WhilesetPixel()getsupsetifyoutrytosetapixeloutsideofthe

boundsofthepicture,thegraphicsmethodsoftheGraphicsclass

drawStringandfillRectdon'tgenerateerrors.They'llsimplyclip

theimageforthepicture,soyoucancreatesimplecodeto

makeanimationsandnotworryaboutgoingoutofbounds.This

makescreatingatickertapemoviefairlysimple.



[Page488]

YoucanaddthefollowingmethodtotheMovieMakerclassto

generateamoviewiththetextappearingontherightsideof

thepictureandmovingacrosstotheleft.



Program131.GenerateaTickertapeMovie



/**

*Methodtocreateatickertapemovie

*@paramdirectorythedirectorytowriteto

*@parammessagethestringtodisplay

*/

publicvoidmakeTickerTapeMovie(Stringdirectory,

Stringmessage)

{

intframesPerSec=30;

Picturep=null;

Graphicsg=null;

FrameSequencerframeSequencer=

newFrameSequencer(directory);

Fontfont=newFont("Arial",Font.BOLD,24);



//loopfor2secondsofanimation

for(inti=0;i
{

//drawthestring

p=newPicture(300,100);

g=p.getGraphics();

g.setColor(Color.BLACK);

g.setFont(font);

g.drawString(message,300-(i*10),50);

//addframetosequencer

frameSequencer.addFrame(p);

}

//replaythemovie

frameSequencer.show();

frameSequencer.replay(framesPerSec);

}



Youcantestthiswiththefollowingmain.Youcanchangethe

directorythatwillholdthecreatedmovieframesfromwhatis

specifiedasthedirvariableinthemainmethod.Theresultof

runningthismainmethodisshowninFigure14.2.

publicstaticvoidmain(String[]args)

{

MovieMakermovieMaker=newMovieMaker();

Stringdir="c:/intro-prog-java/movies/tickertape/";

movieMaker.makeTickerTapeMovie(dir,"Buymorewidgets");

}



[Page489]

Figure14.2.Framesfromthetickertapemethod.



Canwemovemorethanonethingatonce?Sure!Ourdrawing

codejustgetsalittlemorecomplicated.Here'sarecipethat

usessineandcosinetocreatecircularmotiontomatchour

linearmotionofProgram130(page486)(Figure14.3).Youcan

addthismethodtotheclassMovieMaker.



Figure14.3.Movingtworectanglesatonce.

(Thisitemisdisplayedonpage490intheprintversion)



Program132.MoveTwoObjectsatOnce



/**

*Methodtomakeamoviethathasatworectanglesmoving

*around

*@paramdirectorythedirectorytoputthemovie

*frames

*/

publicvoidmakeTwoRectangleMovie(Stringdirectory)

{

intframesPerSec=30;

Picturep=null;

Graphicsg=null;

FrameSequencerframeSequencer=

newFrameSequencer(directory);

//loopthroughthefirstsecond



for(inti=0;i
{

//drawafilledrectangle

p=newPicture(640,480);

g=p.getGraphics();

g.setColor(Color.RED);

g.fillRect(i*10,i*5,50,50);

g.setColor(Color.BLUE);

g.fillRect(100+(int)(10*Math.sin(i)),

4*i+(int)(10*Math.cos(i)),

50,50);

//addframetosequencer

frameSequencer.addFrame(p);

}

//replaythemovie

frameSequencer.show();

frameSequencer.replay(framesPerSec);

}



[Page490]

Youcantestthiswiththefollowingmain.Youcanchangethe

directorythatwillholdthecreatedmovieframesfromwhatis

specifiedasthedirvariableinthemainmethod.Theresultof

executingthefollowingmainmethodisshowninFigure14.3.

publicstaticvoidmain(String[]args)

{

MovieMakermovieMaker=newMovieMaker();

Stringdir="c:/intro-prog-java/movies/rectangle2/";

movieMaker.makeTwoRectangleMovie(dir);

}



Wedon'thavetocreateouranimationsoutofthingsthatwe

candraw,likerectangles.WecancopyPictureobjectsto

differentlocations.Thiskindofcoderunsprettyslowly.



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

Chapter 14. Encoding, Manipulating, and Creating Movies

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

×