You are on page 1of 13

JavaMorphTutorial

Animageprocessingprogram

claus.erhard.wimmer@googlemail.com

JavaMorphTutorial
Animageprocessingprogram

Content
Documenthistory.................................................................................................................................2
WhoisMoeder..................................................................................................................................2
ThecreationofMoeder...................................................................................................................2
Themorphingmethodinfilmindustry...........................................................................................2
Starttheprogramwithitssampledata............................................................................................3
License.............................................................................................................................................3
WherecanIfindwhat?.........................................................................................................................4
The.jararchive................................................................................................................................4
Foldersintheworkingdirectory......................................................................................................4
Themodaldialogues........................................................................................................................5
MeshAlgorithm...................................................................................................................................6
Cornerpointmerging.......................................................................................................................6
Triangulationofthemesh'srectangles............................................................................................7
Triangleinterpolation......................................................................................................................7
Polygonclipping...................................................................................................................................8
Creatingtheclipmatrix...................................................................................................................8
Linealgorithm.............................................................................................................................9
Scanlinealgorithm.....................................................................................................................9
Smoothalgorithm........................................................................................................................9
Weightedpixelmerger...................................................................................................................10
Programdesign...................................................................................................................................10
Decoratorpattern...........................................................................................................................10
Configurationclasses.....................................................................................................................11
Themainclass................................................................................................................................11
Dialogues........................................................................................................................................11
Mathematicalclasses......................................................................................................................11
Usageguide.........................................................................................................................................11
Menufunctions...............................................................................................................................11
Configurationvariables..................................................................................................................12
Hints...............................................................................................................................................13
MakeaGimpfilm..........................................................................................................................13
MakeaMPlayerfilm......................................................................................................................14
Werkel............................................................................................................................................14
20130315

GPLv2

1/13

JavaMorphTutorial

Animageprocessingprogram

claus.erhard.wimmer@googlemail.com

Documenthistory
Version

Date

Remark

1.0

20090107

Initialversion.

1.1

20090119

Meshmadeindependentfromthegrid.

Documenthistory

WhoisMoeder
ThecreationofMoeder
Moederisanhermaphroditic,opticalmerged,medialbeing.Itwascreatedbetweentheformer
GermanfederalchancellorMr.GerhardSchroederandthecurrentofficeholderMrs.Angela
Merkel.ThecreationofMoederhasbeendonebythemorphprogramJavaMorphwhichisthe
subjectofthistutorial.DependingontheconfigurationofJavaMorphMoedercanhavedifferent
numbersofsiblingswithseveralmixratiosbetweenitsbothparents.

Schroeder

Moeder

Merkel

Themorphingmethodinfilmindustry
Itmaybetheintentionofoneauthortomergetwosimilarbutdifferentpicturesintooneresult
picture.Thecommonwayistoaddtwohalftransparentlayersoftwoinputpictureswiththesame
size.Butthereisageneralproblem:Exponentregionsofbothpicturescanbesituatedatdifferent
coordinatesevenifbothpictureshavethesamesize.Anadditionalprocessingstepisnecessary
whilerendering.Theintermediatecopiesofbothinputpictureshavetobedeformedinthatmanner
20130315

GPLv2

2/13

JavaMorphTutorial

Animageprocessingprogram

claus.erhard.wimmer@googlemail.com

thatallexponentregionsaremovedtotheircongruentplacewithintheresultpicture.Becausethe
calculationlogicisnotabletofindexponentregions(thoseareeyes,nose,lipsandotherinthecase
ofaportraitpicture)themorphcomputerprogramlaystwoidenticalmeshesoverbothinput
pictures.Theauthorhastomovethemeshpointsovertheexponentpointsofthepictures.Nowthe
morphprogramisabletocreatethemergedpictures.

Starttheprogramwithitssampledata
Toinstalltheprogramyouneedtwoitems:

