• No results found

Expressing imaging algorithms using a C++ based image algebra programming environment

N/A
N/A
Protected

Academic year: 2019

Share "Expressing imaging algorithms using a C++ based image algebra programming environment"

Copied!
172
0
0

Loading.... (view fulltext now)

Full text

(1)

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

[email protected]

.

Recommended Citation

(2)

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~

_

(3)

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

(4)

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.

(5)

EXPRESSING IMAGING ALGORITHMS USING

A

C++

BASED

IMAGE ALGEBRA PROGRAMMING

ENVIRONMENT

by

Davender Nath Gupta

Submittedto the Center for

Imaging

Science in partialfulfillmentoftherequirements

forthedegreeofMasterofScience

atthe Rochester Instituteof

Technology

ABSTRACT

Homogeneous Image Algebra isused asthebasis foranimage processingenvironment

thatusesthe

image,

insteadofthepixel, asthefundamentalunit

being

manipulated. The

object-orientedlanguageC++isusedtoimplementtheenvironment. Examplesofapplications arethat

include

filtering,

regiongrowing, skeletonization,Fourier TransformsandHadamard transforms

are presented. ThisthesisconcludesthatC++does haveseveralfeatureswhichareof great

(6)

ACKNOWLEDGEMENTS

Thisworkhas beenmade possiblethrough thesupport oftheCanadian Forces.

Iwishto thankDr. Edward

Dougherty,

whofirstsuggested mythesistopic. Workonthis

problem allowed metobecomecomfortablein

Pascal, C,

and

C++,

as well aswith

UNIX,

thus

keeping

mycomputer skillsuptodate

(and

givingmetwoexcusestogotoLA!).

I also wishtoacknowledgethevaluable assistance ofthedepartmentofComputer

Scienceand Information

Technology

at

RIT,

andspecifically Dr. Peter

Anderson,

whoprovided
(7)

DEDICATION

(8)

TABLE

OF CONTENTS

TABLE 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 6

Procedural 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

(9)

Notation Conventions 1

FEATURES 2

General 2

oopsSlip Class

Library

2

Preprocessor 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 5

180 degreerotation

(-)

6

Complement

(!)

6

Binary

operators 6

Multiplicative Operators 6

Multiplication

(*)

6

Division

(/)

7

Zero-division

(%)

7

Additive Operators 7

Addition

(+)

7

Subtraction

(-)

7

Relational Operators 8

Equality

Operators 8

Additional Image Class Operators (Extended

Operators)

8

IMAGECLASS FUNCTIONS 1 0

Organization 1 0

Constructors and destructors 1 0

Self managementfunctions 1 1

Basis functions 1 2

Inquiry

functions 1 2

Arithmetic functions 1 2

Structural functions 1 3

Extended functions 1 3

Morphological functions 13

Statistical functions 1 3

Thresholding

functions 14

Higher-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 9

SOURCE FILE ORGANIZATION 1 9

General 2 0

Header Files 2 0

Source files 20

(10)

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

1

Simplicity

1

Efficiency

and Performance 2

BUT 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

(11)

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

(12)

EXPRESSING IMAGING ALGORITHMS

USING A C++ BASED

IMAGE

ALGEBRA PROGRAMMING

ENVIRONMENT

CHAPTER 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 beenproposedto

completely describe image interactions. The noteworthyapproaches usetheconcept ofthe Imageasthefundamental unitofmanipulation. The definitionofImage may vary between

algebras,butis generallymeanttoencompassthe totalnumber of pictureelements,orpixels, as

(13)

Problem. Fewpractical

implementations

have beenmadeofimagealgebras. Ameans

of

implementing

animagealgebraexpressionusingadedicated languageorenvironmentis
(14)

CHAPTER 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 completetooltodemonstratethe

correctnessof algorithms. Analgebraic mathematical approachtoimage processingoffersmany

ofthesequalities.

Thegoal of animagealgebraistoexpress allimageoperations

hierarchically

froma small

collectionofproven,wellbehavedprimitivebasisoperations. Not only doessuch an algebra

providea sound mathematical

framework,

butitalsolaysthefoundation for languagesand

systems 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 refined

by

GeorgesMatheron

[Mat75]

andJ.P. Serra

[Ser81

]

fortextureanalysisof geologicalformations.

TheworkofMatheronandSerra has been

directly

appliedin an area ofimageanalysis
(15)

involves analyzing imageswith respectto their shapes, notonly intheir

domain,

orextent,butalso

intheirgrey level

(considered

athird dimensionofthedomain). Becauseofitsorigins,it benefits

froma strictermathematicalformulationthanotherimage processingmethodologies,andis

being

usedtoovercomethe

limitations

oftraditionallinearconvolution-type operations.

ThemathematicsofMatheronandSerrawere appliedina systematicwaytoimages

by

