Rochester Institute of Technology
RIT Scholar Works
Theses
Thesis/Dissertation Collections
4-18-1990
Expressing imaging algorithms using a C++ based
image algebra programming environment
Davender Nath Gupta
Follow this and additional works at:
http://scholarworks.rit.edu/theses
This Thesis is brought to you for free and open access by the Thesis/Dissertation Collections at RIT Scholar Works. It has been accepted for inclusion
in Theses by an authorized administrator of RIT Scholar Works. For more information, please contact
.
Recommended Citation
EXPRESSING IMAGING ALGORITHMS
USING A C++ BASED
IMAGE ALGEBRA PROGRAMMING ENVIRONMENT
by
D~vender
Nath Gupta
Captain, Canadian Forces
B.Eng. Royal Military College of Canada
(1984)
A
th~sis
submitted in partial fulfillment
of the requirements for the degree of
Master of Science in the Center for
Imaging Science in the College of
Graphic Arts and Photography of the
Rochester Institute of Technology
18 April 1990
Signature of the Author
_D_a_v_a_nd_e_r_N_at_h_G_u-'-p_ta
_
Accepted by
M_en~d_i_Va_e_z_-P_ra_v_a_ni~
_
COLLEGE OF GRAPHIC ARTS AND PHOTOGRAPHY
ROCHESTER INSTITUTE OF TECHNOLOGY
ROCHESTER, NEW YORK
CERTIFICATE OF APPROVAL
M.S. DEGREE THESIS
The M.S. Degree Thesis of Davender Nath Gupta
has been examined and approved
by the thesis committee as satisfactory
for the thesis requirement for the
Master of Science degree
Dr. Edward
R.
Dougherty, Thesis Advisor
Dr. Peter O. Anderson
Dr. Harvey Rhody
Title of Thesis:
THESIS RELEASE PERMISSION FORM
ROCHESTER INSTITUTE OF TECHNOLOGY
COLLEGE OF GRAPHIC ARTS AND PHOTOGRAPHY
EXPRESSING IMAGING ALGORITHMS USING A C++ BASED
IMAGE ALGEBRA PROGRAMMING ENVIRONMENT
I. Davender Nath Gupta, hereby grant permission to the Wallace Memorial Ubrary of
R.I.T.
to
reproduce my thesis in whole or in part. Any reproduction will not be for commercial use or profit.
EXPRESSING IMAGING ALGORITHMS USING
A
C++
BASED
IMAGE ALGEBRA PROGRAMMING
ENVIRONMENT
by
Davender Nath Gupta
Submittedto the Center for
Imaging
Science in partialfulfillmentoftherequirementsforthedegreeofMasterofScience
atthe Rochester Instituteof
Technology
ABSTRACT
Homogeneous Image Algebra isused asthebasis foranimage processingenvironment
thatusesthe
image,
insteadofthepixel, asthefundamentalunitbeing
manipulated. Theobject-orientedlanguageC++isusedtoimplementtheenvironment. Examplesofapplications arethat
include
filtering,
regiongrowing, skeletonization,Fourier TransformsandHadamard transformsare presented. ThisthesisconcludesthatC++does haveseveralfeatureswhichareof great
ACKNOWLEDGEMENTS
Thisworkhas beenmade possiblethrough thesupport oftheCanadian Forces.
Iwishto thankDr. Edward
Dougherty,
whofirstsuggested mythesistopic. Workonthisproblem allowed metobecomecomfortablein
Pascal, C,
andC++,
as well aswithUNIX,
thuskeeping
mycomputer skillsuptodate(and
givingmetwoexcusestogotoLA!).I also wishtoacknowledgethevaluable assistance ofthedepartmentofComputer
Scienceand Information
Technology
atRIT,
andspecifically Dr. PeterAnderson,
whoprovidedDEDICATION
TABLE
OF CONTENTSTABLE OF CONTENTS vii
CHAPTER 1
-INTRODUCTION 1-1
AIM OF THESIS 1
Aimofthesis 1
PROBLEM STATEMENT 1
Background 1
Problem 1
CHAPTER 2
-PREVIOUS WORK 2-1
GENERAL 1
Chapter Objective 1
IMAGE ALGEBRA 1
Context 1
Originofimagealgebra 1
COMPUTER IMPLEMENTATIONS OF IMAGEALGEBRA 2
General 2
AFATL Image Algebra 2
C-3PL 3
SLIP 4
Otherimplementations 4
CONCLUSION 5
CHAPTER 3- GENERAL DESIGN 3-1
GENERAL
Chapter Objective USERS
Intended audience and uses
Level of user sophistication
Hardware and Software
DESIGN QUALITIES 2
CHOICE OF MATHEMATICAL BASIS 2
Conclusion 3
USER INTERFACE 4
General 4
Blockdiagrams 4
Alphanumeric expressions 5
Conclusion 6
IMPLEMENTATION STYLES 6
Programming
Styles 6Procedural approach 6
Object-oriented approach 6
Conclusion 8
LIBRARYVS. LANGUAGE 8
Desired characteristicsoffinal system 8
Implementation approach 8
Conclusion 9
SELECTION OF A HOSTLANGUAGE 9
General 9
Pascal 9
FORTRAN 1 1
ANSIC 1 2
C++ 1 4
Conclusion 1 6
GENERAL DESIGN 16
CHAPTER 4- IMPLEMENTATION 4-1
GENERAL 1
Chapter Objective 1
Notation Conventions 1
FEATURES 2
General 2
oopsSlip Class
Library
2Preprocessor 2
DERIVED TYPE CLASSES 2
General 2
Byte 2
Coord 3
IMAGE CLASSES 3
Abstract data type 3
Frames of reference 4
Elementvalues 4
Image types 5
Nullimages 5
IMAGE CLASS OPERATORS 5
OverloadedC++operators 5
Unary
operators 5180 degreerotation
(-)
6Complement
(!)
6Binary
operators 6Multiplicative Operators 6
Multiplication
(*)
6Division
(/)
7Zero-division
(%)
7Additive Operators 7
Addition
(+)
7Subtraction
(-)
7Relational Operators 8
Equality
Operators 8Additional Image Class Operators (Extended
Operators)
8IMAGECLASS FUNCTIONS 1 0
Organization 1 0
Constructors and destructors 1 0
Self managementfunctions 1 1
Basis functions 1 2
Inquiry
functions 1 2Arithmetic functions 1 2
Structural functions 1 3
Extended functions 1 3
Morphological functions 13
Statistical functions 1 3
Thresholding
functions 14Higher-level functions 1 4
FUNCTION CALLING SYNTAX 1 4
Member function invocation 1 4
Friend function invocation 1 5
IMAGE STRUCTURE CLASSES 16
Domain class 1 6
Range classes 17
FOR_DOMAIN_OF CONSTRUCT 1 8
Purpose 1 8
Syntax 1 8
ERROR HANDLING 19
Preconditions and Postconditions 1 9
Error
flag
errno 1 9SOURCE FILE ORGANIZATION 1 9
General 2 0
Header Files 2 0
Source files 20
Program Compilation 2 1
Restrictions and Caveats 21
CHAPTER 5- APPLICATION EXAMPLES 5-1
GENERAL 1
Chapter Objective 1
Applications 1
Algorithm Illustration 1
GREY SCALE DILATION 1
Algorithm Description 1
Implementation 2
REGION GROWING 6
Purpose 6
Algorithm 6
Implementation 7
SKELETONIZATION 9
Aim 9
Algorithm description 9
oopsSlip Implementation 1 0
C Implementation 1 1
FOURIER TFtANSFORM 1 3
Generalized Picture Transform 13
Discrete Fourier Transform 1 3
Inverse Fourier Transform 1 5
oopsSlip Implementation 1 5
HADAMARD TRANSFORM 17
Mathematical description 1 7
Implementation 1 8
FILTERING 20
Aimof algorithm 2 0
Algorithm description 20
oopsSlip Implementation 21
C Implementation 2 2
Image Results 2 3
CHAPTER6- DISCUSSION 6-1
GENERAL 1
Chapter Objective 1
MEETING THE SYSTEM REQUIREMENTS 1
Design Qualities 1
Portability
1Simplicity
1Efficiency
and Performance 2BUT IS ITOBJECT-ORIENTED? 3
Requirementsofan Object-Oriented System 3
Conclusion 5
USE OF IMAGE ALGEBRA 5
General 5
CHAPTER7- FUTURE DIRECTIONS 7-1
GENERAL 1
Chapter Objective 1
USE OFC++VERSION2.0 1
OTHER OBJECT-ORIENTED LANGUAGES 1
Ada 1
Otherlanguages 2
VISUAL INTERFACE 2
CHAPTER 8- CONCLUSION 8-1
APPENDIXA- INTRODUCTIONTO IMAGEALGEBRA A-1
GENERAL 1
HOMOGENEOUS IMAGE ALGEBRA '. 1
Operationsand Inducement 1
Basis 2
FINITE HOMOGENEOUS IMAGE ALGEBRA 2
General 2
Bound Matrix 2
Star 3
Basis operations 3
Extended operators 5
Structural operators 7
Minkowski operators 7
Behaviorof star 8
CONCLUSION 8
APPENDIX B
-CLASS DECLARATION LISTINGS B-1
APPENDIX C
-IMAGE FUNCTION DICTIONARY C-1
EXPRESSING IMAGING ALGORITHMS
USING A C++ BASEDIMAGE
ALGEBRA PROGRAMMING
ENVIRONMENTCHAPTER 1 - INTRODUCTION
AIM OF THESIS
Aim ofthesis. Theaim ofthisthesisistoimplementanimage processingsystemthat
usestheImageastheprimaryunit ofmanipulation.
PROBLEM STATEMENT
Background. Image processingalgorithmsforgeneral-purposecomputersareusually
designedtomanipulatepictureelements,orpixels. Theneedtoimplementalgorithmsthis way
tends,
in manycases, toobscuretheclarityofthe underlyingalgorithm.Severalmathematical
techniques,
calledimagealgebras,have beenproposedtocompletely describe image interactions. The noteworthyapproaches usetheconcept ofthe Imageasthefundamental unitofmanipulation. The definitionofImage may vary between
algebras,butis generallymeanttoencompassthe totalnumber of pictureelements,orpixels, as
Problem. Fewpractical
implementations
have beenmadeofimagealgebras. Ameansof
implementing
animagealgebraexpressionusingadedicated languageorenvironmentisCHAPTER 2 - PREVIOUS WORK
GENERAL
Chapter Objective. Theaim ofthischapteristodescribetheworkinthisfieldtodate.
IMAGE ALGEBRA
Context. Much development in image processing algorithmstodate has been done
empirically,basedon statistical science orsimply intuitive judgement. Severalcurrent problemsin
imaging
pointto the needforastandardized,coherent and completetooltodemonstratethecorrectnessof algorithms. Analgebraic mathematical approachtoimage processingoffersmany
ofthesequalities.
Thegoal of animagealgebraistoexpress allimageoperations
hierarchically
froma smallcollectionofproven,wellbehavedprimitivebasisoperations. Not only doessuch an algebra
providea sound mathematical
framework,
butitalsolaysthefoundation for languagesandsystems whose abilitytoexpressimage processingalgorithms canbe
thoroughly demonstrated,
andthatproduce correct and robust results.
Origin of image algebra. There exists a number ofdifferentimagealgebras, most
basedon an approachtoset mathematics pioneered
by
H. Minkowski[Min03],
and refinedby
GeorgesMatheron
[Mat75]
andJ.P. Serra[Ser81
]
fortextureanalysisof geologicalformations.TheworkofMatheronandSerra has been
directly
appliedin an area ofimageanalysisinvolves analyzing imageswith respectto their shapes, notonly intheir
domain,
orextent,butalsointheirgrey level
(considered
athird dimensionofthedomain). Becauseofitsorigins,it benefitsfroma strictermathematicalformulationthanotherimage processingmethodologies,andis
being
usedtoovercomethe
limitations
oftraditionallinearconvolution-type operations.ThemathematicsofMatheronandSerrawere appliedina systematicwaytoimages
by
twoprimarygroups:
Dougherty
and Giardina([DoG85], [DoG87b], [DoG88a]),
and Ritterandhisteam
{[RSG85], [RDW87]
and[RSW87]
).
The heterogeneous(many-typed)
imagealgebrasdeveloped
by
these twoindependentgroups require several sortsofdatatypes tofully
describeimagealgorithms.
Further developmentoftheDougherty/Giardina imagealgebra resulted ina
homogeneousor single-sortedimagealgebra
([Dou89a]
and[Dou89b]).
Theadvantage ofthissingledatatypealgebraisthatitcan expressanyothertypeofimagealgebra,orany kindofimage
processingoperation. Appendix Aprovides a general overview ofHomogeneous Image Algebra.
COMPUTER IMPLEMENTATIONS OF IMAGE ALGEBRA
General. Aconcise algorithmformulationmethodsuch asimagealgebra provides a
convenient methodfor
defining
acomputingenvironment whereitcanbeused. Threeprincipalgroupshave been workingtoimplementvariationsofMatheronandSerra'swork: Ritterandhis
teamatthe
University
ofFlorida[RDW87],
LougheedandSternberg
attheEnvironmentalResearch InstituteofMichigan
[Ste83]
andDougherty
attheMorphologicalImaging
LaboftheAFATL Image Algebra. UnderthesponsorshipoftheU.S. Air Force Armament
Technical
Laboratory (AFATL)
andthe Defense Advanced Research ProjectsAgency
(DARPA),
aresearchanddevelopmentteamatthe
University
ofFlorida, Gainesville,
headedby
GerhardRitter,
has developedaheterogeneous
(many-sorted)
imagealgebrabasedonimagesandtemplates
[RSG85].
Templatesare a means ofrelatingthedomainoftheinputto thedomainoftheoutput. AFORTRAN based languagepreprocessor enables a usertoprototype image
processingalgorithmsdeveloped using AFATL Image Algebraandimplementthemon a
computer.
Althoughtheirlanguage is relativelycomplete, the templateoperations add a measure of
complexityto thesystem. Inthe
beginning,
itwasdesignedtobeused on a specialized arrayprocessor, althoughlaterversions run on a general-purpose computer.
C-3PL. Researchgroups atthe
University
ofMichiganandtheEnvironmental ResearchInstituteofMichigan
(ERIM),
headedby Stanley Sternberg
andRobertLougheed,
havedevelopedaparallel pipeline imageprocessor,called acytocomputer,and ahigh-level language
specificallycreatedfor imageprocessing,calledC-3PL
[Ste83].
Thecytocomputer applies sequences of neighborhoodtransformations todigitized
images. Eachneighborhoodtransformationismadeinanindividual processingelementknown
asaprocessingstage. Thecomputerisa serial pipeline ofstages,where each stage performs a
transformationontheentire image.
The image processing languageused
by
thecytocomputerisdirectly
basedontheThissystemwas one ofthefirst to dealwithimagesas a whole
(as
opposedto thepixellevel). The image
being
processed iscalledtheactiveimage,
whichismodifiedby
probingorcombination withotherimagescalledstructuringelements. Thearchitecture providesfor
manipulationofboth
binary
images,
usingsilhouettetransformations,
and grey-scaleimages,
usingumbratransformations.
Thecurrentversion ofthecytocomputer istheCyto-HSS
(Cytocomputer-High
SpeedSystem) [Lou89].
Theadvantages ofthecytocomputer arethatmorphological operations are executedvery
fast.
However,
sincethearchitectureisunique, theimage processing languagecannotbeusedon other systems. It isalsointended primarily formorphological imageprocessing.
SLIP. Homogeneous Image Algebrawas extendedinto Finite HomogeneousImage
Algebra
(FHIA) by Dougherty
andGiardina[DoG87b],
which providedabasisforcomputerimplementation.
FHIAis basedontheconceptoftheboundmatrix ofreal values onatwo-dimensional
CartesiangridZx
Z,
Zbeing
theset ofintegers. Thematrixhas dimensionsmrowsby
ncolumns,anditspositioninthegrid isgiven
by
thecoordinates rowtand columnrofthetop
left-handelementinthematrix. Allthevalues ofelementsoutsidetheboundmatrix arecalled *
(star),
or undefined. Undefinedvalues are also allowedinsidethebound matrix. Asignificantfeatureof
FHIA isthatany interaction between finite images
(bound
matrices)canbe defined fromaset,orTheoriginalworkto implement FHIAwasperformed
by
Paramjit
SehdevattheStevensInstituteof
Technology [D0S88],
andwascalledStructured Language
for ImageProcessing
(SLIP).
Itconsisted of alibrary
ofPascalandassembly languagesubroutinesthatexecuted on aDEC VAXcomputer. Theobjective oftheproject wastoprovideaportablemeansforresearchers
toexperimentwithFHIA.
I haveworked on andimprovedthisimplementation
([DGS89]
and[GDA90]),
provingtheconcept of a portable structured
imaging
environment.Other implementations. Theuse ofobject-orientedlanguages for image processing
andimagealgebraimplementation is
beginning
tobeexamined. Peter MarineauandMichael M.SkolnickattheRensselaer Polytechnic Institute
[MSk89]
aredefining
an object-orientedimaging
language formathematical morphology. Acommercial parallelprocessingcomputer, the
AIS-5000
by
AppliedIntelligenceSystems,
isalso programmedin Objective-C[ScW88].
Theseapproachesdonotappearto be basedon a specific algebraic means ofexpressingalgorithms.
Michael A. JenkinsandJanice I. GlasgowofQueen's
University
atKingston,
Ontario havetakenadifferentapproachusingarraytheory,the
'study
ofnested,rectangularly-arrangedcollections ofdataobjects"
([JeG89])
asthebasisfortheirNested InteractiveArray
Language(Nial).
Nialcanbeusedinseveral different programmingstyles(procedural,
object-oriented, etc.)CONCLUSION
Image processingsystemsbasedon acompletemathematicalformulationhave been
designed and built
(Ritter,
Lougheedand Dougherty). Objectorientedtechniquesarebeing
exploredfortheirusein imageprocessing.
To
date,
thereappearstohave beenno attempts atbuilding
animage-as-objectorientedCHAPTER 3 - GENERAL DESIGN
GENERAL
Chapter Objective. Theobjective ofthischapteristodescribethe requirements,
constraintsand designchoicesin
implementing
animage-as-object image processingsystem.USERS
Intended audience and uses. The intendedusers ofthissystem arethe students
andresearch staff oftheRochesterInstituteofTechnology. Thesystem willbeusedfor
demonstration,
prototyping ofimage processingapplications(especially
morphologicalprocessing),andteaching.
Level of user sophistication. Thecomputer experience of users variesfromnovice
toexpert.
Many
fall intothenovicecategory,and are notfamiliarwith computerinternalsordatastructures. Theuser will be familiarwithatleastone ofthe"fundamental"computerlanguages
(FORTRAN,
Pascal,
C,
etc.). Theuser will alsobe familiarwiththebasicprinciples ofimageprocessing.
Hardware and Software. Theequipmentavailable includes
Sun, VAX7VMS,
UNIX/Ultrix,
IBM-PCand Macintoshsystems. Languagesavailable includeFORTRAN,
BASIC,
Pascal,
CandC++. The finalsoftwareshouldbeabletointerfaceas much as possiblewiththeseDESIGN QUALITIES
Thesystemmust provide animage processingenvironmentthatisportable,simple and
efficient.
Portability
canbeachievedby
ensuringthat thesystem canfunctionwithout specialhardwareor software. Thisrequirementallowsthesystemtobeused onanygeneral-purpose
computer.
Thesystem shouldbesimpletouse and maintain. There isno provisionforuser
training,
otherthan thedocumentation provided.
Simplicity
encouragesuse,and reduces potentialsources of errors.
Althoughefficiencyiscompromisedtosomedegree
by
theportabilityrequirement, thesystem should provideforas
timely
a response as possible.CHOICE OF MATHEMATICAL BASIS
Severalauthors
([CDM88],
[JeG89])
havenotedtherequirementforanimage processinglanguageorsystemtobe builtona soundmathematicalbasis.
Using
mathematicaltheory
as astarting pointforsystemdesignensures a consistent and complete set ofoperators, providesa
mechanismforcorrectnessproofs and eliminates redundant andcontradictory constructions,
The primaryrequirementofa mathematicalbasis foranimage processingsystemis
simplicity. Asimplemeansofexpressing
interactions
between imagestranslatesintosimpleralgorithms and
implementations.
To
keep
thesystemsimple, thenumber of objects manipulated mustbekepttoaminimum. Since Finite Homogeneous Image Algebra
(FHIA)
has onlyonedatatype,
theimage,
andtheinteractions between imagesaredefined ina simplemanner,it isa good choiceasthe
basis foranimage processingsystem.
Apossibledisadvantageofusing FHIA isthatitcontains somefundamental differences
comparedtomoretraditionalmethods. In
FHIA,
thedomainsoftheimageareimportant,
aswell astheconcept of undefinedelement,or*
(star).
Thesetwofeaturescauseresults generatedby
anFHIA-basedsystem and atraditionalsystemto
differ,
althoughtheFHIAresultisrigorousmathematically. Traditionalalgorithms oftentake"shortcuts*or simplifications eventhough the
resultsmaysuffer
(for
example,divisionby
zero: FHIAreturnsa*,butmost return ao).Theadvantages ofusing FHIA isthatalogicalmeansof
defining
image interactions isdeveloped
(for
example,whatdoestheaddition oftwo imagesmean?). Thispowerfultoolinturnleadstoalogical definitionofhigher-levelimagemanipulations
(extended
operators,filters). Thisadvantage oftheuse of adefinedmathematicalmodelfor image interactionssuch asFHIA
outweighstheapparentdisadvantage.
Other imagesalgebrassuchasAFATL Image
Algebra,
withits imagesandtemplates,
donothaveasstraightforwardanapproachto
defining
imageinteractions,
asdoesFHIA ThismakesConclusion.
FiniteHomogeneous
Image Algebrawillbeused asthemathematicalfoundation forthis
implementation.
USER
INTERFACE
General. Image processingalgorithmscan bespecifiedin manyways. Two primary
means of expressionhave been developed for
describing
Image Algebra imagemanipulations:block diagramsand mathematicalexpressions.
Block diagrams. Block
diagrams,
suggestedby Dougherty
andGiardina[DoG87a],
area graphical means ofprogramming inwhicheachfunction isrepresented
by
a"blackbox" with aspecified number of
inputs,
outputs and adefinedaction. Figure 3-1 gives an example of ablockdiagram.
structuring
tran h! add r-H
i
domain element
se tran add
range extmax ? dilate
im1
tran add
[image:23.543.50.497.413.585.2]The block diagramconventions are similartothatof a generaldata-flowdiagram. Themain
difference is inthemeansof
displaying
howanactionisimplemented
overthedomainand rangeof an image.
The domain
box
isconnectedtoallthetranboxes aningthat theelements ofthedomainstructurearefed oneatatimeto theinputofthe tran procedure. The highest tran
box receivesthefirstelement, thesecond getsthesecondelement,andso on
(represented
by
the threevertical
dots)
untilthelastelement. Theaction oftherangeboxcan be similarlyinterpreted. Theresultsfromthetranandadd.functionsarecombinedtogetherusingthe
extmaxfunction.
Eachofthefunctionsare
"defined"
by
lower levelsofblockdiagrams,
until,atthelowestlevel,
onlytheFHIA basisoperations(image
add,imagemultiply,etc)are used.Using
theblockdiagram,
theindependentand parallel nature oftheloop
contents standsout,whichisthemajor advantage ofthisvisualtool. Otheradvantages ofblock diagramsareits
visual representation ofdata flow andtheabstraction oftheimplementation fromthedesign
Agraphicaluserinterface isrequiredfortheuse ofblock diagramsas aprogramming
method. Sophisticated hardwareand software would berequiredfor direct entryof adiagram. In
addition, theusermaynotdesignthemost efficient methodof
implementing
analgorithm. Avisuallanguageeditor and compiler/optimizeristhereforerequiredforthisapproach.
Although block diagrams have beenusedtosomedegreeof successin
illustrating
computer
implementation
difficult. Forexample,looping
and control mechanismshavenotbeenconsistently defined.
Alphanumeric expressions. Since FHIAconsistsofmathematicalexpressions
concerning
images,
suchasc=a+b,wherea,band careimages,
itcantranslatewellintoanalphanumericmeansofprogramming. Suchan approach couldbesimplertoimplementthan
using block
diagrams,
becausespecial userinterface hardwarewould notbe required.Sincethesyntax of
describing
image interactions foran alphanumerically-based systemwouldfollowmore
directly
fromtheimagealgebra, thisapproach would require creation of animagealgebra
library
usinga commonprogramminglanguage,
or of a special-purposeprogramming language.
Conclusion. Analphanumericuserinterfacewillbe usedtoimplementimagealgebra.
Block diagramscanhowever beused asasupplementary documentationtool.
IMPLEMENTATION STYLES
Programming Styles. Therearetwomain stylesinwhichthissystem canbe
implemented: theobject-orientedapproachandtheprocedural
(structured)
approach. Thechoice of style willinfluence thearchitectureofthesoftwaresystem.
Procedural approach. Theprocedural approachisthe traditional
"structured"
proceduresthatoperate ondatawiththatdata
(modularity)
ispossibletoa certaindegree usingprocedurallanguages.
Theadvantageofthisapproachisthatit istheonemostwidelyusedatthemoment,and
theone mostfamiliartothepotentialusers ofthesystem. Traditionalgeneral-purpose computer
architecturesandoperatingsystems are also"tuned"tothisstyle ofprogramming
[Str88].
Object-oriented approach. "Object-oriented" referstoenvironments and
programmingtechniques thatsupportdataabstraction,data
hiding,
proceduralmodularityandconcurrence
[Str88a].
Pureobject-oriented systems consist of groupings of"virtual
devices",
calledobjects.thatcan
"communicate"
with each other. Objectsencapsulateconventionaldatastructures and
theroutinesneededtomanipulatethedata. Objectsare organizedintoclasses,ordatatypesof a
similarfunction. Classescanfurtherbe defined intosubclasses. The"actualization"
of an object
iscalled aninstance.
Eachobjectisself-contained,and cannot
directly
accessthedataof otherobjects. Thisrestricted accessisone ofthemajor advantages oftheobject-orientedparadigm,inthat the
implementation detailsoftheobjectare
hidden,
andthepermitted actionswiththedataarewell-definedand strictlycontrolled. Inthissystem,
defining
imagesas objectswould enforcetheFHIAconcept astheimageasthe fundamental unit ofmanipulation,and preventtheuserfrom
dealing
directly
with pixels.The conceptof"messagepassing",used insuch object-orientedlanguagesas
Smalltalk
mathematicalinnature,and severalinvolvetwoimages
(such
asfiltering,
dilation)
toproduceathirdimageasresult.
Themost severedisadvantageofthisapproachistheintendeduser'snon-familiaritywith
object-orientedparadigms
(at
this time). Sincethe targetusershave different computingbackgroundsand skills
(with
somehaving
noformal introductionto programming,structuredorotherwise),use ofthisapproach could compromise one ofthebasic designconsiderations,
simplicity.
Anotherdrawback isthe
difficulty
ofimplementing
an object-oriented approach with aportablelanguage. Theclosesttoa
"portable"
language isC++
[Str88b].
Itcan allowroutineswrittenin ANSI
C,
sincethelatterisa subset ofC++. Specialistobject-orientedprogramminglanguagessuch asSmalltalkwould compromiseportabilityevenfurther.
Many
object-oriented tools and techniques available at the moment are better suitedtoapplications such as model
building,
computer-based simulations and expert systemknowledgerepresentation
[Kos88].
The image processingapplicationstargetedby
thissystemare more of amathematicalnature,andlendthemselvesmoreefficientlyto traditional
data-only
structures.
However,
thepossibilitiesoftreating
imagesas objectsdoesmakeforsimplerprogramdesign.
Conclusion. The ideal implementation methodologywouldbeacombinationofboth
theobject-orientedapproach,forits data
hiding
anddata-based modularity,andtheproceduralapproach,becauseofits
familiarity
to theuser. Itis importantthat theuserbeabletochooseLIBRARY VS. LANGUAGE
Desired characteristics of final system. To implement Finite Homogeneous
Image
Algebra,
thefinalsystem needsthefollowing
characteristics:a. Structures: Sincetheimage isastructureofdata
(the
matrix,andits location inspace,at aminimum),amechanismfor referringto thewhole groupingofdatawith one referenceisrequired. Thissimplifiesthe code, increases readabilityandforcestheusertoreferto the dataat ahigher
level;
b. Procedural Modularity: Ameans ofgrouping proceduresintomodules, either onthebasisoftheirfunctions
("structured
programming")ortheir relationship tothedata("object-oriented
programming")isneededtoorganize thelargenumber offunctionsinthelibrary
intoa manageablesystem;c. Equational expression: Since imagealgebraismathematical,functions
shouldbe implementedas equations
(such
asc = A + b; whereA,Bandcare images).Implementation approach. Therearetwopossibilitiesto implement FHIA: complete
designof anew, FHIA-based
language;
andbuilding
of alibrary
andtoolsusinganexistinglanguage.
The firstalternative would require afullsyntacticalanalysis,as well as construction of a
parser and compiler. Thiscanbequitecomplicated, expensive,andmaynot meetthedesired
systemqualities,especiallysimplicitytothe user,since
they
would havetolearnanotherlanguage.
Portability
canbeanother obstacleto thesuccessful useofa newlanguage. Theadvantage ofthisapproach isthatthe languagecouldincorporatethe"image processor'swayof
thinking",
as someimaging
constructs("repeat
over entireimagedomain")
translateawkwardlyThesecondalternative ofprovidinga
library
of constructsbasedon anexisting languagecouldbesimplerfortheusertolearnand cheapertoimplement. Some languagesprovidetools
toimplementmostor all oftherequiredcharacteristicsforthesystem. Thedisadvantageisthat
not alltoolsmay beavailable or can notbeconstructed.
Conclusion. Thesecondapproach, thatof
building
animaging
library,
istheoneselectedforthis study,mainly because it isthesimpler approach.
SELECTION OF A HOST LANGUAGE
General. Fourcomputerlanguageswere examinedfortheirsuitabilitytohostaFHIA
library:
Pascal, FORTRAN,
CandC++. Thissectiondescribestheadvantagesanddisadvantagesof each.
Pascal. The firstimplementationof
FHIA
called SLIP (Structured Language for ImageProcessing)
wasdonein Pascal[D0S88].
Thisimplementationdidnotusestructures,andtherefore the matrix, its dimensionsandits locationwere passed witheveryprocedurecall,
resulting instatementssuchas:
Add( AR, AT, MA, NA, A,
BR, BT, MB, NB, B,
BR, BT, MB, NB, B) ;
Theproblem withthisapproachisthatthealgorithmflowcanbeobscured
by having
somanyarguments
"cluttering
up"eachprocedurecall. ThesecondincarnationofSLIP
[DGu89]
Useoftherecordtypedefinitionallowstheboundmatrix and
{t,
r, m, n} valuestobepassed around as oneunit. Pascal alsoallows variable matrixsizes,
by
usingpointersandthenewanddispose procedurestoallocate anddeallocatememory.
The
disadvantage
ofPascal isthecallingconvention. Astatementsuch asAdd
(A,
B, B) ;whereaandbare
images,
raisesthe question, whichimage isinput,
and whichisoutput? Inthiscase,a consistent proceduredesigncoulddesignatethelastargumenttoalwaysbethe output,
butwithout such apolicy
(or
correctdocumentation),
errors canbemade.Ifone wantstouse variable-sized matricesformaximum use ofmemory, theonusisonthe
usertodesignatethatvariable names refertopointerstoimagestructures. Theabove call would
then look like:
var
A,B: "
Image; begin
(...)
Add(A, B, B) ;
(...)
end.
Failuretoincludethepointer symbol "
inthedeclarationwould resultin an error. The
syntax couldbe improved
by defining
Addas afunction returninga pointer. Thecallthenbecomes:
B = Add(A,B) ;
which ismuch closerto thedesired format.
ThemaindisadvantagesofPascalarememorymanagementandportability. The latter
problem referstothefactthatnostandard means ofgrouping proceduresintomoduleshas
been
(version 1.00A)
toVAX Pascal. Ateachtransfer(required
touseimagedisplay
routines ontheVAX),
the module headers hadtoberewritten,fromtheTurboto theVAXstyle:Turbo Pascalmoduleheader: unit modulename
(moduleid)
VAX Pascalmoduleheader: module modulename
Inaddition,VAX Pascalproceduresthatcanbecalledfromoutsidethemodule musthave
thedesignation
[global]
.The memorymanagementissue isanother mainproblemwhenusing Pascal. Theonusis
ontheusertoensureimagesare allocated withnewbeforeuse, anddeallocatedwithdispose
whenfinished. Failure to doso makestheavailablememory fill upquickly,and causesthe
proceduretocrash.
By
notusingpointers,anddeclaring
arraystobeof afixed maximalsize,memoryallocation anddeallocation ismore automated
(although
it isa waste ofmemorytouse a64x64elementarraytocontain a3x3matrix).
FORTRAN. Standard FORTRAN-77 hastwomajordrawbacks: lackof a structure
declarationmechanism, and alackof pointers.
Becausethereisno structuredeclarationmechanism,referencetoa procedure mustbe
intheform:
CALL ADD( AR, AT, MA, NA, A, BR, BT, MB, NB, B,
BR, BT, MB, NB, B) ;
VAX
FORTRAN
doescontainastructure mechanism(structure)
whichgreatlysimplifies
implementation.
For example,theabove codefragment
would look like:STRUCTURE
/IMAGE/
UNION
MAP
INTEGER*2 R ! Upper left-hand corner coord (column)
INTEGER*2 T ! Upper left-hand corner coord (row)
INTEGER*2 M ! Number of rows in image
INTEGER*2 N ! Number of columns in image
INTEGER*2 PIXEL(1:128,1:128) ! Image elements END MAP
END UNION
END STRUCTURE
(.. .)
IMAGE A,B
(...)
CALL ADD(A, B, B)
(...)
Thestructure statementisnot yet part ofthestandardFORTRAN.
Theotherdisadvantageof standard FORTRAN isthelackof apointer mechanism. This
meansthatimagesmustbe declaredtobethemaximum allowablesize,before compile
time,
resulting ineither a waste ofspace,or a program abortduetoalackof space.
ANSI C. ANSI C isa standarddefinitionofCthatallowsstructure
declarations,
pointers,andastandardmeans ofgroupingproceduresintomodules. Amajor advantage ofthisversion of
C is itsportability.
Structuresaredeclared
by
using thestructspecifier. The resultingstructurescanbePointerscanbeusedtoprovide arrayswhosesize isnotknownat compiletime. The
mallocand freefunctionsare calledtoallocate anddeallocatememory,howeverthiscreates
thesame problem as mentionedin Pascalabove: theonusisagain ontheusertodecidewhen
animage isneeded. Failuretoproperly initializeanddeallocateanimagecouldhave disastrous
consequences. Another problemwith allocationanddeallocation isthat theseextraneous
statements"clutterup"
theimplementation.
Anotherproblem withpointers,also presentin
Pascal,
is howtoaddress elementspointedto
by
an address whichis itselfan element of a structure. Forexample,aCimplementation of animagestructureis:
typedef int pix; /* PIXEL TYPE */
typedef struct image /* IMAGE STRUCTURE */
{
/* col no of top left-hand corner*/
/* row number of top lh corner */
/* number of rows */
/* number of columns /
/* pixel values */
To findoutthesizeof an
image,
thefollowing
expressionisrequired:{
image* A;
int nbr_of_rows, nbr_of_cols;
nbr_of_rows = A->M;
nbr_of_cols = A->N;
(...)
Accessing
pixelsdirectly
ismorecomplicated:pixell 1 = *(A->pixel + (rownum) + (colnum) ) ;
int R
int T
int M
int N
pix *pixel;
Thesubscriptoperator
[]
cannotbeusedbecausetheelementarraywas notdeclaredwitha rowlength dimension: thecompilerdoesnotknow how
long
a rowis. Macrosorfunctionscanbedesignedtomake accesstoimageelementsmorenatural,especiallytonovice programmers.
The use ofheader filesandfunction prototypes provideaconvenientmeansofgrouping
proceduresintomodules. Functionscan alsobe implementedtoreturn pointersto
images,
so"equational"
procedureformatscanbeused. Theapplication examplesshow several cases of
this typeof expression.
Oneproblem withfunctionsremains:
they
are still an unnaturalwayofformulating
anarithmeticalexpression. Ifaandbare
integers,
is itnot preferabletowrite "b = a+b"
insteadof
"B=add(A,B)
;"?Asimilar argument canbemadefor images.
Defining
operatorsforimagealgebra canbedoneonaUNIXsystem,
by defining
asyntax,andwritinga preprocessorusingutilities such aslex and yacc, buttheimplementation canbequite complicated.
Anotherproblem withfunctioncalls
(also
presentin PascalandFORTRAN),
isthat"natural"
function namessuch as open,close, abs,andmaxcannotbe redefined when applied
toimages. This increasestheprobabilityof user errors.
C++. C++isasupersetoftheC languagethatsupports controlled accesstostructures
("classes").
Another featureofC++thatappliestothisimplementationistheuse ofconstructorsanddestructors.
Aclassisadatastructurethatcontains withinittherelevantfunctions. Inthecaseof a
prototype
declarations
forallfunctions
thatcan accesstheclass. Thismeetsthemodularityrequirementforahost
language,
in thatproceduresareorganizedas afunctionofthedata(class)
on which
they
operate.A featureofclassesistheabilitytocontrol whichparts oftheclass canbeaccessiblefrom
the"outside*. Inaclass
library,
thedataelementsarekept"private",
and are notdirectly
accessiblefrom instancesotherthanitselforthosedeclared "friend". Functionscanbemadeto
insulate theuserfromthedata internals
(setimageLoc
, showimageLoc). This abilitytoforcetheusertoconsiderthedatastructureas awholeisanother ofthedesiredattributes of ahost
language.
Withclasses,operators
(+,
*,=) canbe"overloaded",
orredefined, tohave meaningwhen appliedto new classes. This capabilityallowsthestatement:
B = A + B;
tomean"add image Btoimage Aand returntheresultin B". This abilitytouse equational
expressionsisanotherdesiredattribute of ahost language. Functionssuch asopenandmaxcan
alsobeoverloadedtohavetheirimagealgebrameaningwhen appliedto
images,
and stillkeep
theiroriginaldefinitionwhen appliedtofilestreams
(open)
or numbers(max).
Amajor advantage of
C++,
when comparedtoC,
PascalandFORTRAN,
isthecapabilityto defineconstructorsanddestructorstoallocatememory automaticallywhenavariableis
declared,
andtomarktheallocated memory for disposalwhenthevariableisnolongerneeded.This freestheuserfrommostoftheresponsibility formemorymanagement
(although
theusermustbecareful nottoreferto thevariable outsidethescopeinwhichitwas
declared,
sinceitnoAtthepresent
time,
themajordisadvantage
of C++is itsportability. Therearetwoslightlyincompatibleversionsthatexist ofC++: version 1.2
([Str86])
and version2.0([Gut89],
[Lip89]).
Upwardmigrationoftheclass
library
fromaversion1.2compilertoa version2.0compilershouldnothaveanadverseeffect onthe
library,
althoughthishasnotbeentested becausea version2.0compilerwasnotavailable.
Inaddition,onlya certain number ofoperatorscanbeoverloadedin C++. This isa
problem
because,
forexample, the often used operatorextaddused as:B = extadd(A, B) ;
couldbemoreclearlyexpressed as:
B = A <+> B
Conclusion. C++ appearstobethebestchoicetomeettherequirements of
hosting
aFHIA
library,
having
a well-controlled structuremechanism,a meanstoorganize modules and ameanstoexpressimagealgebra equationsintheirnatural mathematicalform. ItresemblancetoC
will makeitsuse somewhat easier.
GENERAL DESIGN
Thissystem will use analphanumericuser
interface,
basedonFinite HomogeneousImage
Algebra,
to implementaclasslibrary
writtenin C++.The generaldesignofthesystem will consist of.
a class
library
writteninC++,
defining
theimageandthefunctions neededtooperate onit;
andTheC++class
library
willbeimplemented
inamannerthat,
whenappropriate,can allowbothan object-orientedfunctioncallstyle:
a. extend(b) ;
anda moretraditionalfunctioncall style:
extend
(a,
b) ;CHAPTER
4 -IMPLEMENTATION
GENERAL
Chapter
Objective.
Theelementsneededtoimplement Finite Homogeneous ImageAlgebra have been defined ina class
library
calledtheObject Oriented Programming SystemStandard
Library
for Image Processing(oopsSlip).
Theobjective ofthischapteristo describe thefeaturesandimplementationoftheclasslibrary.
oopsSlip User Manual. Thischapter andAppendix C
(Class
FunctionDictionary)
areintendedto beusedtogetherand constitutetheuser manualforthesystem.
Examplesoftheuseoftheclass
library
are givenin Chapter 5.Notation Conventions. Toaid in explainingthe
implementation,
thefollowing
notation conventions are used:
Courier font
IMAGEor IMAGE
PIXorPix
denotespredefined
keywords, identifiers,
or othercomputer-relatedobjects,used
directly ("literally")
inthe system;isa genericimage
type,
anyofthepredefined imageclasses;
FEATURES
General. Thesystem consistsoftheoopsSlipclass
library
andapreprocessor.oopsSlip Class Library. The oopsSlipclass
library
isa set ofthreegroups of classes:a. type classes
(coord,
Byte), whicharederived from the C++fundamentaltypes;
b. image classes
(Bytelmage,
Intlmage, Reallmage,Compleximage),which are imagesthathaveallthesamefunctionsand
methods, butare composed of one ofthefundamentalorderived
types;
andC. imageStructure Classes
(Domain,
ByteRange, IntRange,RealRangeandComplexRange),which are classesderived fromtheimage classes.
Preprocessor. Sixadditional operators are addedtothenormal overloadableC++
operatorset. This istoaccommodatetheextended operators
(extadd,
extmult, extmax,andextmin) andbasicmorphological operators
(dilate
anderode). Apreprocessordecodesthesespecial symbolsinto functioncalls, thencompiles andlinkstheuser program.
DERIVED TYPE CLASSES
General. C++containsfundamentaldatatypessuch as int, float,anddouble. To
accomodatetheimageprocessingalgorithmsintheoopsSlipclass
library,
twoothertypeclassesaredefined: ByteandCoord.
Byte. TheByte isaninteger type that takesuponebyteofspace. Itcan
Coord. This isusedtodenote thecoordinatesof anobject,and isa pair ofintvalues.
Theconventionfor referring toacoordinateis
(row,
column). The onlyoperatorsdefined forCoordare <<,== and !=. Themethodtoreferto
coordinatecomponentsis
(here
isoftypeCoord):
rowComponent = here.row
();
columnComponent = here,col();
or rowComponent = row(here) ; columnComponent = col
(here);
The brackets intheexpressionsareimportant because
they
refertomemberfunctionsoftheclassCoord. Thiswillbe furtherexplainedinthesection on Function
Calling
Syntax.IMAGE CLASSES
Abstract datatype. The"generic"
imageclassisanimplementationoftheconcept of
bound matrix,anmrow
by
Ncolumnmatrix,withthetop
left-handcornerelement at rowtandcolumnrina universalCartesiangrid,asillustratedin figure4-1. The locationof an elementis
referredtoas apixel,and itsvalue, thegrevvalue.
image location
in grid:
row T = 3
column R = -1
grid column numbers
I
i i7 i i i i i
i '
i i i i i
ei
:
:
:
:
1 N 7 ' ?
4 i i
i i i i i
i i
.::::& *
'3-'i''''V-'.'.'.i-V.'.'i'.'-'.'-V-V.', -. -1----i- -!- -+'--t-
-. _ i
6
!
7 p i_|
grid row
!--.-= 6 _ _ _ --2 2-i- -i-i.-.-i l.iV-v-v-".'-'.i-v-ViV.v.y""".
numbers ? -5 i-4 i -i: o;-v-1 y:2V3:-v-4X''5-:
i i i
i i i
.**-i . _ i_ _
r_ __i i
i i
-3' i i i i
-4i i i i i
__JL_J__L_1__I__
1 1 1 1 1
-5i i i i i
i i i i i i L. JL _l
Fig
4-1 Coordinatesofimageoverlaid onCartesiangridFramesof reference. The Cartesiangridisusedtoposition
images,
regions withinan
image,
andimageelementsina universalframeofreference,calledthegrid coordinates. Gridcoordinatesare usedbecauserelative positionofimageregionscanbe important in FHIA A
frameof referencelocalto the
image,
image coordinates,locateselementsby
their(row,
column)coordinates relativetothe
top
left handelementintheimagematrix(being
element(o.o)).
Thisreferenceisusedformanipulationswithin animage.
Element values. Elementsofthebound matrixare eitherdefinedorundefined.
Definedelementscanhaveanyvalueaccording to thedatatype
being
used(double,
int, [image:41.543.89.476.53.380.2]image fromaperiscope,whichcanberound)fit therectangularbound imagematrixdatatype.The
undefinedelementvalue isgiven
by
the constantstar.Image types. The elementsofthebound matrixcanbecomposed of one ofthe
fundamentalorderived types. The designationsandcorrespondingtypesare:
Intlmage correspondsto int;
Reallmage correspondstodouble;
Bytelmage correspondsto Byte;
Complexlmage correspondstocomplex.
All imagetypeshavethesamefunctionsand operatordefinitions.
Null images. Thenullimage isan imagewith0
(zero)
rows and0(zero)
columns. Itcanbe locatedanywhereinthegrid. Itis denoted generically
by
nulliMAGE,which correspondstothe
following
valuesforthefollowing
types:nulllntlmageisusedwith an Intlmage;
nullReallmageisusedwith aReallmage;
nullBytelmageisusedwith aBytelmage;
nullComplexImageisused with a Complexlmage.
IMAGE CLASS OPERATORS
Overloaded C++ operators. Several C++ operatorsare givenspecific meanings
with respecttoimages. Therearetwo typesofoperators:
binary
(operating
ontwoimages)
andUnary
operators.Expressions
withunaryoperatorsgroupright-to-left:
unary-expression:
unary-operator expression
unary-operator: one of
i
180 degree rotation
(-).
Theresult oftheunary-operator on animage isthat the
image isrotated 180 degreesabouttheorigin
(0,0)
oftheglobalCartesiangrid.Complement
(
!).
Theresult oftheunary !operator on animage isthateverydefinedpixel becomesundefined (= star), andeveryundefined pixelisgiventhevalue 1. All
elements outsidetheresulting imageare consideredtohavevalue 1.
Binary
operators. Thebinary
operators, indecreasing
precedence,are:*
multiplytwoimagesor animageand a scalar
/
dividetwoimagesor animageby
a scalar(division
by
zero givesstar) %zerodivide2 imagesor animage
by
a scalar(division
by
zero giveszero)+ addtwo imagesor animageandascalar
subtracttwoimagesor a scalarfromanimage
< isone imagesmallerthan theother > isoneimagelargerthan theother
== isone imageequalto theother != isone imagenot equalto theother
<= isoneimagesmallerorequalthan theother
>= isone imagelargeror equalthantheother
Multiplicative Operators . The multiplicative operators
*,
/and% groupleft-to-right:
multiplicative-expression:
expression * expression
Multiplication
(*).
The *(image
multiply)operatorperforms a multiplication
between corresponding definedelementsofthe
intersecting
parts oftheoperandimages.Thedomainoftheresultistheintersectionofthe two images. Iftheimages donot
intersect,
theresultisa nullimage. Ifone ortheotheror bothofthe
corresponding
elementsisundefined, thecorrespondingelementinthe resultisundefined.
Multiplication
of animageby
a scalaris definedasthemultiplicationof eachdefinedelementoftheoperandimage
by
thatscalar. Multiplication iscommutative.
Division
(/).
The/ (image divide)
operator performs adivisionofthefirstoperandimage
by
thesecond ontheintersecting
domainoftheimages. Ifone ortheotherorbothofthecorrespondingelements onthe intersectionareundefined, theresult isundefined. Ifthe
corresponding elementinthedivisoris 0
(zero)
thentheresultisundefined. Iftheimages donotintersect,
theresultisa nullimage. Divisionof animageby
a scalaris definedasthedivisionofeachdefinedelementoftheimage
by
thatscalar. Divisionby
o(zero)
setsthepixeltostar.Zero-division
(%).
The%(image
zero-divide)operatorperforms a"zero-division",
inthatifthecorrespondingelementinthedivisorisao
(zero),
theresultingpixel issettoo(zero).
If the images donot
intersect,
theresultisanullimage. Zero-divisionof animageby
a scalarisdefined inananalogousmannertodivision.
Additive Operators. Theadditive operators+and
-group left-to-right:
additive-expression:
expression + expression
expression expression
Addition
(+).
The domainoftheresult ofthe+(image
add)operatoronimages isthe intersectionofthedomainsof each oftheoperand images. The resulting greyvalues arethe
orbothare undefined. Ifoneorbothoftheoperandsisanull
image,
theresultisa nullimage.Additionof animagetoascalaris definedastheadditionofthescalartoevery definedelementof
theimage. Addition iscommutative.
Subtraction(-
).
Image Subtraction is defined inan manner analogoustoaddition.
Relational
Operators.
Therelationaloperatorsgroup inthesame manner astheirC++counterparts:
relational-expression:
image-expression
< image-expressionimage-expression
> image-expressionimage-expression
<= image-expressionimage-expression >= image-expression
Theoperators <
(smaller),
>(larger),
<=(smaller
orthe same), >=(larger
orthesame)relatetheextent ofthedomain
(or
size)oftheimages. Theextent ofthedomainof animage,
oritscardinality,isthe number ofdefinedelementsintheimage. Therelational operators yieldthe
constantfalse
(=0)
ifthespecifiedrelationisfalse,
andtrue(=1
)
if it istrue. Anullimage hasacardinalityof0.
Eguality
Operators. The equalityoperatorstestwhether animage isthesame asanother:
equality-expression:
image-expression == image-expression image-expression >.= image-expression
The==
(equal to)
operator returnstrue(=1)
iftheimageheader and imagematrices areAdditional
Image Class Operators(Extended
Operators). Sixadditional(non
C++)
operators are providedinordertoimplementtheextendedoperators andthemorphologicalfunctionsdilateanderode. Inorder of
decreasing
precedence,they
are:[+] dilate [-] erode
<@> extmax
(extended
maximum)< "
> extmin
(extended
minimum)<*> extmult
(extended
multiplication)
<+> extadd
(extended
addition)Theseoperatorshave the highestprecedence,sothat
they
areevaluatedfirst.Evaluationorderis from lefttoright. Thesyntaxis:
extended-arithmetic-expression:
expression <+> expression
expression <*> expression
expression <@> expression
expression <~> expression
Theaction oftheextended arithmetic operatorsisanalogousto thenormal arithmetic
operatorsontheintersectionoftheoperand images. This intermediateresultisextended
by
unioning the remaining domainofthesecondoperandto the result, thenunioningthe remaining
domainofthefirstoperandto theresult. Ifthedomains do not
intersect,
theresultistheunionofthedomains. Ifone ortheotherimage isnullthen theresultisthedomainofthenon-nullimage.
If bothoperands arenull, the resultisa nullimage. Extendedoperationsbetween imagesand
scalars are notdefined. Extendedoperators are not commutative.
Sincetheseare not validC++operators,anyprogramcontaining thesesymbols mustfirst
bepassedthroughapreprocessor. This stepconsistsofrecognizingthesymbols and
replacing
The
advantage ofusing
thesesymbolsinstead
of afunctioncallisthat theseare commonimage operators,and are used atleastasoftenastheimagearithmetic operators such as+,or*. It
can also make anequational expressionmorereadable:
h = a [-] (f <+> g) ;
h = erode
(a,
extadd(f,
g) ) ;are equivalentstatements. The imagearithmeticis highlightedwhen operators are used.
IMAGE CLASS FUNCTIONS
Organization. Thepower oftheoopsSlip
library
residesintheset of morethan 100image processing functionsavailableintheImageclasses. Theseroutines canbesubdividedinto
groupsaccordingto theirfunctions.
The
following
discussion isanoverview oftheprincipalimage functions. A detailed listofthefunctionprototypesisgivenintheheader file listingsofAppendix
B,
and eachis described inthe Function
Dictionary
oftheuser manual atAppendixC.Constructors and destructors. The imageclasseshaveconstructorsand
destructorsthatallocate and deallocatespacefortheimage. Theconstructoriscalled
automatically inC++whenadeclarationismade:
Intlmage iml;
Reallmage im2(0,1,2,3,4.1) ;
Theconstructor statement consistsofthe typename.variable name, anda
groupof
Ptional
initialization
arguments,in parenthesis. Theorder oftheinitializationarguments anddefaultvaluesifnotspecified are:
T row numberof
top
left handcorner ofimage(default
o);
R column number oftop
left handcorner ofimage(default
o); M numberofrowsintheimage(default
o)
-rownumbersgofrom oto m-l; n number of columnsintheimage
(default
o)-columnsgofromo to N-1;
Theconstructor
function
isalso calledwhenassigningoneimagetoanotherduring
declaration:
Intlmage im4 = iml;
Other typesofinitializationarguments,usinga secondimage
(here
calledother), are:Reallmage name
(other,
0) ;setsname'sheaderthesame asother, butwith all definedelements=0
Reallmage name(otherLoc, M, N, 0) ;
setsnametosamelocationasother
(the
coordinate valueotherLoccontains thelocationofother), butwithdimensionsmby
n,and all elements=0.Variablescanbe declaredatanypointin aprogram,but
they
mustbe declared beforethey
areused,and areautomatically deallocatedwhenthevariable passes outof scope.Destructorsareautomaticallycalled
by
the compiler,sothey
are nottobecalledby
theuser.
Self managementfunctions. Accesstoelements oftheimage
(t,
r, m, n, elementarea showsthetotal numberof
defined
and undefined elements card showsthe number ofdefined
elementselem showstheelement valueat acertainlocation
setElem setstheelement valueat acertainlocationtoa certain value setAll sets alltheelementsintheimage toa certain value
loc showstheimage
location
(t
,r)setlmageLoc setstheimage location
(t,r)
numCols showsthe numberofcolumns(n)
numRows showsthenumber of rows(m)
nextElemLoc showsthelocationofthenextdefined elementintheimage
nextElemVal showsthevalue ofthenextdefined elementintheimage
Othermanagementfunctionsare:
print printtheimageas a matrixto thestandard output writelmage writestheimagetoafilestream
readimage readstheimage fromafilestream
Basis functions. Sixoperators aredefinedastheFHIA basis: imageaddition
(+),
imagemultiplication
(*),
image division(/),
extended maximum(extmax),
ninety degreerotation(ninety)
andbasistranslation(tran).
Appendix A describestheformal definitionof each ofthesefunctions.
Inouirv functions. Theseoperatorsreturn a booleanvaluetrue orfalseabout
certain aspects oftheimage:
isComp
image checksiftheimageisacomplementedimage isNulllmage checksiftheimage isnull oremptyisDomainEqualcomparesthedomainsoftwoimages
isHeaderEqualcomparestheheaders
(t,
r, m. n)oftwoimagesArithmetic functions. Thearithmetic operators+, ,*,/,and% aredefinedto
operatebetweentwo
images,
or animageand a scalar. Ifa scalarisone ofthe arguments,it istransformed toanimageofequaldomainastheotherargument, butwith allimageelements equal
to thescalar. Inthis way,theresultof animageoperatedon
by
a scalar resultsinanimageof samedomainastheinput image.
Otherarithmeticfunctionsthatoperatebetweentwoimages:
max findthemaximum valuebetween corresponding elements
min findtheminimum valuebetween corresponding elements
Thereare alsoarithmeticfunctionsthatoperateonlyon oneimage:
sub additiveinverse
(negate
alldefinedelements)abs absolute value alldefined elements
comp complementtheimage
sgr square alldefined elements
sgrt findthesquare root of alldefinedelements
recip reciprocalof alldefinedelements
sin,cos, tan trigonometricfunctionsof alldefinedelements
Structural functions. These functionsperform manipulations onthedomainofthe
image:
flip
flip
theimageovertheoriginwindow restricttheimagetoa certainwindow transpose transpose therows and columns
minbound findtheminimalbound matrix
intersect findthe
intersecting
domain betweentwoimagesninety2 rotateimage 180 degreesabouttheorigin
ninety3 rotateimage270 degreesabouttheorigin
Extended functions. Aset ofextendedfunctionsare provided:
extend imageextension
extmult extendedmultiplication
extmin extendedminimum
extmult extended maximum
Morphological
functions.
The morphologicalfunctions dilate,erode,open,close, and minksub
(Minkowski
subtraction)areimplemented.Binary
operations can alsobeperformedongreyscaleimages
by
using b_dilate, b_erode, bopen,and b_close.Statistical functions. Statisticsontheimagecanbeobtainedwiththe
following
functions:
avg findtheaverage pixel value med findthemedian pixel value
max findthemaximal pixelvalue
min findtheminimum pixel value
sum findthesum ofthepixel values
ssg calculatethesum ofsquares
Theseroutines return a valuetypedaccordingto the typeoftheinput image
(for
example,maxon an intlmage returns anint).
Thresholding functions. Asetof
thresholding
functionsprovidesflexibility
inalgorithmdesign: thresh, threshAbove,threshBelow,threshBelowEqual,
threshBetween,threshDefined.
Higher-level functions. Therearemanyother routinesthatperformhigher level
image manipulations,such as theFourier transform,filter,andhist. The implementationof
FUNCTION
CALLING SYNTAX
Member
function invocation.
Theobject-oriented paradigm assumesthatobjectsactonmessages. ThismechanismissimulatedinC++
by
invoking
memberfunctions(functions
grouped with agivenobject)usingthesyntax
instanceName.functionName(arguments) ;
where:
instanceName isthename of aninstanceoftheobject
functionName isthe name of a memberfunctionofthatinstance
arguments arethearguments passedto thefunction
Forexample, theclassReallmage containsthememberfunctionsninety(),
thresh( ) andextend( ). Iftheinstanceiml of Reallmageiscreated,then thesemember
functionsare calledusingthesyntax:
Reallmage iml; Reallmage im2;
double tVal ;
(...)
iml.ninety() ;
/* "iml, rotate by ninety degrees" */
iml.thresh(tVal) ; /*
"iml, threshold yourself at tVal" */
iml.extend(im2) ; /* "iml, extend yourself by
im2" */
This formoffunction invocationcan alsobeusedinsideexpressions,such as:
for (int i = 0; i < iml.area(); i++) {;}
Functions
canbe"chained",
forexamplethefunction
ninety2 0 isequivalenttochainingtheninety() function:
iml.ninety2 () ; /*
"iml,
rotateby
180 degrees"*/
iml. ninety() .ninety() ; /* "iml, rotate
by
9 0 degrees, then..."//*
...rotate by 90 degrees again" */
Theargumentsin the function
invocation
canbe any data typeor another object
(such
asanother
image).
Friend function
invocation.
Themorefamiliar Cstyle offunction invocation issimulated
by defining
friendfunctions,
wheretheargument objectshaveaccesstoeach other'smember
functions.
Using
this syntax, theabove examples wouldread:Reallmage iml;
Reallmage im2;
double tVal;
(...)
ninety(iml); /* "rotate iml
by ninety degrees" */
thresh(iml,tVal) ; /* "threshold iml at tVal" /
iml = extend
(iml,
im2) ; /* "extend iml
by
im2" */for (int i = 0; i < area(iml); i++) {;}
IMAGE STRUCTURE
CLASSESDomain class. TheDomainclass contains an orderedlistofcoordinates ofthedefined
elementsinanimage. The imagetraversalorderis from lefttoright
(increasing
gridcolumnnumber),
top
tobottom(decreasing
grid row number).separately. Acomparisonoftheuse ofthisclassis
illustrated
intheimplementationof grey-scaledilation,
givenin Chapter 5(Application Examples).
Thisexample showsthatextractingtheDomainin its entirety beforeuse wastesmemory,
processing time,
cluttersthealgorithm andaddsanotherdata typetothesystemthatdoesnot
necessarily
addto thefunctionality. Theequivalentfunctionsadhere better totheobject-oriented paradigmthattheimagecontains all"it
needstoknowabout
itself.
It isalsothereasonfor selecting FHIAas atheoreticalbasis: onlyonedatatypeis necessarytoperformallimagecomputations.
TheDomainclassis included in this
implementation
asfor compatibilitywith imageprocessingalgorithmsdescribed in
[DoG87a]
andother sources.The onlyroutines availablefortheDomainclassis:
showDomElem show a particularDomainelement
The domain isextractedusingtheextract Domain() functionofthe
image,
anditssizeisgiven
by finding
the number ofdefinedelements(card)
oftheimage.Range classes. TheRangeclasses are an ordered listofthedefinedelementsofthe
image. Orderofimagetraversal isthesame asforDomain,sothe ithelement ofaRangeclass
correspondstothe ithelement oftheDomainclass extractedfromthesameimage.
There isaRangeclasscorresponding toeachtypeofimage:
intRange correspondstoIntlmage;
RealRange correspondstoReallmage ;
ByteRange correspondsto Bytelmage;
The utilityoftheRange classeshasalsobeensuperseded
by
theimplementationoftheimageclass,forthesamereasons astheDomain class above. The implementationofdilation in
chapter5 illustrates this. Note thatneithertheDomain or Range classeswere usedin any
implementation intheoopsSlipclasslibrary.
The only operatordefined fortheRange classesis:
showRngElem showa particular Range element
The domain isextractedusing theextractRange() functionofthe
image,
anditssize isgiven
by finding
thenumberofdefinedelements(card)
oftheimage.FOR_DOMAIN_OF CONSTRUCT
Purpose. Thepurpose ofthe for_domain_of 0 constructisto implementtheimage
processingparadigm of
"processing
overthedomainof animage". Forexample,inconvolution,oneimage istranslatedover another
by doing
atranoftheorigin ofthefirst imageovereverydefined pixelofthesecond. Ateachtran,an operation isperformed.
Syntax. Theconstruct syntax resemblesthe for0do/endforof
FORTRAN:
for_domain_of (img)
{
statement
Theconstructis implementedasthemacro:
{Coord here = img.nextElemLoc () ;
for (int i=0; <img.card() ; i++, here=i.mg.nextElemLoc(here) )
Insidethe for_domain_of()
loop,
therearetwovariablesthatareautomatically defined:here isthegrid coordinates ofthedefinedelementpresently
being
operatedon; i isa counterfrom 0to thenumber ofdefinedelements.Thescope ofthesevariablesislocalto the
loop,
sotheconstructs canbenested(this
isthereasonforthe"{"
beforethedeclarationofhere.
Theconstruct mustbeterminatedwith eithertheend_f or0 statement
(img
isoptional),or a second"}".
Forexample, tosetallthedefinedelements of an imageto theirnegative value
(the
implementationofinv):
for_domain_of ( (*this) ) {
setElem(here, -elem(here) ) ;
}
end_for() ;Figure
Related documents