ThesmallJavaMorphprogramasa*.jararchive.
Sun'sJavaRuntimeEnvironmentVersion1.6aliasVersion6whichisdistributedstand
aloneorasapartoftheJavadevelopmentkit.

IfYouarenotsurewhethertheJREisinstalledonYourcomputeropenaconsolewindowan
type:>javaversion!Aversionof1.6orehighershouldbedisplayed.Ifthisisnotthecaseplease
downloadtheJREfrom:http://java.sun.com/javase/downloads/?intcmp=1281!TostartJavaMorph
openaconsolewindowagainandenter:>javajarJavaMorph<version_extension>.jar.When
calledforthefirsttimeJavaMorphcreatesafolderontheDesktopnamedwiththeprogramname.
Nootherfileswillbecreatedinthefilesystem.

CloseApplication
Userightmousebutton
Leftinput
Rightinput

ScreenshotofJavaMorph
Screenshot
AfterYouhavestartedtheprogramYouwillfindapreparedsampleconfigurationwithmeshes.All
YouhavetodoistoclicktheMorphitemfromthemousebuttonrightpopupmenu.JavaMorph
willcreateasequenceofmorphedpictureswhichYoucanfindinthefollowingdirectory:
Desktop\JavaMorph\output\*.jpg
whiletheDesktopdirectoryissituatedwithintheuser'shome.

License
JavaMorphisdistributedunderGPLv2.Youarefreetocopyandusetheprogramwithoutpayment.
20130315

GPLv2

3/13

JavaMorphTutorial

Animageprocessingprogram

claus.erhard.wimmer@googlemail.com

Allmodificationsareallowed.PleaseprovideanotheruniqueversionnumberifYouhavemade
modifications!Author,sofar,is:claus.erhard.wimmer@googlemail.com.Findsourcesalsointhe
uniquedistributionorinCVS!

WherecanIfindwhat?
The.jararchive
Thisarchiveactsastheprogramdistribution.Itcontainsasampleoriginofthelatercopiedworking
directoryonthedesktop,thebinarydistribution,thesourcefilesandaJavaDocfolder.While
callingthe.jararchivewiththeJavaruntimeinterpretertheworkingdirectoryonthedesktopis
createdifitdoesn'texist.Thefile'snameofthe.jararchiveisJavaMorph_yyyy_mm_dd.jar.This
nameisalsodefinedwithintheclassCStrings.javawithinthesources.Itshallbemodified
accordingtoincreasedversionnumbersoffutureprogramversions.Hint:Youcanopenthe.jar
archivewitheverycommon.zipprogrambyreplacingtheextension.jarbytheextension.zip
temporarily.

Foldersintheworkingdirectory
Folder'sname

Remark

help\*.pdf

Helpfile&tutorialinPDFformat.OpenwithaPDFreaderlikeacrobat.

output\*.jpg

Generatedmorphresult.Oldfilesdeletedbeforeanewbatchrun.

input\*.jpg

Bothinputfilesasleft.jpg&right.jpg.Edgelength~100...~1000.

mesh\*.msh

Bothmeshfiles.Renewedwithdefaults,afterclosing,ifdeleted.

polygon\*.pol

Bothclippolygonfiles.Samebehaviourlikemeshfiles.

debug\*.png

Smoothedclipmatrixviewwithdilatationborders.Calculatedtriangulation
ofthemeshes.

.\*.props

Propertyfilewithpolygonandmeshdimensions.Read&editalsoasASCII
text!Creatednewifremoved.

Directories

20130315

GPLv2

4/13

JavaMorphTutorial

Animageprocessingprogram

claus.erhard.wimmer@googlemail.com

Themodaldialogues
Dialoguename

Screenshot

About

Description

Configuration

Progress

Meshpopup
menu

20130315

GPLv2

Program'sname
Version
License
Workingdirectory

Closeherewith
Settings
Pathoftheworking
directory
Abortbutton
%
Startmorph
Editthemesh
Edittheconfiguration
Addmeshpoints
Removemeshpoints
Returntoeditmesh
Deletebothmeshes
Showglobalinfo