twoprimarygroups:

Dougherty

and Giardina

([DoG85], [DoG87b], [DoG88a]),

and Ritterandhis

team

{[RSG85], [RDW87]

and

[RSW87]

).

The heterogeneous

(many-typed)

imagealgebras

developed

by

these twoindependentgroups require several sortsofdatatypes to

fully

describe

imagealgorithms.

Further developmentoftheDougherty/Giardina imagealgebra resulted ina

homogeneousor single-sortedimagealgebra

([Dou89a]

and

[Dou89b]).

Theadvantage ofthis

singledatatypealgebraisthatitcan 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. Threeprincipal

groupshave been workingtoimplementvariationsofMatheronandSerra'swork: Ritterandhis

teamatthe

University

ofFlorida

[RDW87],

Lougheedand

Sternberg

attheEnvironmental

Research InstituteofMichigan

[Ste83]

and

Dougherty

attheMorphological

Imaging

Labofthe
(16)

AFATL Image Algebra. UnderthesponsorshipoftheU.S. Air Force Armament

Technical

Laboratory (AFATL)

andthe Defense Advanced Research Projects

Agency

(DARPA),

a

researchanddevelopmentteamatthe

University

of

Florida, Gainesville,

headed

by

Gerhard

Ritter,

has developeda

heterogeneous

(many-sorted)

imagealgebrabasedonimagesand

templates

[RSG85].

Templatesare a means ofrelatingthedomainoftheinputto thedomainof

theoutput. 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 array

processor, althoughlaterversions run on a general-purpose computer.

C-3PL. Researchgroups atthe

University

ofMichiganandtheEnvironmental Research

InstituteofMichigan

(ERIM),

headed

by Stanley Sternberg

andRobert

Lougheed,

have

developedaparallel 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

thecytocomputeris

directly

basedonthe
(17)

Thissystemwas one ofthefirst to dealwithimagesas a whole

(as

opposedto thepixel

level). The image

being

processed iscalledtheactive

image,

whichismodified

by

probingor

combination withotherimagescalledstructuringelements. Thearchitecture providesfor

manipulationofboth

binary

images,

usingsilhouette

transformations,

and grey-scale

images,

usingumbratransformations.

Thecurrentversion ofthecytocomputer istheCyto-HSS

(Cytocomputer-High

Speed

System) [Lou89].

Theadvantages ofthecytocomputer arethatmorphological operations are executedvery

fast.

However,

sincethearchitectureisunique, theimage processing languagecannotbeused

on other systems. It isalsointended primarily formorphological imageprocessing.

SLIP. Homogeneous Image Algebrawas extendedinto Finite HomogeneousImage

Algebra

(FHIA) by Dougherty

andGiardina

[DoG87b],

which providedabasisforcomputer

implementation.

FHIAis basedontheconceptoftheboundmatrix ofreal values onatwo-dimensional

CartesiangridZx

Z,

Z

being

theset ofintegers. Thematrixhas dimensionsmrows

by

n

columns,anditspositioninthegrid isgiven

by

thecoordinates rowtand columnrofthe

top

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,or
(18)

Theoriginalworkto implement FHIAwasperformed

by

Paramjit

SehdevattheStevens

Instituteof

Technology [D0S88],

andwascalled

Structured Language

for Image

Processing

(SLIP).

Itconsisted of a

library

ofPascalandassembly languagesubroutinesthatexecuted on a

DEC VAXcomputer. Theobjective oftheproject wastoprovideaportablemeansforresearchers

toexperimentwithFHIA.

I haveworked on andimprovedthisimplementation

([DGS89]

and

[GDA90]),

provingthe

concept 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]

are

defining

an object-oriented

imaging

language formathematical morphology. Acommercial parallelprocessingcomputer, the

AIS-5000

by

AppliedIntelligence

Systems,

isalso programmedin Objective-C

[ScW88].

These

approachesdonotappearto be basedon a specific algebraic means ofexpressingalgorithms.

Michael A. JenkinsandJanice I. GlasgowofQueen's

University

at

Kingston,

Ontario have

takenadifferentapproachusingarraytheory,the

'study

ofnested,rectangularly-arranged

collections ofdataobjects"

([JeG89])

asthebasisfortheirNested Interactive

Array

Language

(Nial).

Nialcanbeusedinseveral different programmingstyles

(procedural,

object-oriented, etc.)
(19)

CONCLUSION

Image processingsystemsbasedon acompletemathematicalformulationhave been

designed and built

(Ritter,

Lougheedand Dougherty). Objectorientedtechniquesare

being

exploredfortheirusein imageprocessing.

To

date,

thereappearstohave beenno attempts at

building

animage-as-objectoriented
(20)

CHAPTER 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

morphological

processing),andteaching.

Level of user sophistication. Thecomputer experience of users variesfromnovice

toexpert.

Many

fall intothenovicecategory,and are notfamiliarwith computerinternalsordata

structures. Theuser will be familiarwithatleastone ofthe"fundamental"computerlanguages

(FORTRAN,

Pascal,

C,

etc.). Theuser will alsobe familiarwiththebasicprinciples ofimage

processing.

Hardware and Software. Theequipmentavailable includes

Sun, VAX7VMS,

UNIX/Ultrix,

IBM-PCand Macintoshsystems. Languagesavailable include

FORTRAN,

BASIC,

Pascal,

CandC++. The finalsoftwareshouldbeabletointerfaceas much as possiblewiththese
(21)

DESIGN QUALITIES

Thesystemmust provide animage processingenvironmentthatisportable,simple and

efficient.

Portability

canbeachieved

by

ensuringthat thesystem canfunctionwithout special

hardwareor software. Thisrequirementallowsthesystemtobeused onanygeneral-purpose

computer.

Thesystem shouldbesimpletouse and maintain. There isno provisionforuser

training,

otherthan thedocumentation provided.

Simplicity

encouragesuse,and reduces potential

sources of errors.

Althoughefficiencyiscompromisedtosomedegree

by

theportabilityrequirement, the

system should provideforas

timely

a response as possible.

CHOICE OF MATHEMATICAL BASIS

Severalauthors

([CDM88],

[JeG89])

havenotedtherequirementforanimage processing

languageorsystemtobe builtona soundmathematicalbasis.

Using

mathematical

theory

as a

starting pointforsystemdesignensures a consistent and complete set ofoperators, providesa

mechanismforcorrectnessproofs and eliminates redundant andcontradictory constructions,

(22)

The primaryrequirementofa mathematicalbasis foranimage processingsystemis

simplicity. Asimplemeansofexpressing

interactions

between imagestranslatesintosimpler

algorithms and

implementations.

To

keep

thesystemsimple, thenumber of objects manipulated mustbekepttoa

minimum. Since Finite Homogeneous Image Algebra

(FHIA)

has onlyonedata

type,

the

image,

andtheinteractions between imagesaredefined ina simplemanner,it isa good choiceasthe

basis foranimage processingsystem.

Apossibledisadvantageofusing FHIA isthatitcontains somefundamental differences

comparedtomoretraditionalmethods. In

FHIA,

thedomainsoftheimageare

important,

aswell as

theconcept of undefinedelement,or*

(star).

Thesetwofeaturescauseresults generated

by

an

FHIA-basedsystem and atraditionalsystemto

differ,

althoughtheFHIAresultisrigorous

mathematically. Traditionalalgorithms oftentake"shortcuts*or simplifications eventhough the

resultsmaysuffer

(for

example,division

by

zero: FHIAreturnsa*,butmost return ao).

Theadvantages ofusing FHIA isthatalogicalmeansof

defining

image interactions is

developed

(for

example,whatdoestheaddition oftwo imagesmean?). Thispowerfultoolinturn

leadstoalogical definitionofhigher-levelimagemanipulations

(extended

operators,filters). This

advantage oftheuse of adefinedmathematicalmodelfor image interactionssuch asFHIA

outweighstheapparentdisadvantage.

Other imagesalgebrassuchasAFATL Image

Algebra,

withits imagesand

templates,

do

nothaveasstraightforwardanapproachto

defining

image

interactions,

asdoesFHIA Thismakes
(23)

Conclusion.

Finite

Homogeneous

Image Algebrawillbeused asthemathematical

foundation 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,

suggested

by Dougherty

andGiardina

[DoG87a],

are

a graphical means ofprogramming inwhicheachfunction isrepresented

by

a"blackbox" with a

specified number of

inputs,

outputs and adefinedaction. Figure 3-1 gives an example of ablock

diagram.

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]
(24)

The block diagramconventions are similartothatof a generaldata-flowdiagram. Themain

difference is inthemeansof

displaying

howanactionis

implemented

overthedomainand range

of an image.

The domain

box

isconnectedtoallthetranboxes aningthat theelements ofthe

domainstructurearefed oneatatimeto theinputofthe tran procedure. The highest tran

box receivesthefirstelement, thesecond getsthesecondelement,andso on

(represented

by

the threevertical

dots)

untilthelastelement. Theaction oftherangeboxcan be similarly

interpreted. Theresultsfromthetranandadd.functionsarecombinedtogetherusingthe

extmaxfunction.

Eachofthefunctionsare

"defined"

by

lower levelsofblock

diagrams,

until,atthelowest

level,

onlytheFHIA basisoperations

(image

add,imagemultiply,etc)are used.

Using

theblock

diagram,

theindependentand parallel nature ofthe

loop

contents stands

out,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. A

visuallanguageeditor and compiler/optimizeristhereforerequiredforthisapproach.