5/13

JavaMorphTutorial

Meshmerging
Triangulation
Dialoguename

Animageprocessingprogram

claus.erhard.wimmer@googlemail.com

Screenshot

Polygonpopup
menu

Description

Addpolygonpoints
Removepolygonpoints
Returntoeditpolygon
Removeonepolygon

Dialogues

MeshAlgorithm
Cornerpointmerging
Subjectofthemeshalgorithmisittocalculateintersectionpointsoftheresultmatrixasweighted
middlevaluesfromintersectionpoints,withidenticalrow&columnindex,fetchedfrombothinput
meshes.Cornerpointsarecalculatedwiththefollowingformulas:
x=xleft*(1ratio)+xright*ratio
y=yleft*(1ratio)+yright*ratio
Thisleadstothefollowingbehaviour:

Triangulationofthemesh'srectangles
Otherthaninversion1.0themeshisnowgridfree.Eachpointoftheleftmeshhasa1:1relationto
apointoftherightmesh,situatedonasimilarposition.Thisisdonebyanumberedorderofboth
mesh'spoints.Thetriangulationalgorithmhastosplitthe50%mergedmeshintoanumberof
obtuseangledtriangles.EverytriangleshallsatisfytheDELAUNYcondition.Theconditionmeans
that,withinthecircumcircleofonetriangle,nocornerpointmustbewhichdoesn'tbelongtothis
triangle.Becausethemeshconsistsofintegers,anumberofpointscanresideexactlyonthecircum
circle.Inthiscasethealgorithmhastochoseoneofthepointstocreatethetriangle.

Triangleinterpolation
TheIntentionis,todeformthecoordinatesofeverypointfromeachinputtriangletothe
20130315

GPLv2

6/13

JavaMorphTutorial

Animageprocessingprogram

claus.erhard.wimmer@googlemail.com

Interpolation
correspondingpointoftheresulttriangle.Thisisdonebyatransformationmatrixwith2rowsand3
columns.Aquadraticmatrixisn'tnecessary,aconcatenationisn'tneededtobedone.Becauseno
gapsintheresultwillbeaccepted,foreverypointoftheresultpicturethecorrespondingpointsof
theinputpicturesarecalculatedreverselywiththefollowingformulas:
xinput=a11*xresult+a12*yresult+a13
yinput=a21*xresult+a22*yresult+a23
Allinallatrianglecanbetransformedbythematrix.Cornerpointsarematchedexactly.Area&
linepointsareinterpolated.Additionallytothenormalaffinetransformwithtranslaterotateand
scalethecoordinatesystemofthetriangleisnotorthogonal.Thereadercanobtainthetransform
matrixbetweenasinglepairoftrianglesbysolvingasystemof6equationswithsixvariables.This
canbedonebyinsert/setequal/addpairsofequations.
(1)xinput_1=a11*xresult_1+a12*yresult_1+a13
(2)yinput_1=a21*xresult_1+a22*yresult_1+a23
(3)xinput_2=a11*xresult_2+a12*yresult_2+a13
(4)yinput_2=a21*xresult_2+a22*yresult_2+a23
(5)xinput_3=a11*xresult_3+a12*yresult_3+a13
(6)yinput_3=a21*xresult_3+a22*yresult_3+a23
Nowthepointsaretransformed.Allpointsbelongtooneindexoftriangleinthelist.
Thenextsectionexplainswhathastobedonewiththecolourvaluesofthepointlists.

Polygonclipping
Creatingtheclipmatrix
AnadditionalfeatureofJavaMorphisthepossibilitytolimittheinformation,movingfromthe
inputpictureintotheresultpicture,bydefiningapolygon.Theinnerofthepolygonappearswithin
theresultwhentheratiopointstothespecifiedinputpicture.Aclipmatrixwiththedimensionsof
theresultpictureiscreated.Eachpointoftheclipmatrixcorrespondstoonepixelatthepicture.If
thevalueoftheclippictureis0.0thenthepixelisnotshown.Ifthevalueis1.0thenthepixelis
shown.Smoothededgesofthepolygonleadtointermediatevalues.