Although block diagrams have beenusedtosomedegreeof successin

illustrating

(25)

computer

implementation

difficult. Forexample,

looping

and control mechanismshavenotbeen

consistently defined.

Alphanumeric expressions. Since FHIAconsistsofmathematicalexpressions

concerning

images,

suchasc=a+b,wherea,band care

images,

itcantranslatewellintoan

alphanumericmeansofprogramming. Suchan approach couldbesimplertoimplementthan

using block

diagrams,

becausespecial userinterface hardwarewould notbe required.

Sincethesyntax of

describing

image interactions foran alphanumerically-based system

wouldfollowmore

directly

fromtheimagealgebra, thisapproach would require creation of an

imagealgebra

library

usinga commonprogramming

language,

or of a special-purpose

programming language.

Conclusion. Analphanumericuserinterfacewillbe usedtoimplementimagealgebra.

Block diagramscanhowever beused asasupplementary documentationtool.

IMPLEMENTATION STYLES

Programming Styles. Therearetwomain stylesinwhichthissystem canbe

implemented: theobject-orientedapproachandtheprocedural

(structured)

approach. The

choice of style willinfluence thearchitectureofthesoftwaresystem.

Procedural approach. Theprocedural approachisthe traditional

"structured"

(26)

proceduresthatoperate ondatawiththatdata

(modularity)

ispossibletoa certaindegree using

procedurallanguages.

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,

proceduralmodularityand

concurrence