Linealgorithm
Foreachlineofthepolygonapixelprooflinewithintheclippictureiscreated.Exactlytheline
shallbeproofinorthogonaldirectionsbutnotindiagonaldirections.Thisisdonebytheparameter
p.
20130315

GPLv2

7/13

JavaMorphTutorial

Animageprocessingprogram

claus.erhard.wimmer@googlemail.com

colourmerge
Smoothalgorithm
dx=x2x1
dy=y2y1
p_max:=maximum(dx,dy)|p_max>0
Forallintegerpfrom0top_maxdothefollowing:
x=x1+p*(x2x1)
y=y1+p*(y2y1)

Scanlinealgorithm
Thealgorithmhastofilltheinnerofthepolygonwiththeclipvalueof1.0.Thisisperformedbya
statemachine(calledlinewiseforeachpixeloftheline):
Oldstate

Condition

NewState

Action

0(initialforeachline) Linehit

Storeposition1.

Nolinehit

Linehit

Storeposition2.

Connectpositions1&2withclipvalue1.0.

ScanLine

Smoothalgorithm
Withincreasingdistancefromtheouteredgeofthepolygonthevalueoftheclippictureramps
downlinearfrom1.0to0.0.Asmoothfunctionrendersthispatternintotheclipmatrix.Itis
executedforeachpixelofeachlineofthepolygon.Acopyofthelinealgorithmcalculatesthe
pixelsforthesmoothalgorithm.Thesmoothfunctionactswithinaquadraticareaaroundthepixel.

Weightedpixelmerger
Finallythemorphalgorithmmergesthecoloursofthetwoinputpixelsintothecolouroftheresult
pixel.Sofarthealgorithmdoesn'tdistinguishbetweenredgreenandblue.Theoutputcolour
dependsnowonstepratio,clipmatrixandinputcoloursfromleft&right.

Programdesign
Decoratorpattern
TheprogramdisplaysbothinputpicturesinseparateJComponentsimplementedasClassCFrame.
20130315

GPLv2

8/13

JavaMorphTutorial

Animageprocessingprogram

claus.erhard.wimmer@googlemail.com

WhileCFrameonlydisplaysthebackgroundofthepicture,fourdecoratorsrenderanumberof
detailsfortheframelayout.FirsttheCPictureDecoratorpaintsthepicture,scaledtothewindow
sizebutwithfixededgeratio.SecondtheCMeshDecoratorpaintsthemeshandreceivesuseredit
events.ThirdtheCPolygonDecoratorpaintstheclippolygonmakesiteditableandprovidestheclip
picture,generatedbythealgorithmsexplainedabove.FourththeCPopupMenuDecoratorpaintsthe
mousesymbolandshowsthepopupmenu.AllfourclassesimplementtheIDecoratorinterface.
Herethepaint()methodisthemostimportantprocedure.CFramecallssequentiallythepaint()
methodofallfourdecoratorsinthedescribedorder.

Configurationclasses
ThefirstconfigurationclassisCStrings.Thisclassholdsanumberofdirectorypathsandfile
names.Thenameofthe.jararchiveofthisapplicationshallbeenteredhere.Thesecond
configurationclassisCConfig.Thisclassholdsthenumericalconfigurationdataforthemorph
batch.WhentheprogramstartsCConfigreadsapropertyfilewhereitalsosavesthenumericaldata
duringtheprogramshutdown.

Themainclass
CMainisthemainentryforJavaMorph.Itcontainsthemainfunctionanditisreferencedbythe
automaticallygeneratedmanifestfileofthe.jararchive.ThisclassinstancesalsothemainJFrame
oftheapplicationplusthethreedialogues.TheJFrameitselfshowsaleftandarightpicture,
paintedbyCFramewhichareseparatedbyaverticallinepaintedbyaCSeparatorclass.