[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. This

restricted accessisone ofthemajor advantages oftheobject-orientedparadigm,inthat the

implementation detailsoftheobjectare

hidden,

andthepermitted actionswiththedataare

well-definedand strictlycontrolled. Inthissystem,

defining

imagesas objectswould enforcetheFHIA

concept astheimageasthe fundamental unit ofmanipulation,and preventtheuserfrom

dealing

directly

with pixels.

The conceptof"messagepassing",used insuch object-orientedlanguagesas

Smalltalk

(27)

mathematicalinnature,and severalinvolvetwoimages

(such

as

filtering,

dilation)

toproducea

thirdimageasresult.

Themost severedisadvantageofthisapproachistheintendeduser'snon-familiaritywith

object-orientedparadigms

(at

this time). Sincethe targetusershave different computing

backgroundsand skills

(with

some

having

noformal introductionto programming,structuredor

otherwise),use ofthisapproach could compromise one ofthebasic designconsiderations,

simplicity.

Anotherdrawback isthe

difficulty

of

implementing

an object-oriented approach with a

portablelanguage. Theclosesttoa

"portable"

language isC++

[Str88b].

Itcan allowroutines

writtenin ANSI

C,

sincethelatterisa subset ofC++. Specialistobject-orientedprogramming

languagessuch asSmalltalkwould compromiseportabilityevenfurther.

Many

object-oriented tools and techniques available at the moment are better suited

toapplications such as model

building,

computer-based simulations and expert system

knowledgerepresentation

[Kos88].

The image processingapplicationstargeted

by

thissystem

are more of amathematicalnature,andlendthemselvesmoreefficientlyto traditional

data-only

structures.

However,

thepossibilitiesof

treating

imagesas objectsdoesmakeforsimplerprogram

design.

Conclusion. The ideal implementation methodologywouldbeacombinationofboth

theobject-orientedapproach,forits data

hiding

anddata-based modularity,andtheprocedural

approach,becauseofits

familiarity

to theuser. Itis importantthat theuserbeabletochoose
(28)

LIBRARY VS. LANGUAGE

Desired characteristics of final system. To implement Finite Homogeneous

Image

Algebra,

thefinalsystem needsthe

following

characteristics:

a. Structures: Sincetheimage isastructureofdata

(the

matrix,and

its 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 offunctionsinthe

library

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;

and

building

of a

library

andtoolsusinganexisting

language.

The firstalternative would require afullsyntacticalanalysis,as well as construction of a

parser and compiler. Thiscanbequitecomplicated, expensive,andmaynot meetthedesired

systemqualities,especiallysimplicitytothe user,since

they

would havetolearnanother

language.

Portability

canbeanother obstacleto thesuccessful useofa newlanguage. The

advantage ofthisapproach isthatthe languagecouldincorporatethe"image processor'swayof

thinking",

as some

imaging

constructs

("repeat

over entireimage

domain")

translateawkwardly
(29)

Thesecondalternative ofprovidinga

library

of constructsbasedon anexisting language

couldbesimplerfortheusertolearnand cheapertoimplement. Some languagesprovidetools

toimplementmostor all oftherequiredcharacteristicsforthesystem. Thedisadvantageisthat

not alltoolsmay beavailable or can notbeconstructed.

Conclusion. Thesecondapproach, thatof

building

an

imaging

library,

istheone

selectedforthis study,mainly because it isthesimpler approach.

SELECTION OF A HOST LANGUAGE

General. Fourcomputerlanguageswere examinedfortheirsuitabilitytohostaFHIA

library:

Pascal, FORTRAN,

CandC++. Thissectiondescribestheadvantagesanddisadvantages

of each.

Pascal. The firstimplementationof

FHIA

called SLIP (Structured Language for Image

Processing)

wasdonein Pascal

[D0S88].

Thisimplementationdidnotusestructures,and

therefore 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

so

manyarguments

"cluttering

up"

eachprocedurecall. ThesecondincarnationofSLIP

[DGu89]

(30)

Useoftherecordtypedefinitionallowstheboundmatrix and

{t,

r, m, n} valuestobe

passed around as oneunit. Pascal alsoallows variable matrixsizes,

by

usingpointersandthenew

anddispose procedurestoallocate anddeallocatememory.

The

disadvantage

ofPascal isthecallingconvention. Astatementsuch as

Add

(A,

B, B) ;

whereaandbare

images,

raisesthe question, whichimage is

input,

and whichisoutput? Inthis

case,a consistent proceduredesigncoulddesignatethelastargumenttoalwaysbethe output,

butwithout such apolicy

(or

correct

documentation),

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. Thecallthen

becomes:

B = Add(A,B) ;

which ismuch closerto thedesired format.

ThemaindisadvantagesofPascalarememorymanagementandportability. The latter

problem referstothefactthatnostandard means ofgrouping proceduresintomoduleshas

been

(31)

(version 1.00A)

toVAX Pascal. Ateachtransfer

(required

touseimage

display

routines onthe

VAX),

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,and

declaring

arraystobeof afixed maximalsize,

memoryallocation anddeallocation ismore automated

(although

it isa waste ofmemorytouse a

64x64elementarraytocontain 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) ;

(32)

VAX

FORTRAN

doescontainastructure mechanism

(structure)

whichgreatly

simplifies

implementation.

For example,theabove code

fragment

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 resultingstructurescanbe
(33)

Pointerscanbeusedtoprovide 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 elements

pointedto

by

an address whichis itselfan element of a structure. Forexample,aC

implementation 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,

the

following

expressionisrequired:

{

image* A;

int nbr_of_rows, nbr_of_cols;

nbr_of_rows = A->M;

nbr_of_cols = A->N;

(...)

Accessing

pixels

directly

ismorecomplicated:

pixell 1 = *(A->pixel + (rownum) + (colnum) ) ;

int R

int T

int M

int N

pix *pixel;

(34)

Thesubscriptoperator

[]

cannotbeusedbecausetheelementarraywas notdeclaredwitha row

length dimension: thecompilerdoesnotknow how

long

a rowis. Macrosorfunctionscanbe

designedtomake 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 unnaturalwayof

formulating

an

arithmeticalexpression. Ifaandbare

integers,

is itnot preferabletowrite "b = a+b

"

insteadof

"B=add(A,B)

;"?

Asimilar argument canbemadefor images.

Defining

operatorsforimagealgebra canbe

doneonaUNIXsystem,

by defining

asyntax,andwritinga preprocessorusingutilities such as

lex and yacc, buttheimplementation canbequite complicated.

Anotherproblem withfunctioncalls

(also

presentin Pascaland

FORTRAN),

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 ofconstructors

anddestructors.

Aclassisadatastructurethatcontains withinittherelevantfunctions. Inthecaseof a

(35)

prototype

declarations

forall

functions

thatcan accesstheclass. Thismeetsthemodularity

requirementforahost

language,

in thatproceduresareorganizedas afunctionofthedata

(class)

on which

they

operate.

A featureofclassesistheabilitytocontrol whichparts oftheclass canbeaccessiblefrom

the"outside*. Inaclass

library,

thedataelementsarekept

"private",

and are not

directly

accessiblefrom instancesotherthanitselforthosedeclared "friend". Functionscanbemadeto

insulate theuserfromthedata internals

(setimageLoc

, showimageLoc). This abilitytoforce

theusertoconsiderthedatastructureas awholeisanother ofthedesiredattributes of ahost

language.

Withclasses,operators

(+,

*,=) canbe

"overloaded",

orredefined, tohave meaning

when 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 still

keep

theiroriginaldefinitionwhen appliedtofilestreams

(open)

or numbers

(max).

Amajor advantage of

C++,

when comparedto

C,

Pascaland

FORTRAN,

isthecapability

to defineconstructorsanddestructorstoallocatememory automaticallywhenavariableis

declared,

andtomarktheallocated memory for disposalwhenthevariableisnolongerneeded.

This freestheuserfrommostoftheresponsibility formemorymanagement

(although

theuser

mustbecareful nottoreferto thevariable outsidethescopeinwhichitwas

declared,

sinceitno
(36)

Atthepresent

time,

themajor

disadvantage

of C++is itsportability. Therearetwoslightly

incompatibleversionsthatexist ofC++: version 1.2

([Str86])

and version2.0

([Gut89],

[Lip89]).

Upwardmigrationoftheclass

library

fromaversion1.2compilertoa version2.0compilershould

nothaveanadverseeffect onthe

library,

althoughthishasnotbeentested becausea version2.0

compilerwasnotavailable.

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

a

FHIA

library,

having

a well-controlled structuremechanism,a meanstoorganize modules and a

meanstoexpressimagealgebra equationsintheirnatural mathematicalform. ItresemblancetoC

will makeitsuse somewhat easier.

GENERAL DESIGN

Thissystem will use analphanumericuser

interface,

basedonFinite Homogeneous

Image

Algebra,

to implementaclass

library

writtenin C++.

The generaldesignofthesystem will consist of.

a class

library

writtenin

C++,

defining

theimageandthefunctions neededtooperate on

it;

and
(37)

TheC++class

library

willbe

implemented

inamanner

that,

whenappropriate,can allow

bothan object-orientedfunctioncallstyle:

a. extend(b) ;

anda moretraditionalfunctioncall style:

extend

(a,

b) ;
(38)

CHAPTER

4 -

IMPLEMENTATION

GENERAL

Chapter

Objective.

Theelementsneededtoimplement Finite Homogeneous Image

Algebra have been defined ina class

library

calledtheObject Oriented Programming System

Standard

Library

for Image Processing

(oopsSlip).

Theobjective ofthischapteristo describe the

featuresandimplementationoftheclasslibrary.

oopsSlip User Manual. Thischapter andAppendix C

(Class

Function

Dictionary)

are

intendedto beusedtogetherand constitutetheuser manualforthesystem.

Examplesoftheuseoftheclass

library

are givenin Chapter 5.

Notation Conventions. Toaid in explainingthe

implementation,

the

following

notation conventions are used:

Courier font

IMAGEor IMAGE

PIXorPix

denotespredefined

keywords, identifiers,

or other

computer-relatedobjects,used

directly ("literally")

inthe system;

isa genericimage

type,

anyofthepredefined image

classes;

(39)

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++fundamental

types;

b. image classes

(Bytelmage,

Intlmage, Reallmage,

Compleximage),which are imagesthathaveallthesamefunctionsand

methods, butare composed of one ofthefundamentalorderived

types;

and

C. imageStructure Classes

(Domain,

ByteRange, IntRange,

RealRangeandComplexRange),which are classesderived fromtheimage classes.

Preprocessor. Sixadditional operators are addedtothenormal overloadableC++

operatorset. This istoaccommodatetheextended operators

(extadd,

extmult, extmax,and

extmin) andbasicmorphological operators

(dilate

anderode). Apreprocessordecodes

thesespecial symbolsinto functioncalls, thencompiles andlinkstheuser program.

DERIVED TYPE CLASSES

General. C++containsfundamentaldatatypessuch as int, float,anddouble. To

accomodatetheimageprocessingalgorithmsintheoopsSlipclass

library,

twoothertypeclasses

aredefined: ByteandCoord.

Byte. TheByte isaninteger type that takesuponebyteofspace. Itcan

(40)

Coord. This isusedtodenote thecoordinatesof anobject,and isa pair ofintvalues.

Theconventionfor referring toacoordinateis

(row,

column). The onlyoperatorsdefined for

Coordare <<,== and !=. Themethodtoreferto

coordinatecomponentsis

(here

isoftype

Coord):

rowComponent = here.row

();

columnComponent = here,col();

or rowComponent = row(here) ; columnComponent = col

(here);

The brackets intheexpressionsareimportant because

they

refertomemberfunctionsof

theclassCoord. Thiswillbe furtherexplainedinthesection on Function

Calling

Syntax.

IMAGE CLASSES

Abstract datatype. The"generic"

imageclassisanimplementationoftheconcept of

bound matrix,anmrow

by

Ncolumnmatrix,withthe

top

left-handcornerelement at rowtand

columnrina universalCartesiangrid,asillustratedin figure4-1. The locationof an elementis

referredtoas apixel,and itsvalue, thegrevvalue.

(41)

image location

in grid:

row T = 3

column R = -1

grid column numbers

I

i i

7 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 onCartesiangrid

Framesof reference. The Cartesiangridisusedtoposition

images,

regions within

an

image,

andimageelementsina universalframeofreference,calledthegrid coordinates. Grid

coordinatesare usedbecauserelative positionofimageregionscanbe important in FHIA A

frameof referencelocalto the

image,

image coordinates,locateselements

by

their

(row,

column)

coordinates relativetothe

top

left handelementintheimagematrix

(being

element

(o.o)).

This

referenceisusedformanipulationswithin animage.

Element values. Elementsofthebound matrixare eitherdefinedorundefined.

Definedelementscanhaveanyvalueaccording to thedatatype

being

used

(double,

int, [image:41.543.89.476.53.380.2]
(42)

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. Itcan

be locatedanywhereinthegrid. Itis denoted generically

by

nulliMAGE,which correspondsto

the

following

valuesforthe

following

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

ontwo

images)

and
(43)

Unary

operators.

Expressions

with

unaryoperatorsgroupright-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 isthatevery

definedpixel becomesundefined (= star), andeveryundefined pixelisgiventhevalue 1. All

elements outsidetheresulting imageare consideredtohavevalue 1.

Binary

operators. The

binary

operators, in

decreasing

precedence,are:

*

multiplytwoimagesor animageand a scalar

/

dividetwoimagesor animage

by

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% group

left-to-right:

multiplicative-expression:

expression * expression

(44)

Multiplication

(*).

The *

(image

multiply)operatorperforms a multiplication

between corresponding definedelementsofthe

intersecting

parts oftheoperandimages.The

domainoftheresultistheintersectionofthe two images. Iftheimages donot

intersect,

theresult

isa nullimage. Ifone ortheotheror bothofthe

corresponding

elementsisundefined, the

correspondingelementinthe resultisundefined.

Multiplication

of animage

by

a scalaris defined

asthemultiplicationof eachdefinedelementoftheoperandimage

by

thatscalar. Multiplication is

commutative.

Division

(/).

The

/ (image divide)

operator performs adivisionofthefirstoperand

image

by

thesecond onthe

intersecting

domainoftheimages. Ifone ortheotherorbothofthe

correspondingelements onthe intersectionareundefined, theresult isundefined. Ifthe

corresponding elementinthedivisoris 0

(zero)

thentheresultisundefined. Iftheimages donot

intersect,

theresultisa nullimage. Divisionof animage

by

a scalaris definedasthedivisionof

eachdefinedelementoftheimage

by

thatscalar. Division

by

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 animage

by

a scalaris

defined inananalogousmannertodivision.

Additive Operators. Theadditive operators+and

-group left-to-right:

additive-expression:

expression + expression

expression expression

Addition

(+).

The domainoftheresult ofthe+

(image

add)operatoronimages is

the intersectionofthedomainsof each oftheoperand images. The resulting greyvalues arethe

(45)

orbothare undefined. Ifoneorbothoftheoperandsisanull

image,

theresultisa nullimage.

Additionof animagetoascalaris definedastheadditionofthescalartoevery definedelementof

theimage. Addition iscommutative.

Subtraction(-

).

Image Subtraction is defined in

an manner analogoustoaddition.

Relational

Operators.

Therelationaloperatorsgroup inthesame manner astheir

C++counterparts:

relational-expression:

image-expression

< image-expression

image-expression

> image-expression

image-expression

<= image-expression

image-expression >= image-expression

Theoperators <

(smaller),

>

(larger),

<=

(smaller

orthe same), >=

(larger

orthesame)relatethe

extent ofthedomain

(or

size)oftheimages. Theextent ofthedomainof an

image,

orits

cardinality,isthe number ofdefinedelementsintheimage. Therelational operators yieldthe

constantfalse

(=0)

ifthespecifiedrelationis

false,

andtrue

(=1

)

if it istrue. Anullimage hasa

cardinalityof0.

Eguality

Operators. The equalityoperatorstestwhether animage isthesame as

another:

equality-expression:

image-expression == image-expression image-expression >.= image-expression

The==

(equal to)

operator returnstrue

(=1)

iftheimageheader and imagematrices are
(46)

Additional

Image Class Operators

(Extended

Operators). Sixadditional

(non

C++)

operators are providedinordertoimplementtheextendedoperators andthemorphological

functionsdilateanderode. 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,

theresultistheunionof

thedomains. 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

(47)

The

advantage of

using

thesesymbols

instead

of afunctioncallisthat theseare common

image 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 100

image processing functionsavailableintheImageclasses. Theseroutines canbesubdividedinto

groupsaccordingto theirfunctions.

The

following

discussion isanoverview oftheprincipalimage functions. A detailed listof

thefunctionprototypesisgivenintheheader file listingsofAppendix

B,

and eachis described in

the 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) ;

(48)

Theconstructor statement consistsofthe typename.variable name, anda

groupof

Ptional

initialization

arguments,in parenthesis. Theorder oftheinitializationarguments and

defaultvaluesifnotspecified are:

T row numberof

top

left handcorner ofimage

(default

o

);

R column number of

top

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 calledwhenassigningoneimagetoanother

during

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), butwithdimensionsm

by

n,and all elements=0.

Variablescanbe declaredatanypointin aprogram,but

they

mustbe declared before

they

areused,and areautomatically deallocatedwhenthevariable passes outof scope.

Destructorsareautomaticallycalled

by

the compiler,so

they

are nottobecalled

by

the

user.

Self managementfunctions. Accesstoelements oftheimage

(t,

r, m, n, element
(49)

area showsthetotal numberof

defined

and undefined elements card showsthe number of

defined

elements

elem 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 of

thesefunctions.

Inouirv functions. Theseoperatorsreturn a booleanvaluetrue orfalseabout

certain aspects oftheimage:

isComp

image checksiftheimageisacomplementedimage isNulllmage checksiftheimage isnull orempty

isDomainEqualcomparesthedomainsoftwoimages

isHeaderEqualcomparestheheaders

(t,

r, m. n)oftwoimages
(50)

Arithmetic functions. Thearithmetic operators+, ,*,/,and% aredefinedto

operatebetweentwo

images,

or animageand a scalar. Ifa scalarisone ofthe arguments,it is

transformed toanimageofequaldomainastheotherargument, butwith allimageelements equal

to thescalar. Inthis way,theresultof animageoperatedon

by

a scalar resultsinanimageof same

domainastheinput 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

theimageovertheorigin

window restricttheimagetoa certainwindow transpose transpose therows and columns

minbound findtheminimalbound matrix

intersect findthe

intersecting

domain betweentwoimages

ninety2 rotateimage 180 degreesabouttheorigin

ninety3 rotateimage270 degreesabouttheorigin

Extended functions. Aset ofextendedfunctionsare provided:

extend imageextension

(51)

extmult extendedmultiplication

extmin extendedminimum

extmult extended maximum

Morphological

functions.

The morphologicalfunctions dilate,erode,open,

close, and minksub

(Minkowski

subtraction)areimplemented.

Binary

operations can alsobe

performedongreyscaleimages

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

functionsprovides

flexibility

in

algorithmdesign: thresh, threshAbove,threshBelow,threshBelowEqual,

threshBetween,threshDefined.

Higher-level functions. Therearemanyother routinesthatperformhigher level

image manipulations,such as theFourier transform,filter,andhist. The implementationof

(52)

FUNCTION

CALLING SYNTAX

Member

function invocation.

Theobject-oriented paradigm assumesthatobjects

actonmessages. 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++) {;}

(53)

Functions

canbe

"chained",

forexamplethe

function

ninety2 0 isequivalentto

chainingtheninety() function:

iml.ninety2 () ; /*

"iml,

rotate

by

180 degrees"

*/

iml. ninety() .ninety() ; /* "iml, rotate

by

9 0 degrees, then..."/

/*

...rotate by 90 degrees again" */

Theargumentsin the function

invocation

canbe any data type

or another object

(such

asanother

image).

Friend function

invocation.

Themorefamiliar Cstyle offunction invocation is

simulated

by defining

friend

functions,

wheretheargument objectshaveaccesstoeach other's

member

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

CLASSES

Domain class. TheDomainclass contains an orderedlistofcoordinates ofthedefined

elementsinanimage. The imagetraversalorderis from lefttoright

(increasing

gridcolumn

number),

top

tobottom

(decreasing

grid row number).
(54)

separately. Acomparisonoftheuse ofthisclassis

illustrated

intheimplementationof grey-scale

dilation,

givenin Chapter 5

(Application Examples).

Thisexample showsthatextractingthe

Domainin its entirety beforeuse wastesmemory,

processing time,

cluttersthealgorithm and

addsanotherdata typetothesystemthatdoesnot

necessarily

addto thefunctionality. The

equivalentfunctionsadhere better totheobject-oriented paradigmthattheimagecontains all"it

needstoknowabout

itself.

It isalsothereasonfor selecting FHIAas atheoreticalbasis: onlyone

datatypeis necessarytoperformallimagecomputations.

TheDomainclassis included in this

implementation

asfor compatibilitywith image

processingalgorithmsdescribed in

[DoG87a]

andother sources.

The onlyroutines availablefortheDomainclassis:

showDomElem show a particularDomainelement

The domain isextractedusingtheextract Domain() functionofthe

image,

anditssize

isgiven

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;

(55)

The utilityoftheRange classeshasalsobeensuperseded

by

theimplementationofthe

imageclass,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 is

given

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 imageoverevery

defined pixelofthesecond. Ateachtran,an operation isperformed.

Syntax. Theconstruct syntax resemblesthe for0do/endforof

FORTRAN:

for_domain_of (img)

{

statement

(56)

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

is

thereasonforthe"{"

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() ;
(57)

Figure

Fig 3-1Example of block diagram (dilation)
Fig 4-1Coordinates of image overlaid on Cartesian grid
Fig 5-1Example of block diagram (dilation)
Fig 5-2Implementation of Dilate using Domain and Range
+7

References

Related documents