Dialogues
Additionallytothemainwindowtherearethreeclassesholdingdialogues.Thefirstdialogueis
CConfigwhichactsalsoasstoreforconfigurationdata.Itcontainsseveralinputfieldsrealizedas
CEditclassinstances.TheseconddialogueisCAboutwhichshowstheprogram'smetadata,like
versioninfo&workingdirectory,totheuser.ThethirddialogueisCProgress.CProgressisthe
modalprogressbar.Itblocksmainthreadexecutionduringthemorphbatch.That'swhythemorph
batchhasitsownthread.

Mathematicalclasses
ThecentralmathematicalclassisCMorphOperator.Itperformsthemorphbatchwiththenumber
ofconfiguredintermediatepictures.Themeshtransform&pixelmergealgorithmsbelongtothis
class.CMorphOperatorhasthreehelperclasses.CGeocalculatestransformationmatrices.
CTriangleisasetofpointslimitedbythreecorners.Ithasmultipleinstances.CTransformcontains
theelementsofthetransformationmatrixwhichisexplainedabove.
Version1.1containstwonewclasses:CTriangulationwhichreadsthemeshandcreatesacollection
20130315

GPLv2

9/13

JavaMorphTutorial

Animageprocessingprogram

claus.erhard.wimmer@googlemail.com

ofitstriangles.AndCLinewhichisusedbyCTriangulation.CLinerepresentsaedgeofone
triangle.Itcandetectacrossingedgeofanothertrianglefortestpurposes.

Usageguide
Menufunctions
Usetherightmousebuttontoopenthepopupmenu!
Function'sname

Description

Morph!

Startingthemorphbatch.Deletestheoldoutputfiles.Progressbarisshown
whenpreparationsaredoneandrenderingoftheoutputfilesbegins.

Editmesh.

Editmeshofcorrespondingpicture.Stopeditpolygon.Usercanmovethe
nearestmeshpointbydraggingwiththeleftmousebutton.Whenselectedfor
bothpictures:Theotherpictureshowsthecorrespondingmeshpoint.

Editpolygon.

Editpolygonofcorrespondingpicture.Stopeditmesh.Usercanmovethe
cornerpointsbydraggingwiththeleftmousebutton.

Editconfig>

Openthedialoguetoeditnumericalconfigurationvalueswhichinfluencethe
morphbatch.Valuesarestoredbyclosingthedialoguewindow.

MeshPoints/Add Addpointstobothmeshes.Addeachsinglepointatcursorpositionby
Points+
clickingtheleftmousebutton.
MeshPoints/Sub Removepointfrombothmeshes.Removeeachsinglepointnearesttoto
Points
cursorbyclickingtheleftmousebutton.
MeshPoints/Off Returntoeditmeshmode.HereYoucandragthemeshpoints.
Points
MeshPoints/
DeletemeshX

Deletethosemeshwhichbelongstothecorrespondingpicturefromthefile
system.Adefaultmeshwiththeconfigureddimensionsisprovidedand
painted.Theprogramsavesthenewmeshduringshutdown.

PolygonPoints/
AddPoints+

Addpointstoonepolygon.Addeachsinglepointatcursorpositionby
clickingtheleftmousebutton.

PolygonPoints/
SubPoints

Removepointsfromonepolygon.Removeeachsinglepointnearesttocursor
byclickingtheleftmousebutton.

PolygonPoints/
OffPoints%

Returntoeditpolygonmode.Youcandragthepolygonpoints.

PolygonPoints/
DeletepolygonX

Deletethosepolygonwhichbelongstothecorrespondingpicturefromthefile
system.Adefaultpolygonwiththeconfigureddimensionsisprovidedand
painted.Theprogramsavesthenewpolygonduringprogramshutdown.

20130315

GPLv2

10/13

JavaMorphTutorial

Animageprocessingprogram

Function'sname
Helpabout?

claus.erhard.wimmer@googlemail.com

Description
Showprograminfo.HereYoucanfindthepathtotheworkingdirectory,the
author'snameandtheversioninfo.

Menufunctions

Configurationvariables
Youcaneditthisvariablesbyopeningtheconfigurationdialogue.Invalidvaluesareclippedsuiting
intothe,astooltips,displayed,boundaries.Closethedialoguewindowtostore!
Variable'sname

Description

Numofmorphsteps

Whenentering<N>thenthedistancebetweenleftandrightisdivided
into<N>steps.Theoutputdirectorywillcontaintheleft&theright
pictureplus<N1>mergers.

Rowsofmesh

Numberofhorizontalrowsofquadsforbothmeshes.Whenmodified:
Oldmeshisdeleted&newdefaultmeshisprovided.

Columnsofmes

Numberofverticalrowsofquadsforbothmeshes.Whenmodified:Old
meshisdeleted&newdefaultmeshisprovided.

Pointsofpolygon

Cornerpointsofbothpolygons.Whenmodified:Bothpolygonsare
deletedandnewdefaultbothareprovided.

Pointsofrightpolygon

Cornerpointsoftherightpolygon.Whenmodified:Oldrightpolygonis
deleted&newdefaultrightpolygonisprovided.

Smoothradius

Sizeofthefuzzyareaaroundthepolygonsinbothclipmatrices.Usedto
hideborderswhenYouuseJavaMorphtomounttwopictures.

Marksize

Sizeofcursorandmarkedmesh+polygonpoints.

Workdir

Readonlybutcopyable.Absolutepathoftheworkingdirectory.

Configurationvariables

Hints
Afterrenderingthesampleyoucanfeelfreetosubstitutethepicturesleft.jpg&right.jpginthe
inputdirectorybyyourownboth.Deletealsothemeshestherefore&adoptnewdefaultmeshes.
ConsiderthattheCPUtimegrowssquarewisewiththepicture'sdiagonal.However,itisn't
necessarythatbothpictureshaveidenticaldimensions.Thedimensionoftheresultistheunionof
thedimensionsfromleft.jpg&right.jpg.Youcanalsodealwithcopiesofthewholeworking
directory.ThismaybeusefulifYouintendtoarchiveanumberofmorphprojects.

20130315

GPLv2

11/13

JavaMorphTutorial

Animageprocessingprogram

claus.erhard.wimmer@googlemail.com

MakeaGimpfilm
Asimplewaytocreateafilmistherenderingasanimated.gifbytheGnuImageManipulation
Program.Trythefollowing:
1. OpenGimp.
2. ClickFile>Open(000.jpgfromoutputdirectory).
3. ClickFile>Open_as_Layers(Markallotherfilesofoutputdirectory)inpicturewindow.
4. ClickFile>SaveAs(*.gif).
5. ConfirmSaveAs_Animation+Make_Index!
6. StartExport.
7. Chooseloopmode&speed.
8. ClickOK!
9. Openthe.gifwithawebbrowser.

MakeaMPlayerfilm
1. DownloadMplayer.
2. Gotothedirectory:.../Desktop/JavaMorph/output!
3. Enter:#>mencoder"mf://*.jpg"mffps=10ooutput.aviovclavclavcoptsvcodec=mpeg4

Werkel
FinallyIwanttoimprovemyapplyphototogetabetterjobinabigcompany.Itisnoteasyforme
tosmileonphotos.That'swhyIdecidedtomergealittlebitMrs.Merkelintomyphoto.Toreduce
theforgery,thistimeIdecidedtostealonlytheproportionsfromMrs.Merkel,stepbystep.ButI
wanttoholdmyownpixelsonallpictures.

20130315

GPLv2

12/13

JavaMorphTutorial

Theauthor

20130315

Animageprocessingprogram

Werkel

claus.erhard.wimmer@googlemail.com

Werkelsquarewise

GPLv2

13/13

You might also like