INTERNATIONAL STUDENT EDITION
Imaga ProcBssillJ, AnalYsis, and Machina Vision Milan Sonka The University of Iowa, Iowa City Vaclav Hlavac Czech Technical University, Prague Roger Boyle University of Leeds, Leeds
•
THOMSON
Australia
Canada
Mexico
Singapore
Spain
United
Kingdom
United States
•
THOIVISON
Image Processing. Analysis. and Machine Vision. International Student Edition
by Milan Sonka, Vaclav Hlavac, Roger Boyle General Manager:
Production Manager:
Compositor:
Chris Carson
Renate McCloy
Vit Zyka
Developmental Editor:
Interior Design:
Printer:
Hilda Gowans
Vit Zyka
ThomsonlWest
Permissions Coordinator:
Cover Design:
Vicki Gould
Andrew Adams
©
COPYRIGHT
2008 by Thomson
Learning, part of the Thomson Corporation Printed and bound in the United States of America 1
2
3
4
10
09
08
07
For more information contact Thomson Learning, 1120 8irchmount Road, Toronto, Ontario, M1 K 5G4. Or you can visit our Internet site at http://www.thomsonlearning.com Library of Congress Control Number 2007921909 ISBN: 10: 0-495-24438-4 ISBN: 13: 978-0-495-24428-7
ALL RIGHTS RESERVED. No part of
North America
this work covered by the copyright
Thomson Learning
herein may be reproduced,
1120 Birchmount Road
transcribed. or used in any form or
Toronto, Ontario M1K 5G4
by any means-graphic, electronic,
Canada
or mechanical, including photocopying, recording, taping, Web distribution, or information storage and retrieval systems without the written permission of the publisher. For permission to use material from this text or product, submit a request online at www.thomsonrights.com Every effort has been made to trace ownership of all copyrighted material and to secure permission from copyright holders. In the event of any question arising as to the use of any material, we will be pleased to make the necessary corrections in future printings.
Asia
Thomson Learning 5 Shenton Way #01-01 UIC 8uilding Singapore 068808 Australia/New Zealand
Thomson Learning 102 Dodds Street South bank, Victoria Australia 3006 Europe/Middle East/Africa
Thomson Learning High Holborn House SO/51 Bedford Row London WCIR 4LR United Kingdom Latin America
Thomson Learning Seneca, 53 Colonia Polanco 11560 Mexico D.F. Mexico Spain
Paraninfo Calle/ Magallanes, 25 28015 Mad r id, Spain
A bbreviations
1D 2D, 3D, . . . AAM AI ASM B-rep BBN CAD CCD CONDENSATION CSG CT dB DCT dof DWF ECG EEG EM FFT FOE GA GB GMM GVF HMM ICA IRS JPEG Kb KB Mb MB MDL MR
one dimension ( al ) two dimension ( al ) , three dimension ( al ) , ... active appearance model artificial intelligence active shape model boundary representation Bayesian belief network computer-aided design charge-coupled device CONditional DENSity propagATION constructive solid geometry computed tomography decibel, 20 times the decimal logarithm of a ratio discrete cosine transform degrees of freedom discrete wavelet frame electro-cardiogram electro-encephalogram expectation-maximization fast Fourier transform focus of expansion genetic algorithm Giga byte = 230 bytes = 1,073,741,824 bytes Gaussian mixture model gradient vector flow hidden Markov model independent component analysis intensity, hue, saturation Joint Photographic Experts Group Kilo bit = 210 bits = 1 ,024 bits Kilo byte = 2 1 0 bytes = 1 ,024 bytes Mega bit = 2 20 bits = 1,048,576 bits Mega byte = 2 20 bytes = 1,048,576 bytes minimum description length magnetic resonance
MRI
{LS
ms OCR OS PCA p.d.f. PDM PET PMF RANSAC RGB RCT SNR SVD TV
magnetic resonance imaging microsecond millisecond optical character recognition order statistics principal component analysis probability density function point distribution model positron emission tomography Pollard-Mayhew-Frisby (correspondence algorithm) RANdom SAmple Consensus red, green, blue reversible component transform signal-to-noise ratio singular value decomposition television
arg(x, y) argmax (expr(i) ) i
argmin (expr(i) ) i
div mod round(x) o
AC A c B, B AnB AuB AlB A
x Ixl x·y x Ixl b(x ) �x
af/ax \7f, gradf \7 2f
f*g F. * G
DE D4 Ds
F*
rank(A) T* [; L o
=:;
A
angle (in radians) from x axis to the point (x, y) the value of i that causes expr( i) to be maximal the value of i that causes expr( i) to be minimal
integer division or divergence remainder after integer division largest integer which is not bigger than x + 0.5 empty set complement of set A set A is included in set B intersection between sets A and B union of sets A and B difference between sets A and B (uppercase bold) matrices (lowercase bold) vectors magnitude (or modulus) of vector x scalar product between vectors x and y estimate of the value x absolute value of a scalar Dirac function small finite interval of x, difference partial derivative of the function .f with respect to x gradient of f Laplace operator applied to f convolution between functions f and g elemcnt-by-element of matrices F, G Euclidean distance city block distance chessboard distance complex conjugate of the complex function F rank of a matrix A transformation dual to transformation T, also complex conjugate of T mean value operator linear operator origin of the coordinate system
Sym bols # 13 EB
e
o •
® o 8 1\ V trace cov sec
number of (e.g., pixels) point set symmetrical to point set B morphological dilation morphological erosion morphological opening morphological closing morphological hit-or-miss transformation morphological thinning morphological thickening logical and logical or sum of elements on the matrix main diagonal covariance matrix secant, sec a = 1/ cos a
Contents
list of algorithms
xiv
Preface
xvii
Possible course outlines
xxii
1
Introduction 1.1 1.2 1.3 1.4 1.5
Motivation Why is computer vision difficult? Image representation and image analysis tasks Summary References
2 The image, its representations and properties
2.1 2.2 2.3
2.4
2.5
2.6 2.7
Image representations, a few concepts Image digitization 2.2.1 Sampling 2.2.2 Quantization Digital image properties 2.3.1 Metric and topological properties of digital images 2.3.2 Histograms 2.3.3 Entropy 2.3.4 Visual perception of the image 2.3.5 Image quality 2.3.6 Noise in images Color images 2.4.1 Physics of color 2.4.2 Color perceived by humans 2.4.3 Color spaces 2.4.4 Palette images 2.4.5 Color constancy Cameras: an overview 2.5.1 Photosensitive sensors 2.5.2 A monochromatic camera 2.5.3 A color camera Summary References
1
1 3 5 9 10 11
11 14 14 15 16 17 24 25 25 28 29 31 31 33 37 39 40 41 41 43 45 46 47
Contents
vi 3
The image. its mathematical and physical background 3.1 3.2
3.3 3.4
3.5 3.6 4
Overview 3.1.1 Linearity 3.1.2 The Dirac distribution and convolution Linear integral transforms 3.2.1 Images as linear systems 3.2.2 Introduction to linear integral transforms 3.2.3 1D Fourier transform 3.2.4 2D Fourier transform 3.2.5 Sampling and the Shannon constraint 3.2.6 Discrete cosine transform 3.2.7 Wavelet transform 3.2.8 Eigen-analysis 3.2.9 Singular value decomposition 3.2.10 Principal component analysis 3.2. 11 Other orthogonal image transforms Images as stochastic processes Image formation physics 3.4.1 Images as radiometric measurements 3.4.2 Image capture and geometric optics 3.4.3 Lens abberations and radial distortion 3.4.4 Image capture from a radiometric point of view 3.4.5 Surface refiectance Summary References
Data structures for image analysis 4.1 4.2
4.3
4.4 4.5
Levels of image data representation Traditional image data structures 4.2.1 Matrices 4.2.2 Chains 4.2.3 Topological data structures 4.2.4 Relational structures Hierarchical data structures 4.3.1 Pyramids 4.3.2 Quadtrees 4.3.3 Other pyramidal structures Summary References
5 Image pre-processing 5.1
5.2
Pixel brightness transformations 5.1.1 Position-dependent brightness correction 5 . 1 .2 Gray-scale transformation Geometric transformations 5.2.1 Pixel co-ordinate transformations 5.2.2 Brightness interpolation
49
49 50 50 52 52 53 53 58 61 65 66 72 73 74 77 77 80 81 81 85 87 91 95 96 98
98 99 99 102 104 105 106 106 108 109 1 10
III
113
ll4 l l4 ll5 118 ll9 121
Contents
5.3
5.4
5.5 5.6
Local pre-processing 5.3.1 Image smoothing 5.3.2 Edge detectors 5.3.3 Zero-crossings of the second derivative 5.3.4 Scale in image processing 5.3.5 Canny edge detection 5.3.6 Parametric edge models 5.3.7 Edges in multi-spectral images 5.3.8 Local pre-processing in the frequency domain 5.3.9 Line detection by local pre-processing operators 5.3. 10 Detection of corners ( interest points ) 5.3. 1 1 Detection of maximally stable extremal regions Image restoration 5.4.1 Degradations that are easy to restore 5.4.2 Inverse filtration 5.4.3 Wiener filtration Summary References
6 Segmentation I
6.1
6.2
6.3
6.4 6.5 6.6 6.7
Thresholding 6.1.1 Threshold detection methods 6.1.2 Optimal thresholding 6.1.3 Multi-spectral thresholding Edge-based segmentation 6.2.1 Edge image thresholding 6.2.2 Edge relaxation 6.2.3 Border tracing 6.2.4 Border detection as graph searching 6.2.5 Border detection as dynamic programming 6.2.6 Hough transforms 6.2.7 Border detection using border location information 6.2.8 Region construction from borders Region-based segmentation 6.3.1 Region merging 6.3.2 Region splitting 6.3.3 Splitting and merging 6.3.4 Watershed segmentation 6.3.5 Region growing post-processing Matching 6.4.1 Matching criteria 6.4.2 Control strategies of matching Evaluation issues in segmentation 6.5. 1 Supervised evaluation 6.5.2 Unsupervised evaluation Summary References
vii
123 124 132 138 142 144 147 147 148 154 156 160 162 164 165 165 167 169
175
176 179 180 183 184 185 188 191 1 97 207 212 221 222 223 225 227 229 233 235 237 238 240 241 241 245 246 249
Contents
viii
7 Segmentation II
7.1 7.2
7.3 7.4 7.5 7.6 7.7 7.8 7.9 8
Shape representation and description 8. 1 8.2
8.3
8.4 8.5 8.6 9
Mean Shift Segmentation Active contour models-snakes 7.2. 1 Traditional snakes and balloons 7.2.2 Extensions 7.2.3 Gradient vector flow snakes Geometric deformable models-level sets and geodesic active contours Fuzzy Connectivity Towards 3D graph-based image segmentation 7.5.1 Simultaneous detection of border pairs 7.5.2 Sub-optimal surface detection Graph cut segmentation Optimal single and multiple surface segmentation Summary References Region identification Contour-based shape representation and description 8.2.1 Chain codes 8.2.2 Simple geometric border representation 8.2.3 Fourier transforms of boundaries 8.2.4 Boundary description using segment sequences 8.2.5 B-spline representation 8.2.6 Other contour-based shape description approaches 8.2.7 Shape invariants Region-based shape representation and description 8.3.1 Simple scalar region descriptors 8.3.2 Moments 8.3.3 Convex hull 8.3.4 Graph representation based on region skeleton 8.3.5 Region decomposition 8.3.6 Region neighborhood graphs Shape classes Summary References
257
257 265 265 269 270 275 283 291 292 297 298 306 318 320 328
332 335 335 336 339 341 344 347 347 351 352 357 360 365 368 369 370 371 373
Object recognition
380
9.1 9.2
381 386 387 390 393 396 402 404 405
9.3
Knowledge representation Statistical pattern recognition 9.2.1 Classification principles 9.2.2 Classifier setting 9.2.3 Classifier learning 9.2.4 Support Vector Machines 9.2.5 Cluster analysis Neural nets 9.3.1 Feed-forward networks
Contents
10
ix
9.3.2 Unsupervised learning 9.3.3 Hopfield neural nets 9.4 Syntactic pattern recognition 9.4.1 Grammars and languages 9.4.2 Syntactic analysis, syntactic classifier 9.4.3 Syntactic classifier learning, grammar inference 9.5 Recognition as graph matching 9.5. 1 Isomorphism of graphs and sub-graphs 9.5.2 Similarity of graphs 9.6 Optimization techniques in recognition 9.6 . 1 Genetic algorithms 9.6.2 Simulated annealing 9.7 Fuzzy systems 9.7. 1 Fuzzy sets and fuzzy membership functions 9.7.2 Fuzzy set operators 9.7.3 Fuzzy reasoning 9.7.4 Fuzzy system design and training 9.8 Boosting in pattern recognition 9.9 Summary 9.10 References
407 409 410 412 4 14 417 418 419 423 424 425 427 430 430 433 433 437 438 441 444
Image understanding
450
10.1 Image understanding control strategies 10. 1 . 1 Parallel and serial processing control 10. 1 .2 Hierarchical control 10. 1 .3 Bottom-up control 10.1.4 Model-based control 10.1.5 Combined control 10. 1 .6 Non-hierarchical control 10.2 RANSAC: Fitting via random sample consensus 10.3 Point distribution models 10.4 Active Appearance Models 10.5 Pattern recognition methods in image understanding 10.5.1 Classification-based segmentation 10.5.2 Contextual image classification 10.6 Boosted cascade of classifiers for rapid object detection 10.7 Scene labeling and constraint propagation 10.7.1 Discrete relaxation 10.7.2 Probabilistic relaxation 10.7.3 Searching interpretation trees 10.8 Semantic image segmentation and understanding 10.8.1 Semantic region growing 10.8.2 Genetic image interpretation 10.9 Hidden Markov models 10.9.1 Applications 10.9.2 Coupled HMMs 10.9.3 Bayesian belief networks 10.10 Gaussian mixture models and expectation-maximization
452 452 453 453 454 455 458 461 464 475 486 486 488 492 497 498 500 503 504 506 507 516 522 523 524 526
x
Contents
10. 1 1 Summary 10. 12 References 11 3D
12
vision. geometry
534 537 546
1 1 . 1 3D vision tasks 1 1 . 1 . 1 Marr ' s theory 1 1 . 1.2 Other vision paradigms: Active and purposive vision 1 1 .2 Basics of projective geometry 1 1.2.1 Points and hyperplanes in projective space 1 1 .2.2 Homography 1 1 .2.3 Estimating homography from point correspondences 1 1 .3 A single perspective camera 1 1.3.1 Camera model 1 1 .3.2 Projection and back-projection in homogeneous coordinates 1 1.3.3 Camera calibration from a known scene 1 1.4 Scene reconstruction from multiple views 1 1.4.1 Triangulation 1 1 .4.2 Projective reconstruction 1 1 .4.3 Matching Constraints 1 1 .4.4 Bundle adjustment 1 1 .4.5 Upgrading the projective reconstruction, self-calibration 1 1 .5 Two cameras, stereopsis 1 1 .5.1 Epipolar geometry; fundamental matrix 1 1 .5.2 Relative motion of the camera; essential matrix 1 1.5.3 Decomposing the fundamental matrix to camera matrices 1 1 .5.4 Estimating the fundamental matrix from point correspondences 1 1 .5.5 Rectified configuration of two cameras 1 1 .5.6 Computing rectification 1 1 .6 Three cameras and trifocal tensor 1 1 .6. 1 Stereo correspondence algorithms 1 1 .6.2 Active acquisition of range images 1 1.7 3D information from radiometric measurements 1 1 .7. 1 Shape from shading 1 1 .7.2 Photometric stereo 1 1 .8 Summary 1 1 .9 References
547 549 551 553 553 555 558 561 561 565 565 566 566 568 569 571 571 573 573 575 577 578 579 581 583 584 591 594 595 598 600 601
Use of 3D vision
606
12.1 Shape from X 12. 1 . 1 Shape from motion 12.1.2 Shape from texture 12.1.3 Other shape from X techniques 12.2 Full 3D objects 12.2.1 3D objects, models, and related issues 12.2.2 Line labeling 12.2.3 Volumetric representation, direct measurements 12.2.4 Volumetric modeling strategies 12.2.5 Surface modeling strategies
606 606 613 614 617 617 618 620 622 624
Contents
xi
12.2.6 Registering surface patches and their fusion to get a full 3D model 12.3 3D model-based vision 12.3.1 General considerations 12.3.2 Goad's algorithm 12.3.3 Model-based recognition of curved objects from intensity images 12.3.4 Model-based recognition based on range images 12.4 2D view-based representations of a 3D scene 12.4.1 Viewing space 12.4.2 Multi-view representations and aspect graphs 12.4.3 Geons as a 2D view-based structural representation 12.4.4 Visualizing 3D real-world scenes using stored collections of 2D
626 632 632 633 637 639 639 639 640 641
��
12.5 3D reconstruction from an unorganized set of 2D views-a case study 12.6 Summary 12.7 References 13 Mathematical morphology
13.1 Basic morphological concepts 13.2 Four morphological principles 13.3 Binary dilation and erosion 13.3.1 Dilation 13.3.2 Erosion 13.3.3 Hit-or-miss transformation 13.3.4 Opening and closing 13.4 Gray-scale dilation and erosion 13.4.1 Top surface, umbra, and gray-scale dilation and erosion 13.4.2 Umbra homeomorphism theorem, properties of erosion and dilation, opening and closing 13.4.3 Top hat transformation 13.5 Skeletons and object marking 13.5. 1 Homotopic transformations 1 3.5.2 Skeleton, maximal ball 13.5.3 Thinning, thickening, and homotopic skeleton 13.5.4 Quench function, ultimate erosion 13.5.5 Ultimate erosion and distance functions 13.5.6 Geodesic transformations 13.5.7 Morphological reconstruction 13.6 Granulometry 13.7 Morphological segmentation and watersheds 13.7.1 Particles segmentation, marking, and watersheds 13.7.2 Binary morphological segmentation 13.7.3 Gray-scale segmentation, watersheds 13.8 Summary 13.9 References 14 Image data compression
14.1 Image data properties 14.2 Discrete image transforms in image data compression
M2 646 650 651 657
657 659 661 661 662 665 665 667 667 670 671 672 672 673 675 677 680 681 682 684 687 687 687 689 691 692 694
696 696
xii
Contents
14.3 14.4 14.5 14.6 14.7 14.8 14.9
Predictive compression methods Vector quantization Hierarchical and progressive compression methods Comparison of compression methods Other techniques Coding JPEG and MPEG image compression 14.9.1 JPEG-still image compression 14.9.2 JPEG-2000 compression 14.9.3 MPEG-full-motion video compression 14.10 Summary 14. 1 1 References
700 701 703 704 705 706 707 707 708 711 713 715
15 Texture
718
15.1 Statistical texture description 15.1.1 Methods based on spatial frequencies 15.1.2 Co-occurrence matrices 1 5 . 1 .3 Edge frequency 15. 1.4 Primitive length (run length) 15. 1 .5 Laws' texture energy measures 15.1.6 Fractal texture description 15.1.7 Multiscale texture description-wavelet domain approaches 15.1.8 Other statistical methods of texture description 15.2 Syntactic texture description methods 15.2.1 Shape chain grammars 15.2.2 Graph grammars 15.2.3 Primitive grouping in hierarchical textures 15.3 Hybrid texture description methods 15.4 Texture recognition method applications 15.5 Summary 15.6 References
16 Motion analysis 16.1 Differential motion analysis methods 16.2 Optical flow 16.2.1 Optical flow computation 16.2.2 Global and local optical flow estimation 16.2.3 Combined local-global optical flow estimation 16.2.4 Optical flow in motion analysis 16.3 Analysis based on correspondence of interest points 16.3.1 Detection of interest points 16.3.2 Correspondence of interest points 16.4 Detection of specific motion patterns 16.5 Video tracking 16.5.1 Background modeling 16.5.2 Kernel-based tracking 16.5.3 Object path analysis
721 721 723 725 727 728 728 730 734 736 737 738 740 741 742 743 745
750 753 757 757 760 762 764 767 768 768 771 775 776 780 786
Contents
16.6 Motion models to aid tracking 16.6.1 Kalman filters 16.6.2 Particle filters 16.7 Summary 16.8 References
xiii 791 793 798 803 805
Acknowledgments
811
Index
812
List of algorithm s
2.1 2.2 2.3 4.1 4.2 5.1 5.2 5.3 5.4 5.5 5.6 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 6.9 6.10 6.11 6.12 6.13 6.14 6.15 6.16 6.17 6.18 6.19 6.20 6.21 6.22 6.23 7.1 7.2 7.3
Distance transform Computing the brightness histogram Generation of additive, zero mean Gaussian noise Co-occurrence matrix Cr (z, y) for the relation r' Integral image construction Histogram equalization Smoothing using a rotating mask Efficient median filtering Canny edge detector Harris corner detector Enumeration of Extremal Regions. Basic thresholding Iterative (optimal ) threshold selection Recursive multi-spectral thresholding Non-maximal suppression of directional edge data Hysteresis to filter output of an edge detector Edge relaxation Inner boundary tracing Outer boundary tracing Extended boundary tracing Border tracing in gray-level images A-algorithm graph search Heuristic search for image borders Boundary tracing as dynamic programming Curve detection using the Hough transform Generalized Hough transform Region forming from partial borders Region merging (outline) Region merging via boundary melting Split and merge Split and link to the segmentation tree Single-pass split-and-merge Removal of small image regions Match-based segmentation Mean shift mode detection Mean shift discontinuity preserving filtering Mean shift image segmentation
21 24 29 100 101 117 128 129 146 159 162 176 181 183 185 187 189 192 192 195 197 198 206 210 217 220 222 225 226 230 231 232 237 238 261 263 264
L ist of algorithms
7.4 7.5 7.6 7.7 7.8 7.9 8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 9.10 9.11 9.12 9.13 9.14 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10. 1 1 10.12 10.13 10. 14 10.15 10.16 10.17
Absolute fuzzy connectivity segmentation Fuzzy object extraction Fuzzy object extraction with preset connectedness Graph cut segmentation Optimal surface segmentation Multiple optimal surface segmentation 4-neighborhood and 8-neighborhood region identification Region identification in run length encoded data Quadtree region identification Calculating area in quadtrees Region area calculation from Freeman 4-connectivity chain code representation Region convex hull construction Simple polygon convex hull detection Skeleton by thinning Region graph construction from skeleton Learning and classification based on estimates of probability densities assuming the normal distribution Minimum distance classifier learning and classification Support vector machine learning and classification MacQueen k-means cluster analysis Back-propagation learning Unsupervised learning of the Kohonen feature map Recognition using a Hopfield net Syntactic recognition Graph isomorphism Maximal clique location Genetic algorithm Simulated annealing optimization Fuzzy system design AdaBoost Bottom-up control Coronary border detection---a combined control strategy N on-hierarchical control Random sample consensus for model fitting--RANSAC Approximate alignment of similar training shapes Fitting an ASM AAM construction Active Appearance Model matching Contextual image classification Recursive contextual image classification AdaBoost feature selection and classifier learning Discrete relaxation Probabilistic relaxation Updating a region adjacency graph and dual to merge two regions Semantic region merging Genetic image segmentation and interpretation Gaussian mixture parameters via expectation-maximization
xv 285 286 288 303 307 314 332 333 334 353 353 360 362 365 367 395 396 400 403 407 408 409 411 421 422 427 429 437 439 453 456 459 461 465 470 475 478 490 492 494 500 503 505 506 510 528
xvi 10.18 10. 19 11.1 1 1.2 11.3 12.1 12.2 12.3 15.1 15.2 15.3 15.4 15.5 15.6 16.1 16.2 16.3 16.4 16.5 16.6 16.7
List of a lgorithms
Expectation-maximization ( a generalization of algorithm 10.17) Baum-Welch training for H:MMs ( the forward-backward algorithm) Image rectification PMF stereo correspondence Reconstructing shape from shading Line labeling Iterative closest reciprocal points Goad's matching algorithm Autocorrelation texture description Co-occurrence method of texture description Edge-frequency texture description Primitive-length texture description Shape chain grammar texture synthesis Texture primitive grouping Relaxation computation of optical flow from dynamic image pa.irs Optical flow computation from an image sequence Velocity field computation from two consecutive images Background maintenance by median filtering Background maintenance by Gaussian mixtures Kernel-based object tracking Condensation ( particle filtering)
532 533 582 590 597 619 631 635 721 725 725 728 737 740 759 759 769 776 779 783 800
Preface
Image proce88ing, analY8i8, and machine vi8ion represent an exciting and dynamic part of cognitive and computer science. Following an explosion of interest during the 1970s and the 1980s, the last three decades were characterized by a maturing of the field and significant growth of active applications; remote sensing, technical diagnostics, autonomous vehicle guidance, biomedical imaging (2D, 3D, and 4D) and automatic surveillance are the most rapidly developing areas. This progress can be seen in an increasing number of software and hardware products on the market-as a single example of many, the omnipresence of consumer-level digital cameras is striking. Reflecting this continuing development, the number of digital image processing and machine vision courses offered at universities worldwide is increasing rapidly. There are many texts available in the areas we cover-many of them are referenced somewhere in this book. The subject suffers, however, from a shortage of texts which are 'complete' in the sense that they are accessible to the novice, of use to the educated, and up to date. Here we present the third edition of a text first published in 1 993. We include many of the very rapid developments that have taken and are still taking place, which quickly age some of the very good textbooks produced in the recent past. The target audience spans the range from the undergraduate with negligible experience in the area through to the Master ' s and research student seeking an advanced springboard in a particular topic. Every section of this text has been updated since the second version (particularly with respect to references) . Chapters 2 and 3 were reorganized and enhanced to better present a broad yet not overwhelming foundation, which is used throughout the book. While the second edition published in 1998 provided a comprehensive treatment of 2D image processing and analysis, analysis of volumetric and thus inherently 3D image data has become a necessity. To keep up with the rapidly advancing field, a brand new Chapter 7 covers image segmentation methods and approaches with 3D (or higher dimension) capabilities such as mean shift segmentation, gradient vector flow snakes, level sets, direct graph cut segmentation, and optimal single and multiple surface detection. As a result, the book now has two chapters devoted to segmentation, clearly reflecting the importance of this area. Many other new topics were added throughout the book. Wholly new sections are presented on: support vector classifiers; boosting approaches to pattern recognition; model fitting via random sample consensus; active appearance models; object detection using a boosted cascade of classifiers; coupled hidden Markov models; Bayesian belief networks; Gaussian mixture models; expectation-maximization; JPEG 2000 image compression; multiscale wavelet texture description; detection of specific motion patterns; background modeling for video tracking; kernel-based tracking; and particle filters for motion mod eling. All in all, about 25% of this third edition consists of a newly written material
xviii
Preface
presenting state-of-the-art methods and techniques that have already proven their impor tance in the field. A carefully prepared set of exercises is of great use in assisting the reader in acquiring practical understanding. We have chosen to provide a stand-alone Matlab companion book [Svoboda et al. , 2008J with an accompanying web page ( http: //www.engineering. thomsonlearning.com ) rather than include exercises directly. This companion text contains short-answer questions and problems of varying difficulty, frequently requiring practical usage of computer tools and /or development of application programs. It concentrates on algorithmic aspects; the Matlab programming environment was chosen for this purpose as it allows quick insights and fast prototyping. Many of the algorithms presented here have their counterparts in the exercise companion book. Source code of programs and data used in examples are available on the web page, which will undoubtedly grow with contributions from users. The exercise companion book is intended both for students and teachers. Students can learn from short-answer questions, formulated problems and from programmed examples. They are also likely to use pieces of the code provided in their own programs. Teachers will find the book useful for preparing examples in lectures, and assignments for their students. Our experience is that such material allows the teacher to concentrate a course on ideas and their demonstrations rather than on programming of simple algorithms. Solutions to problems will be available for teachers in the password protected part of the web page. The web page will also carry the official list of errata. The reader is encouraged to check this resource frequently. This book reflects the authors' experience in teaching one- and two-semester under graduate and graduate courses in Digital Image Processing, Digital Image Analysis, Image Understanding, Medical Imaging, Machine Vision, Pattern Recognition, and Intelligent Robotics at their respective institutions. We hope that this combined experience will give a thorough grounding to the beginner and provide material that is advanced enough to allow the more mature student to understand fully the relevant areas of the subject. We acknowledge that in a very short time the more active areas will have moved beyond this text. This book could have been arranged in many ways. It begins with low-level processing and works its way up to higher levels of image interpretation; the authors have chosen this framework because they believe that image understanding originates from a common database of information. The book is formally divided into 1 6 chapters, beginning with low-level processing and working toward higher-level image representation, although this structure will be less apparent after Chapter 12, when we present mathematical morphology, image compression, texture, and motion analysis which are very useful but often special-purpose approaches that may not always be included in the processing chain. Decimal section numbering is used, and equations and figures are numbered within each chapter. Each chapter is supported by an extensive list of references and exercises [ Svoboda et al. , 2008]. A selection of algorithms is summarized formally in a manner that should aid implementation-not all the algorithms discussed are presented in this way (this might have doubled the length of the book) ; we have chosen what we regard as the key, or most useful or illustrative, examples for this treatment. Each chapter further includes a concise Summary section. Chapters present material from an introductory level through to an overview of current work; as such, it is unlikely that the beginner will, at the first reading, expect to absorb all of a given topic. Often it has been necessary to make reference to material
Preface
xix
in later chapters and sections, but when this is done an understanding of material in hand will not depend on an understanding of that which comes later. It is expected that the more advanced student will use the book as a reference text and signpost to current activity in the field-we believe at the time of going to press that the reference list is full in its indication of current directions, but record here our apologies to any work we have overlooked. The serious reader will note that the reference list contains citations of both the classic material that has survived the test of time as well as references that are very recent and represent what the authors consider promising new directions. Of course, before long, more relevant work will have been published that is not listed here. This is a long book and therefore contains material sufficient for much more than one course. Clearly, there are many ways of using it, but for guidance we suggest an ordering that would generate five distinct modules:
Digital Image Processing I, an undergraduate course. Digital Image Processing I I, an undergraduate/graduate course, for which Digital Image Processing I may be regarded as prerequisite.
Computer Vision I, an undergraduate/graduate course, for which Digital Image Process ing I may be regarded as prerequisite.
Computer Vision I I, a graduate course, for which Computer Vision I may be regarded as prerequisite.
Image Analysis and Understanding, a graduate course, for which Computer Vision I may be regarded as prerequisite. The important parts of a course, and necessary prerequisites, will naturally be specified locally; a suggestion for partitioning the contents follows this Preface. Assignments should wherever possible make use of existing software; it is our expe rience that courses of this nature should not be seen as 'programming courses ' , but it is the case that the more direct practical experience the students have of the material discussed, the better is their understanding. Since the first edition was published, an explosion of web-based material has become available, permitting many of the exercises we present to be conducted without the necessity of implementing from scratch-we do not present explicit pointers to Web material, since they evolve so quickly; however, pointers to specific support materials for this book and others may be located via the designated book web page, http://www.engineering.thomsonlearning.com. The book has been prepared using the :f5\1EX text processing system. Its completion would have been impossible without extensive usage of the Internet computer network and electronic mail. We would like to acknowledge the University of Iowa, the Czech Technical University, and the School of Computing at the University of Leeds for providing the environment in which this book was born and re-born. Milan Sonka is Professor of Electrical & Computer Engineering, Ophthalmology & Visual Sciences, and Radiation Oncology at the University of Iowa, Iowa City, Iowa, USA. His research interests include medical image analysis, computer-aided diagnosis, and machine vision. Vaclav Hlavac is Professor of Cybernetics at the Czech Technical University, Prague. His research interests are knowledge-based image analysis, 3D model-based vision and relations between statistical and structural pattern recognition. Roger Boyle is Professor of Computing and Head of the School of Computing at the
xx
Preface
University of Leeds, England, where his research interests /:Ire in low-level vision I:Ind pattern recognition. The first two authors first worked together as faculty membcrs of the Department of Control Engine<)ring, Faculty of Electrical Engineering, Cz{.-'ch Technical University, Prague, Czech Republic from 1983 to 1990, and have been co-operating wit.h the third since 1991. Interestingly ellough, Boyle and Sonka, having collaborated for 15 years over the Internet, had their first face-to-face meeting only very recently, ill the fall of 2006. We are happy to report that this meeting did not spoil their working relat.ionship. All authors have contributed thronghout-the ordering on the cover corresponds to the weight of individual contribution. Any errors of fact are the joillt responsibility of alL For th e first time, the book was not typeset by the authors. Professional help from Dr. Vit Zyka has resulted in a visually pleasing, clean, and well formatted manuscript. Despite long hours, and periods of the-ItS our wives cali it -author's syndrome of limited communication with the outHidc world, we arc already looking fonvard to future editions in which all omissions, typos, an d errors get corrected. Milan Sonka The University of Iowa Iowa City, Iowa, USA
[email protected] http://www .engineering.uiowa.cdll/ ""sonka
Voic!av Hlavac Czech Technical University Pm.que, Czech Republic
[email protected] http://cmp.felk.cvut.cz/....hlavac ..
Roger Boyle University of Leeds Leeds, Unitnl Kingdom
l'
[email protected] http://www.comp.leeds.l:IC.uk/roger/
Preface
xxi
References Svoboda T., Kybic J., and Hlavac
MATLAB Companion.
V. Image Processing, Analysis, and Machine Vision: A 2008.
Thomson Engineering,
Possible course outlines
Here, one possible ordering of the material covered in the five courses proposed in the Preface is given. This should not, of course, be considered the only option-on the contrary, the possibilities for organizing Image Processing and Analysis courses are practically endless. Therefore, what follows shall only be regarded as suggestions, and instructors shall tailor content to fit the assumed knowledge, abilities, and needs of the students enrolled. Figure 1 shows course pre-requisite dependencies of the proposed ordering. Figure 2 shows the mapping between the proposed course outlines and the material covered in the individual chapters and sections. Digital Image
/'
Processing I UG
�
Computer Vision I
Digital Image Processing"
/'
UG/G
UG/G
�
Image Analysis and
Computer Vision"
Understanding
G
Figure
C
=
1:
G
Pre-requisite dependencies of the proposed five courses. DC = undergraduate course,
graduate course.
course
DIPI
chapter 1 2
3
••
4
5
•••
-
CVII
•
•
IAU
•
•
7
.. •• "' .
DIPII CVI
6
•
•
8
9
10
.. - � ..
-
. -
-
11
12
13
...
14
•• •
15
16
•
••
..
Figure 2: Mapping between the proposed course outlines and material covered in individual
chapters and sections. See course outlines for details.
Possible course outlines
xxiii
Digital I mage Processing I ( D I P I ) An undergraduate course.
1 Introduction 2
4 5
6
3
14
The image, its representation and properties 2.1 Image representations 2.2 Image digitization 2.3 Digital image properties Data structures for image analysis Image pre-processing Pixel brightness transformations 5.1 Geometric transformations 5.2 Local pre-processing (except 5.3.6-5.3.7, 5 .3.9, 5.3. 1 0, limited coverage of 5.3 5.3.4, 5.3.5, 5.3.5) Image restoration (except 5.4.3) 5.4 Segmentation 6.1 Thresholding (except 6. 1.3) 6.2 Edge-based segmentation (except 6.2.4, 6.2.5, 6.2.7, 6.2.8) Region growing segmentation (except 6.3.4) 6.3 6.4 Matching Evaluation issues in segmentation 6.5 The image, its mathematical and physical background 3.2 Linear integral transforms (3.2.1-3.2.4, 3.2.6 only) Image data compression (except wavelet compression) Practical image processing projects
Digital I mage Processing I I ( D I P I I ) An undergraduate/graduate course, for which Digital Image Processing I may be regarded as prerequisite.
1 Introduction (brief review) 2
3
5
14 15
The image, its representation and properties 2.4 Color images Cameras 2.5 The image, its mathematical and physical background (except 3.2.8-3.2.10) Image pre-processing 5.3.4 Scale in image processing 5.3.5 Canny edge detection 5.3.6 Parametric edge models 5.3.7 Edges in multi-spectral images 5.3.8 Pre-processing in frequency domain 5.3.9 Line detection 5.3. 1 0 Corner detection 5.3. 1 1 Maximally stable extremal regions 5.4 Image restoration Image compression (14.2, 14.9 only) Texture (15.1.6, 1 5 . 1 .7 only)
xxiv
Possible course outlines
13 Mathematical morphology Practical image processing projects
Computer Vision I (CV I ) An undergraduate/graduate course, for which Digital Image Processing I may be regarded as prerequisite. 1 Introduction (brief review) 2 The image, its representation and properties (brief review) 6 Segmentation I 6.2.4 Border detection as graph searching 6.2.5 Border detection as dynamic programming 6.3.4 Watershed segmentation 7 Segmentation II 7.1 Mean shift segmentation 7.2 Active contour models 8 Shape representation and description 9 Object recognition Knowledge representation 9.1 9.2 Statistical pattern recognition (except 9.2.4) Neural networks 9.3 9.4 Syntactic pattern recognition 10 Image understanding (except 10.4, 10.6, 10.9, 10.10) 15 Texture (except 15.1.6, 15.1.7) Practical computer vision projects
Computer Vision I I (CV I I ) A graduate course, for which Computer Vision I may be regarded as prerequisite. 2 The image, its representation and properties 2.4 Color images Cameras 2.5 3 The image, its mathematical and physical background 3.4 Image formation physics 5 Image pre-processing 5.3.4 Scale in image processing 5.3.5 Canny edge detection 5.3.6 Parametric edge models 5.3.7 Edges in multi-spectral images 5.3.9 Line detection 5.3.10 Corner detection 5.3. 1 1 Maximally stable extremal regions 11 3D Vision, geometry and radiometry 12 Use of 3D vision Practical 3D vision projects
I mage Ana lysis and Understanding ( IAU ) A graduate course, for which Computer Vision
I
Possible course outli nes
lllay be regarded as prerequisite.
7 Segmentation (except 7.1, 7.2) 9 Object recognition 9.2.4 Support vector machines Recognition a s graph matching 9.5 Optimization techniqucs in rccognition 9.6 9.7 Fuzzy systems Booiiting in pattern recognition 9.8 3 The image, itii mathematical and physical backgrollnd (3.2.8-3.2.10 only) 10 Image underiitanding lOA Active appearance models 10.6 Boosted caiicadc of classifiers 10.9 Hidden Markov models 10.10 Gaussian mixture rnodelii and expectation maxilllization 16 Motion analysis Practical image understanding projects
xxv
Chapter
1
I ntroduction
1.1
Motivation
Vision allows humans to perceive and understand the world surrounding them, while computer vision aims to duplicate the effect of human vision by electronically perceiving and understanding an image. Books other than this one would dwell at length 011 this sentence and the meaning of the word 'duplicate'-whether computer vision is simulating or mimicking human systems is philosophical territory, and very fertile territory too. Giving computers the ability to see is not an easy task-we live in a three-dimensional (3D) world, and when computers try to analyze objects in 3D space, the visual sen sors available (e.g., TV cameras) usually give two-dimensional (2D) images, and this projection to a lower number of dimensions incurs an enormous loss of information. Sometimes, equipment will deliver images that arc 3D but this may be of questionable value: analyzing such datasets is clearly more complicated than 2D, and sometimes the 'three-dimensionality' is less than intuitive to us ... terahertz scans are an example of this. Dynamic scenes such as those to which we are accustomed, with moving objects or a moving camera, are increasingly common and represent another way of making computer vision more complicated. Figure 1.1 could be witnessed ill thousands of farmyards in many countries, and serves to illustrate just some of the problems that we will face.
Figure 1.1: A frame from a vidoo of a typical farmyard
scene: the cow is one
of a number waJking naturally from right to left. Courlay of D. R. Magee, Univenitll of Leeth.
2
Chapter 1: Introduction There are many reasons why we might wish to study scenes such as this, which
are attractively simple
to us--thc beast
is moving slowly, it is clearly black and white,
its movement is rhythmic, .... However, automated analysis is very fra.ught; in fact, the animal's boundary is often very difficult to distinguish clearly from the background, the motion of the legs is self occluding and (subtly) the concept of 'cow-shaped' is not something easily encoded. The application from which this picture was takenl made use of many of the algorithms presented in this book: starting at a low level, moving features were identified and grouped.
A
'training phase' taught the system what a cow might look
like in various poses (see Figure derived (see Figure
1.2),
from which a model of a 'moving' cow could be
1.3).
L)pA f; �·'-�I t:::j["."rIfi"I. �� � t('i! rJ. t:::' '1 V'r:i� �;.� � ...rt1'1j t:::..!in� /-)�-Y1 C:::Modd I
All Variation
Front Legs Variation
Rear Legs
Variation
Inter-animal Variation
,Model 2
Model J
1.2: Various models for a cow silhou ette: a straight-line boundary approximation has been learned from training data and is able to adapt to different animals and different forms of occlusion. CQurte.,y of D. R. Magee, University uf Leeds.
Figure
These models could then be fitted to new ('unseen') video sequences. Crudely, at this stage anomalous behavior such as lameness could be detected by the model failing to fit properly, or well. Thus we sec a sequence of operations-image capture, early processing, segmentation, model fitting, motion prediction, qualitative/quantitative conclusion-that is characteristic of image understanding and computer vision problems. Each of these phases (which may not occur sequentially!) may be addressed by a number of algorithms which we shall cover in due course.
IThe application was serious; there is a growing need in modern agriculture for automatic monitoring of animal health, for example to spot lameness. A limping cow is trivial for a human to identify, but it is very challenging to do this automatically [Magee, 20011.
1.2 Why
is computer vision difficult?
3
1.3: Three frames from a cow sequence: notice the model call cope with partial occlusion the animal enters the scellC, and the diffcrent po� exhibito:.-'
Figure
as
Unive"sity of Leed:!.
This example is relatively simple to ()xplaiu, but serves to illustrate that many com puter vision t/.."Chniqtles use the rcsults aud methods of mathematics, pattern recognition, artificial intelligence
(AI),
psycho-physiology. computer science, electronics, and other
scientific disciplines. Why is computer vision hard? As
all exercise,
consider a single gray-scale (monochro
matic) image: put the book down and before proceeding write down a few reasons why you feci automat.ic inspection and analysis of it may be difficult.
1.2
Why is computer vision difficult?
This philosophical question provides some insight into the rather complex landscape of computer vision. It can be answered in many ways: we offer six. Here, we mention the
rea-'ions only briefiy--most of them will be discussed in more detail later in the book.
loss of information in 3D
-0
20 is 11 phenomenon which occurs in typical image capture
devices stich as a camera or an eye. Their geometric properties have been approximated by a pinhole model for centuries (a box with
1\
small hole in it., called in Latin a
'camera obscllra' [dark room] ). This physical model corresponds to a mathematical model of perspective projectiou; Figure
1.4 sunllnari:res tile principle.
The projective
t.ransformatioll maps points along rays but does not preserve angles and collinearity.
-
- - -
- ,.
-
•
o:[
� y
-.- - - - - -
......
.
virtual image
-,
...�
' :
real candle
- - - -
pinhole
-
..... . ....
Figure 1.4: The pinhole model of imagiug geQmetry does lIot distin guish size of objects.
image plane
The main trouble with the pinhole model and
it
as
single available view is that the
projective transformation sees a small objt.'Ct close to the camera in the same way
a big object remote from the camera. In this case, a human needs a 'yardstick' to
4
Chapter 1 : Introduction
guess the actual size of the object which the computer does not have. Recall images of moss or lichen captured together with a penny, a matchbox or a Swiss knife.
Interpretation of image(s) constitutes the principal tool of computer vision to approach problems which humans solve unwittingly. When a human tries to understand an image then previous knowledge and experience is brought to the current observation. Human ability to reason allows representation of long-gathered knowledge, and its use to solve new problems. Artificial intelligence has invested several decades in attempts to endow computers with the capability to understand observations; while progress has been tremendous, the practical ability of a machine to understand observations remains very limited. Attempting to solve related multidisciplinary scientific problems under the name cognitive systems is seen as a key to developing intelligent machines. From the mathematical logic and/or linguistics point of view, interpretation of images can be seen as a mapping interpretation: image data ---> model.
The (logical) model means some specific world in which the observed objects make sense. An example might be, nuclei of cells in a biological sample, rivers in a satellite image, or parts in all industrial process being checked for quality. There may be several interpretations of the same image(s). Introducing interpretation to computer vision allows us to use concepts from mathematical logic, linguistics as syntax (rules describing correctly formed expression) , and semantics (study of meaning) . Considering observations (images) as an instance of formal expressions, semantics studies relations between expressions and their meanings. The interpretation of image(s) in computer vision can be understood as an instance of semantics. Practically, if the image understanding algorithms know into which particular do main (model in logical terminology) the observed world is constrained, then automatic analysis can be used for complicated problems.
Noise is inherently present in each measurement in the real world. Its existence calls for mathematical tools which are able to cope with uncertainty; an example is probability theory. Of course, more complex tools make the image analysis much more complicated compared to standard (deterministic) methods.
Too much data. Images and video sequences are huge. An A4 sheet of paper scanned monochromatically at 300 dots per inch (dpi) at 8 bits per pixel corresponds to 8.5 ME. Non-interlaced RGB 24 bit color video 512 x 768 pixels, 25 frames per second, makes a data stream of 225 Mb per second. If the processing we devise is not very simple, then it is hard to achieve real-time performance; i.e., to process 25 or 30 images per second.
Brightness measured in the image is given by complicated image formation physics. The radiance (� brightness, image intensity) depends on the irradiance (light source type, intensity and position) , the observer's position, the surface local geometry, and the surface reflectance properties. The inverse tasks are ill-posed--for example, to reconstruct local surface orientation from intensity variations. This is the reason why image capturing physics is often avoided in practical attempts aiming at image understanding. Instead, a direct link between the appearance of objects in scenes and their interpretation is sought.
l.3 Image representation and image analysis tasks
5
Local window vs. need for global view.
Commonly, image analysis algorithms analyze a particular storage bin in an operational memory (e.g., a. pixel ill the image) and its local neighborhood; the computer sees the image through a keyhole. Seeing the world through a keyhole makes it very difficult to understand more global context. This problem has a long tradition in artificial intelligence: in the 1980s McCarthy argued that formalizing context was a crucial step toward the solution of the problem of generality. It is often very difficult to interpret an image if it is seen only locally or if only a few local keyholes are available. This can be demonstrated pictorially, see Figure 1.5. How context is taken into account is an important facet of image analysis. Figure 1.5: Illustration of the world
•
1.3
y
•
seen
through several keyholes providing only a very local context. Try to guess what object is depicted in the image. It is tlkely to be very difficult if the whole picture has Hot beell seen yet. The complete image is shown deliberately on a different page, see Figure 1.6.
Image representation and image analysis tasks
Image understanding by a machine can be seen as an attempt to find a relation between input image(s) and previollsly t.'Stablishcd models of the observed world. Transition from the input image(s) to the model reduces the information contained in the image to relevant information for the application domain. This process is usually divided into several steps and 5Cveral levels representing the image are used. The bottom layer contains raw image data and the higher levels interpret the data. Computer vision designs these intermediate representations and algorithms serving to establish and maintain relations between entities within and between layers. Image representation ean be roughly divided according to data organization into four levels, see Figure 1. 7. The boundaries between individual Icvels are inexact, and more detailed divisions are also proposed in the literature. Figure 1.7 suggests a bottom up way of information processing, from signals with almost no abstraction, to the highly abstract description ne€
d in an even simpler way. Two levels are often distinguished: Low-level image processing and high-level image understanding. Low-Ietlel processing methods usually lise very little knowledge about the content of images. In the case of the computer knowing image content, it is usually provided by high level algorithms or directly by a hUIll!).n who understands the problem domain. Low-level methods often include image compression, pre-processing methods for Boise filtering, edge extra<:tion, and image sharpening, all of which we shall discuss in this book. Low-level image processing uses data which resemble the input image; for example, an input image captured by a TV camera is 20 in nature, being described by an image function f (x,y)
6
Chapter 1: Introduction
Figure 1.6: It is easy for Immans to interpret an image if it is seen globally: colnpare to Figure 1.5.
whose value, at simplest, is usually brightness depending on two parameters co-ordinates of the location in the image. If the image is to be processed lISillg a computer it
wil! be digitized
x,
y, the
first, after which it
may be reprcscnted by a rectangular matrix with elements corresponding to the brightness at appropriate image locations. Nowadays, this is llsually
an
over-simplificatioll since the
image will be presented iu color, implying (usually) three channels: red, green and blue. Very often, such a data set wil! be part of a video stream with an
associated
frame rate.
Ncvertheles::;, the raw material will be a set or sequence of matrices which represent the inputs and outputs of low-level image processing.
Hi.Qh-level p11)Cessillg
is bflS(..>(i on knowledge, goals, and plans of how to achieve those
goals, and artificial intelligence methods are widely applicable. High-level computer vision tries to imitate human cognitiolJ (although be mindful of the healt.h waming given in the very first paragraph of this chapter) and the ability to make decisiolls accordilJg to the information contained ill the image. In the example described, high-level knowledge
would be related to the 'shape' of a cow and t.he slIbtle illterrclH.tionships between the different parts of that shape, and their (inter-)dyna.mics. High-level visioll begins with some form of formal model of the world, and then the 'reality' perceived ill the form of digitized images is compared to the Illodel. A match
Understanding objects
•••
From images to features
Image digitizalion
From objects 10 images
Figure 1.7: Four possible levels of image representation suitable for image annlysis problems in which objects have to be de tected and classified. Representations arc depicted as shaded ovab.
1.3 Image representation and image analysis tasks
7
is attempted, and when differellces emerge, partial matches (or sub-goals) are sought that overcome the mismatches; the computer switches to low-level image processing to find information needed to update the model. This process is then repeated iteratively, and 'understanding' an image thereby becomes a co-operation between top-down and bottom-up pl'Ocesses. A feedback loop is introduced ill which high-level partial results create tasks for low-level image processing, and the iterative image understanding process should eventually converge to the global goal. Computer vision is expected to solve very complex tasks, the goal being to obtain similar results to those provided by biological systems. To illustrate the complexity of these tasks, consider Figure
1.8
in which a particular image representation is presented
thc valuc on the vertical axis gives the brightness of its correspondillg location in the [gray-scale] image. Consider what this image might be before looking at Figure
1.9, which
is a rather more common representation of the same image.
Figure
1.8:
An unusual image repre;cuta
tion. Both representations contain exactly the same information, but for a human observer it is very difficult to find a correspondence between them, and without the s€(:ond, it is unlikely that one would recognize the face of a child. The point is that a lot of a priori knowledge is used by humans to interpret the images; the machine only begins with an array of numbers and so will be attempting to make identifications and draw conclusions frolll data that to us are more like Figure
1.8
1.9. Increasingly, data capture not lend themselves to straightforward
than Figure
equipment is providing very large data sets that do
interpretatioll by humans-we have already mentioned terahert� imaging as Internal image representations
are
an
example.
not directly understandable--while the computcr is
able to process loea] parts of the image, it is difficult for it to locate global knowledge. General knowledge, domain-specific knowledge, and information extracted (rom the image will be essential in attempting to 'understand' these arrays of numbers. Low-level computer vision techniques overlap almost completely with digital image processing, which hs.'> beeu practiced for decades. The following sequence of processing steps is commouly seen: An image is captured by a sensor (such as a TV camera) and digitized; then the cOlllputer suppresses noise (image pre-processing) and maybe enhances somc object features whidl are relev-dnt to understanding the image. Edge extraction is all example of processing carried out at this stage. Image segmentation is the next step, in which the computer tries to separate objects from the image background and from each other. Totf\! and partial segmentation may be distinguished: total segmentation is pos.';iblc only for vcry silllple tasks, an example being
8
Chapter L Introduction
Figure 1.9: Another representation of Figure l.8.
the recognition of dark non-touching objects from a light background. For example, in analyzing images of printed text (an early step in optical character recognition, OCR) even this superficially simple problem is very hard to solve without error. In more complicated problems (the general case), low-level image proces.'iing techniques handle the partial segmentation tasks, in which only the cues which will aid further high-level processing are extracted. Often, finding parts of object boundaries is an example of low-level partial segmentation. Object description and classification in a totally segmented image are also understood as part of low-level image processing. Other low-level operations are image compression, and techniques to extract information from (but not
understand)
moving scenes.
Low-level image proce�ing and high-level computer vision differ in the data used. Low-level data are comprised of original images represented by matrices composed of brightness (or similar) values, while high-level data originate in images as well, but only those data which are relevant to high-level goals are extracted, reducing the data quantity considerably. High-level data represent knowledge about the image content.-for example, object size, shape, and mutual rdations between objects in the image. High-level data are usually expressed in symbolic form. Most current low-level image processing methods were proposed in the
19708
or
earlier. Recent research is trying to find more efficient and morc general algorithms and is implemeuting them 011 more technologicaUy sophisticated equipment-in particular, parallel machines are being used to ea..se the enormous computational load of operations
conducted on image data sets. The requirement for better and faster algorithms is fuelled by technology delivering larger images (better spatial resolution), and color. A complicated and so far unsolved problem ill how to order low-level step!; to .solve a specific task, and the aim of automating this problem has not yet been achieved. It is usually still a humall operator who finds a Sl.>quence of relevant operations, and domain specific knowledge and ullcertainty cause much to depend on this operator's intuition and previous experience. High-level vision tries to extract and order image processing steps using all available knowledge--image understanding is the heart of the method, in which feedback from high level to low-level is used. Unsurprisingly this task is very complicated and computationally intensive.
David Marr's book [Marr,
1982], discussed in Section 11.1.1, influenced 1980s; it described a new methodology and computational theory inspired by biological vision systems. Developments in the 1990s computer vision considerably throughout the
moved away from dependence on this paradigm, but interest in properly understanding
1.4 Summary
9
and then modeling human visual (and other perceptual) systems persists-it remains the case that the only known solutioll to the 'vision problem' is our own brain! Let us consider :JD
vision problems
for a moment. We adopt the user's view, Le.,
what tasks performed routinely by humans would be good to accomplish by machines. What is the relation of these level
(image
3D
vision tasks to low-level (image processing) and high
analysis) algorithmic methods? There is no widely accepted view in the
academic community. Links between (algorithmic) components and representation levels
are tailored to the specific application solved, e.g., navigation of an autonomous vehicle.
These applications have to employ specific knowledge about the problem solved to be
competitive with tru;ks which humans solve. More general theories are expected to emerge. Many researchers in different fields work on related problems. There is a belief that research in 'cognitive systems' could be the key which may disentangle the complicated world of perception which includes also computer vision.
Fig. 1.10 depicts several 3D
vision tasks and algorithmic components expressed on
different abstraction levels. In most cases, the bottom-up and top-down approach is adopt.ed to fulfill the task.
(Measuremen0 (ManiPUlatiOn) (RecognitiOn) (Navigation) (Pu uit ) rs
TraCking
)
Image analysis Image processing Figure 1.10:
Sevcral 3D computer vision tasks from the user's poiIlt of view are on the upper line (filled). Algorithmic components OIl different hierarchical levels support it iII a bottom-up fashion.
1.4
Summary
Human vision is natural and seems easy; computer mimicry of this is difficult. 'rVe might hope to examine pictures, or sequences of pictures, for quantitative and qualitative analysis. Many standard and advanced AI te<:hnique; are relevant. •
•
'High' and 'low' levels of computer vision can he ideutified. Processing moves from digital manipulation, through pre-processing, segmentation,
and rccognition to understallding-but these processes may be simultaneous and co-operative. •
An understanding of the notions of heuristiCS, a priori knowledge, syntax, and semantics is necessary.
•
The vision literature is large and growing; books may be specialized, elementary, or advanced.
10 • •
Chapter 1 : I ntroduction
A knowledge of the research literature is necessary to stay up to date with the topic. Developments in electronic publishing and the Internet are making a.ccess to vision simpler.
1.5
References
Magee D. R. Machine Vision Techniq'ues JOT the Evaluation oj Animal Behavio7lT. Ph.D. thesis, University of Leeds, 200l . Marr D. Vision-A Computational Investigation into the Human Representation and Pmcessing oj Visv,al lnJormation. Freeman, San Francisco, 1982 .
Chapter
2
The image, its representations and properties
This Chapter and the next introduce concepts and mathematical tool,; which are widely used in image analysis, and will be used throughout this book. We have separatl.."
It.
mathematical background. Such
a division can never be perfect, and this chapter contains some forward references and dependencies
2.1
011
its succe&"iOr.
Image representations, a few concepts
Mathematical models are often lIsed to describe images <md other signals. A signal is a function depending on !;Orne variable with physical meauing; it can be one-dimensional (e.g., dependent on time) , two-dimensional (e.g., an image dependent on two co-ordinates in a plane), three-dimensional (e.g., describing a volumetric object ill space) , or higher� dimensional. A scalar function might be sufficient to describe a mOllodlromatic image, while vectOr functions are used in image processing to represent, for example, color images collsisting of three component colors. Functions we shall work with may be categorized as continuous,
discrete, or digital.
A continuous function has continuous domain and range; if the domain set is discrete,
then we have a discrete function; if the rallgc set is also discrete, then we have a digital
fUllctioll. Many of these functions will be linear, and correspondingly simple to deal with. We shilll take the usual intuitive definition of image on the human retina,
01'
image-an
example might be the
captured by a TV camera. This can be modeled by
f(x,y) where (x,y) are co-ordinates ill f(x, y, t), where t is time. This model is reasonable
a continuous (image) function of two variables a plane, or perhaps three variables
in the great majority of applications that we encounter in day�to-day life, and which
Chapter 2: The i mage, its representations a nd properties
12
are presented in this book. Nevertheless, it is worth realizing that an 'image' may be acquired in many ways. We shall note often that color is the norm, even when we present algorithms from the point of view of monochromatic images, but we do not need either to constrain ourselves to the visible spectrum. Cameras that operate in the infra-red part of the spectrum are now very common (for example, for night-time surveillance) . Other parts of the electro-magnetic [EM] spectrum may also be used; terahertz imaging, for example, is becoming widely available. Further, image acquisition outside the EM spectrum (that is, 'light') is also common: in the medical domain, datasets are generated via magnetic resonance (MR) , computed tomography (CT) , ultrasound etc. All of these approaches generate large arrays of data requiring analysis and understanding and with increasing frequency these arrays are of 3 or more dimensions. We imply a study of all theHe imaging modalities in the title of this book.
The continuous image function The (gray-scale) image function values correspond to brightness at image points. The function value can express other physical quantities as well (temperature, pressure distribution, distance from the observer, etc.). Brightness integrates different optical quantities--using brightness as a basic quantity allows us to avoid the complicated process of image formation which will be discussed in Section 3.4. The image on the human eye retina or on a TV camera sensor is intrinsically two dimensional (2D ) . We shall call such a 2D image bearing information about brightness points an intensity image. The 2D image on the imaging sensor is commonly the result of projection of a three-dimensional (3D) scene. The simplest lllathematical model for this is a pin-hole camera introduced in Figure 1.4. The 2D intensity image is the result of a perspective projection of the 3D scene, which is modeled by the image captured by a pin-hole camera illustrated in Figure 2.1.1n �
X=[x,y,zj'
y
x
u=[l/, �f
f
y
x
z
image plane
Figure 2 . 1 : Perspective projection geometry.
this figure, the image plane has been reflected with respect to the XY plane in order not to get a mirrored image with negative co-ordinates. The quantities x, y , and z are co-ordinates of the point X in a 3D scene, and f is the distance from the pinhole to the image plane. f is commonly called the focal length because in lenses it has a similar meaning. The lenses approximate the pin-hole camera and are widely used. The projected point u has co-ordinates Cu, 'U) in the 2D image plane, which can easily be derived from
2.1 Image representations, a few concepts
similar triangles v, =
xf z
-
,
'lJ =
yf Z
-
.
13 (2.1)
A non-linear perspective projection is often approximated by a linear parallel (or or thographic) projection, where f -> 00. Implicitly, z -> oc says that the orthographic projection is a limiting case of the perspective projection for faraway objects. When 3D objects are mapped into the camera plane by perspective projection, a lot of information disappears because such a transform is not one-to-one. Recognizing or reconstructing objects in a 3D scene from one image is an ill-posed problem. In due course, in Chapter 1 1 , we shall consider more elaborate representations that attempt to recapture information about the 3D original scene that an image depicts. As may be expected, this is not a simple task and involves intermediate representations that try to establish the depth of points in the image. The aim is to recover a full 3D representation such as may be used in computer graphics-that is, a representation that is independent of the viewpoint, and expressed in the co-ordinate system of the object rather than of the viewer. If such a representation can be recovered, then any intensity image view of the object(s) may be synthesized by standard computer graphics techniques. Recovering information lost by perspective projection is only one, mainly geometric, problem of computer vision--a second problem is understanding image brightness. The only information available in an intensity image is the brightness of the appropriate pixel (picture element, image element), which is dependent on a number of independent factors such as object surface reflectance properties (given by the surface material, microstructure, and marking) , illumination properties, and object surface orientation with respect to a viewer and light source. It is a non-trivial and again ill-posed problem to separate these components when trying to recover the 3D geometry of an object from the intensity image. We will introduce the image formation process in Section 3.4. Some applications work with 2D images directly-for example, an image of a flat specimen viewed by a microscope with transparent illumination, a character drawn on a sheet of paper, the image of a fingerprint, etc. Many basic and useful methods used in digital image analysis do not therefore depend on whether the object was originally 2D or 3D. Much of the material in this book restricts itself to the study of such methods-the problem of 3D understanding is addressed explicitly in Chapters 1 1 and 12. Image processing often deals with static images, in which time t is constant. A mono chromatic static image is represented by a continuous image function f (:r:, y) whose arguments are two co-ordinates in the plane. Most of the images considered in this book will be presented as monochromatic and static, but we will frequently note that they are taken from color or dynamic applications, and the extension of the techniques we will develop will be obvious. Computerized image processing uses digital image functions which are usually rep resented by matrices, so co-ordinates are natural numbers. The domain of the image function is a region R in the plane (2.2) where x m , Yn represent the maximal image co-ordinates. The image function has a limited domain-infinite summation or integration limits can be used, as it is assumed that the image function value is zero outside the domain R. The customary orientation of co-ordinates in an image is in the normal Cartesian fashion (horizontal x-axis, vertical
14
Chapter 2: The i mage. its representations and properties
v-axis, origin bottom-left), although the (row, col umn, origin top-left) orientation used in matrices is also often used in digital image processing. The range of image function values is also limited; by convention, in monochromatic images the lowest value corresponds to black and the highest to white. Brightness values bounded by these limits are gray-levels. The quality of a digital image grows in proportion to the spatial, 8pectral, radiometric, and time resolutions. The spatial resolution is given by the proximity of image samples in the image plane; spectral resolution is given by the bandwidth of the light frequencies captured by the sensor; radiometric resolution corresponds to the number of distinguishable gray-levels; and time resolution is given by the interval between time samples at which images are captured. The question of time resolution is important in dynamic image analysis, where time sequences of images are processed. Images f(x, y) can be treated as deterministic functions or as realizations of stochastic processes. Mathematical tools used in image description have roots in linear system theory, integral transforms, discrete mathematics, and the theory of stochastic processes. Mathematical transforms usually assume that the image function f( x v) is 'well-behaved', meaning that the function is integrable, has an invertible Fourier transform, etc. A comprehensive explanation of the mathematical background useful for representing and treating image functions is given in [Bracewell, 2004; Barrett and Myers, 2004J . ,
2.2
I mage d igitization
An image to be processed by computer must be represented using an appropriate discrete data structure, for example, a matrix. An image captured by a sensor is expressed as a continuous function f(�£ , y) of two co-ordinates in the plane. Image digitization means that the function f (:r, y) is sampled into a matrix with 111 rows and N columns. Image quantization assigns to each continuous sample an integer value-·the continuous range of the image function f (x, y) is split into K intervals. The finer the sampling (i.e., the larger Ai and N ) and quantization (the larger K) , the better the approximation of the continuous image function f(.1: , V ) achieved. Image function sampling poses two questions. First, the sampling period should be determined--this is the distance between two neighboring sampling points in the image. Second, the geometric arrangement of sampling points (sampling grid) should be set.
2.2.1
Sampling
Clearly, there is a relationship between the density of digital sampling and the detail that the image will contain; the theoretical aspects of this (in particular, Shannon's theorem) are given in section 3.2.5 --the reader is strongly encouraged to understand at least the implications of this important result. It is worth glancing ahead to Figure 3 . 1 1 to see a clear illustration of this intuitive issue. For now, it is sufficient to appreciate that if quality comparable to an ordinary television image is required, sampling into a 512 x 512 grid is used (768 x 576 for PAL format and 640 x 480 for NTSC format using a rectangular capture window); this is the reason most image digitizers use this (or higher) resolution. Such a resolution turns out to be adequate for a very wide range of practically useful tasks.
2.2 Image digitization
15
A continuous image is digitized at sampling points. These sampling points arc ordered in the plane, and their geometric relation iH called the grid. The digital image is then a data structure, usually a matrix. Grids used in practice are llsually square (Figure 2.2a) or hexagonal (Figure 2.2b) .
(a)
(b)
Figure 2.2:
(a) Square grid. (b) Hexagonal grid.
It is important to diHtinguish the grid from the raster; the raster is the grid on which a neighborhood relation between points is defined 1 . One infinitely small sampling point in the grid corresponds to one picture element also called a pixel or image element in the digital image; in a three-dimensional image, an image element is called a voxel (volume element) . The set of pixels together covers the entire image; however, the pixel captured by a real digitization device has finite size (since the sampling function is not a collection of ideal Dirac impulses but a collection of limited impulses � see Section 3.2.5) . The pixel is a unit which is not further divisible2 from the image analysis point of view. We shall often refer to a pixel as a 'point'.
2.2.2
Quantization
A value of the sampled image Is (j 6.x, k 6.y) is expressed as a digital value in image processing. The transition between continuous values of the image function (brightness) and its digital equivalent is called quantization. The number of quantization levels Hhould be high enough to permit human perception of fine shading details in the image. IVlost digital image processing devices use quantization into k eqnal intervals. If b bits arc llsed to express the values of the pixel brightness then the number of brightness levels is k = 2 b . Eight bits per pixel per channel (one each for red, greCH, blue) arc commonly used although Hystems using other numbers (4, 6, 12, . . . ) can be found. The main problem in images quantized with insufficient brightness levels is the occurrence of false contours. This effect arises when the number of brightness levels is lower than that which humans can easily distinguish. This number is dependent on many factors-for example, the average local brightness-but displays which avoid this effect will normally provide a range of at least 100 intensity levels. This problem can be reduced when quantization into intervals of unequal length is used; the Hize of intervals corresponding to leHS probable brightnesses in the image is enlarged. These gray-scale transformation techniques are considered in Section 5.1 .2. An efficient computer representation of brightness values in digital images requires that eight bitH, four bits, or one bit are used per pixel, meaning that one, two, or eight pixel brightncHses can be stored in one byte.
I E.g., if 4-neighborhoods are used on thc squ are grid, the square raster is obtained. Similarly, if 8-neighborhoods are used on the same square grid, thcn the octagonal raster is obtai ned . These 4- neighborhood and 8-neighborhood concepts are int roduced in Section 2.3. 1 . 2 1n some case, the properties of an image at Rub-pixel resolution can be computed. This is achieved by approximating the image fun ction by a continuous function.
16
Chapter 2: The image. its representations and properties
(0)
(,)
(b)
(d)
Figure 2.3: I3rightne8S levels. (a) 64. (b) 16. (c) 4. (d) 2.
Figure/; 3.11a a.nd 2.3a-d demonstrate I.he effect of reducing the number of brightness levels in an image. An original image with 256 brightness levels (Figure 3.11a) has its number of brightuesl:i levels reduced 1.064 (Fib'lJre 2.3<1.), and no degradation is perceived. Figure 2.3h uses 16 brightness levels and false contours begin t.o emerge, and this become/; clearer in Figure 2.3c with four brightnesses and in Figure 2.3d with only two.
2.3
Digital image properties
A digital image has several properties, both metric and topological, which are somewhat different from those of continuous two-dimensional functions with which we are familiar. Another feature of difference is human perception of images, since judgment of image quality is also important.
2.3 Digital image properties
2.3.1
17
Metric and topological properties of digital images
A digital image consists of picture elements with finite size-these pixels carry information about the brightness of a particular location in the image. Usually ( and we assume this hereafter ) pixels are arranged into a rectangular sampling grid. Such a digital image is represented by a two-dimensional matrix whose elements are natural numbers corresponding to the quantization levels in the brightness scale. Some intuitively clear properties of continuous images have no straightforward analogy in the domain of digital images. Distance is an important example. Any function D holding the following three condition is a 'distance ' (or a metric )
D(p, q) 2: 0 , for ( D (p, q) = 0 if and only if p = q) identity, symmetry, D (p , q) = D ( q , p) , triang71lar inequality. r) D (p, ::; D (p, q) + D (q, r) , The distance between points with co-ordinates ( i, j ) and (h, k) may be defined in several different ways. Here, we discuss the following distance metrics: the Euclidean distance, the 'city block' distance, and the 'chessboard' distance. The Euclidean distance D E known from classical geometry and everyday experience is defined by (2.3) DE ((i,j ) , (h , k) ) = J(i - h) 2 + (j - k) 2 . The advantage of Euclidean distance is that it is intuitively obvious. The disadvantages are costly calculation due to the square root, and its Hon-integral value. The distance between two points can also be expressed as the minimum number of elementary steps in the digital grid which are needed to move from the starting point to the end point. If only horizontal and vertical moves are allowed, the distance D4 is obtained. The distance D1 is also called 'city block' distance ( also Ll metric or Manhattan distance) because of the analogy with the distance between two locations in a city with a rectangular grid of streets and closed blocks of houses:
D4 ( (i, j) , (h, k) ) = [ i - h ! + [ j - k ! .
(2.4)
If moves in diagonal directions arc allowed in the digitization grid, we obtain the distance Ds, often called the 'chessboard' distance. The distance Ds is equal to the number of minimal king-moves on the chessboard from one part to another:
Ds ( (i , .i ) , (h , k) ) = max { ! i - h ! , ! j - k ! } .
(2.5)
These distance definitions are illustrated in Figure 2.4.
o
o
1
2
4
",, '
1
2
3
. /
Figure 2.4:
Distance metrics
De , D4 ,
and
DB .
Pixel adjacency is another important concept in digital images. Any two pixels (p , q ) are called 4-neighbors if they have distance D4 (p, q ) = 1 . Analogously, 8-neighbors
Chapter 2: The image, its representations and properties
18
(1\) 4-Ileigl,borhood are two pixels with Figure
Figure 2.5: Neighborhood or the representative (gray filk-d pixel in the middle).
pixel
(b) 8-neighborhood
D8(p, q)
:0::
1.
Both 4-neighbors and 8-neighbors are illustrated in
2.5.
It will
become
nece$..<;ary to consider important sets consisting of several adjacent
path frOIn pixel P to pixel Q as a sequence of poillts AI, A2, , An, where An :o:: Q, and AH! is a neighbor of Ai, i 1, . . . , n 1; then a region is a set of pixels in which there is a path between any pair of its pixels, all of whose pixels also pixels-regions (in set theory, a region is a connected set). More descriptively, we can define a
At
:0::
. . .
P,
-
-=
H there is a path between two pixels in the set of pixels in the m i age, these pixels
belong to the set. are called
contiguous.
is a set of pixels in which 'to be contiguous' is reflexive, symmetric, and transitive and therefore defines a decomposition of the set (the image in our case) into equivalence classes (regions). Figure 2.6 illustrates a binary image decomposed by the relation 'contiguous' into three regions. Alternatively, we can say that a region
each pair of pixels is contiguous. The relation
.. ...1fr� - � Assume that
Figure 2.6: The relation 'to be contiguous' de composes an image into individual regions. The Japanese Kanji character meaning 'ncar from here' docomposes into
3 regions.
R; are disjoint regions in the image which were created by the relation Ho;;
'to be contiguous ' , alld further assume (to avoid special cases) that these rcgions do not touch the image bounds. Let
be the union of all regions
RC be the set complement
the image. The subset of RC which is contiguous with the image background, and the remainder of the eomplemellt RC is called holes.3 A region is called simple contiguous if it has no holes. Equivalently, the complement of a simply contiguous region is contiguous. A region with holes is called multiple contiguous.
of
R with
R
respect to
bounds is called the
Note that the COIl(.'(:pt of region uses only the property 'to be cOlltigIiOUS'. Secondary properties can be attached to
regions
which originate in image data illterpretation. It is
common to call some regions in the image
objects;
a process which determines which
segmentation Chapters 6 and 7. The brightll� of a pixel is a very simple property which can be used to find objects in some imagC!;; if, for example, a pixel is darker than SOllie predefined value (threshold), regions in an image correspond to objects in the world is a part of image and is discussed ill
then it belongs t.o the object. All such points which are ah;o cOlltiguous constitute one object. A
hole consists of
points which do not belong to
the object
alld are SUlTounded
lSome image processillg literature d� no� distinguish holes and background, and calls both of them bACkground.
2.3
19
Digital image properties
by the object, and all other points constitute the background. An cxample is the black printed text
Oil
this white sheet of paper, in which individual letters
arc
objects. White
areas snrroullded by the letter are holes, fot" example, the area inside the letter white parts of the paper arc the background.
'0'.
Other
These neighborhood and contiguity definitions on the square grid create interesting paradoxCl:;. Figurc 2.7a shows two digital line �gmcnts with 45° slope. If 4�connectivity
is a.lso illustrated; two perpendicular lines do
is used, the lines arc not contiguolls at each of their point.s. An even worse conflict with intuitive understanding of line properties
intersect in onc case (upper right intersection) and do not intersect in another case (lower left), as they do not have any common point (i.e., their set iutersection is empty) .
•
,.
•
•
•
•• ••
•
•
(b)
Figure
2.7:
Paradoxes
of crossing lines.
1£ images i\re digitized in a SQuare grid llsiug
It is known from Euclidean geometry that cadI closed curve (e.g., a circle) divides the plane into two nOll-contiguous regions.
8-connectivity, we can dl"ftw a line from the inner part of a closed curve into the outer
all pixels of the line belong to
part which docs 1I0t iutersect the curve (Figure 2.7h). This implies that the inner ami outer parts of the curve constitute only one region because
only one region. This is another paradox. One possible solution to contiguity paradoxes
is to treat objects USill!; 4-ueighborhoods and back!;round using 8-neighborhoods (or vice versa). A more exact treatment of digital images paradoxes and their solution for biuary images and images with more brightn� levels call be found in [Klette and Rosellfeld, 20041 ·
These problems are typical on square grids-a hexagonal grid (see Figure 2.2), however,
I;olvcs many of them. Any point in the hexagonal raster ha s the same distance to all
its six neighbors. There arc some problems peculiar to the hexagonal raster as well (for example, it is difficult to express a Fourier transform on it). For reasons of simplicity and cll se of processing, moot digitizing devices use a square grid despite the stated drawbacks. An alternative approach to the connectivity problems is to use discrete topology based
on cellular complexes [Kovalevsky, 19891. This approach develops a complete strand of image encoding and segmentation that deals with many issues we shall come to later, such as the representation of boundaries and regions. The idea, first proposed by the German mathematician Bernhard lliemann in the nineteenth century, considers families of sets of different dimellsious; pOints, which arc O-dimellsional sets, may then be assigned to sets containing higher-dimensional structures (such as pixel arrays) . This approach permits the remOVal of the paradoxes we have
S('''CII.
distance transform can be i.ntroduced. The distance transform is also called the distance function or chamfering algorithm or simply chamfering to build an analogy to it. Having introduced the concept of ueighbors, distance and rehrioll, the
20
Chapter 2: The image, its representations and properties
woodcarving operation. Thc idea of the distance transform is importfl,llt as it provides the basis of several fast algorithms as will be shown morc times in this book. The distancc transform provides the distance of pixels from some image subset (perhaps describing objects or some features). The resulting 'image' has pixel values of 0 for elements of the relevant subset, low values for close pixels, and then high values for pixels remote from it·-·the appearance of this array gives the name to the technique. In other words, the distance transform of a binary inlage provides the distance from cach pixel to the nearc::;t non-zero pixel. Hypothetical pixels outside the image limits are also treated as non-zero pixels. For illustration, consider a binary image, in which ones represent the objects and zeros the background. The distance transform here flSSigns to each pixel in the image the distance to the c1O&'_'it object or to the border of the whole image. Pixels within objects have distance traru;forrn equal to zero. The input image is shown in Figure 2.8 and . the result of the distance transform for the distance D4 is illustrated in Figure 2.9. ,
,
0
0
0
0
0
0
0
0
0
0
0
0
,
0
0
0
0
0
0
0
0
0
0
,
0
0
,
0
0
,
,
,
0
0
0
0
0
0
0
,
0
,
0
0
0
0
0
0
0
0
0
0
5
4
4
0
3
2
2
0
,
0
0
0
1
0 0
0
4
2
0
,
,
0
0
0
1
Figure 2.8: Input binary image. Gl"ay pixels correspond to objects and white pixels to background.
,
3
,
0
0
3
2
,
,
3
2
1
2
,
2
3
2
2
3
4
1
2
,
2
, ,
0
0
0
2
,
3
3
0
,
, , 0
, 2
2
2
,
1
0
3
2
2
1
Figure 2.9: Result of the distance trans form when the distancc D4 is considered in caJculatiOIlll.
A two-pass algorithm calculating the distan� transform was suggested by [Rosenfeld and Pfalt"" 1966, H.l68] for distances D4 and Ds. The idea is to traverse the image by a small local 1ll1.\Sk. The first pass starts from top-left ('.orner of the image and moves horizontally left to right until it reaches the bounds of the image and then returns to the beginning of the next row. The second pass goes from the bottom-right corner in the opposite bottom-up: right to left direction using a different local mask. The effectiveness of the algorithm comes from propagating the values of the previous image investigation in a 'wave-like' manner. The m$ks used in calculations arc shown in Figure 2.10.
-
AL
AL
AL
p
AL
-
BR p
BR
BR
SR
Figure 2.10: Pixel neighborhoods used in distance transform calclllations-··pixel p is the central one. The neighborhood on the left is used in the first pass (top-down, left to right) of the algorithm. The neighborhood on the right is used in the second pass (bottom-up, right to left).
2.3 D igital image properties
21
Algorithm 2.1: Distance transform 1 . To calculate the distance transform for a subset S of an image of dimension ]v! x N
with respect to a distance metric D, where D is one of D4 or Ds, construct an M x N array F with elements corresponding to the set S set to 0, and all other elements set to infinity. 2. Pass through the image row by row, from top to bottom and left to right. For each neighboring pixel above and to the left (illustrated in Figure 2.10 by the set AL) set F(p) = min (F(p), D(p, q) + F(q)) . q
3. Pass through the image row by row, from bottom to top and right to left. For each neighboring pixel below and to the right (the set BR in Figure 2.10), set
F(p) = min (F(p), D(p, q) + F(q)) . q
4. The array F now holds a chamfer of the subset S. This algorithm needs obvious adjustments at image boundaries, where the sets AL and BR are truncated. This algorithm has been improved by many authors, e.g. , in [Montanari, 1968] by approximating Euclidean distance by the quasi-Euclidean distance D E , Q v'2
D E . . h k )) _ Q ( (1" J) , ( , -
{
- 1) lj - kl - hl + ( liv'2 - 1) li - hl + lj - kl (
for Ii - hi > IJ - kl otherwise.
,
(2.6)
[Barrow et al., 1977] suggest calculating only in the integer domain. [Borgefors, 1986] generalized the approximation of Euclidean distance calculations to larger masks and to 3D images. The exact calculation of Euclidean distance for 2D images was suggested in [Breu et al. , 1995J . The Euclidean distance transform can be calculated in linear time in higher dimensions [Maurer et al. , 2003]. Distance transform performance is illustrated on an artificial binary image consisting only of three distinct 'ones'. The result for distances DE, D1, Ds and D E is shown in Q Figure 2 . 1 1 . The distance transform has many applications, e.g., in discrete geometry, path planning and obstacle avoidance in mobile robotics, finding the closest feature in the image, and skeletoniJlation (discussed with mathematical morphology methods in Section 13.5.5). An edge is a further important concept used in image analysis. This is a local property of a pixel and its immediate neighborhood -it is a vector given by a magnitude and direction. The edge tells us how fast the image intensity varies in a small neighborhood of a pixel. Images with many brightness levels are used for edge computation, and the gradient of the image function is used to compute edges. The edge direction is perpendicular to the gradient direction which points in the direction of the fastest image function growth. Edges are considered in detail in Section 5.3.2. The related concept of the crack edge creates a structure between pixels in a similar manner to that of cellular complexes. However, it is more pragmatic and less
22
Chapter 2: The image, its representations and properties
Ibl
1.1
Figure 2.11: Iilu:,;tration
lei
Idl
of four distances used often in distallcc transform calculation�. The
inp\lt image consists of three isolated 'ones'. The output distance is visualized as the intensity, lighter values
dcnote
higher distances. Contour plots are superimposed for better visualh:ation.
(a) Euclideall distance O�;.
Euclidean distance DQE.
(b)
Cily block distallce 04• (c) Chessboord distance Olj. (d)
Quasi
mathematically rigorous. Four crack edges are attached to each pixel, which are defined hy its relatiou to its 4-neighbors. Thc direction of the crack cdgt! is that of increasing brightness, and is a multiple of 900, while its magnitude is the ab!)Qlute difference between t.he brightncs... of the relevant pair of pixels. Crack edges are illmitrated in Figure 2.12 and will be IlSed in considering image segmentation (Chapter 6). The border (boundary) of a region is another important concept in image analysis. The border of a region R is the set of pixels within the region that have one or more neigbbors outside R. The definition corresponds to an iut,uitive understanding of the border as a set of points at the bound of the region. This definition of border is sometimes referred to as the inner border to distinguish it from the outer border, that is, the border of the background (i.e., it.s complement) of the region. Inner and outer borders are illustrated in Figure 2.13. Due to the discrete nature of the image, some iuner border elemeuts which wonkl be distinct in the contiullous case coincide in the discrete case, a... can be seen with the one-pixel-wide line at the right of Fignre 2.13.
Figure 2.12:
Crack edge;;.
Figure 2.13: Inner
borders
and outer horders shown com::iidcrcd.
ali
of a region showu as white circles black squan."l;. 4-ueighborhood was
Note that there is a differenc.c between border and edge. The border is a global concept related to a region, while edge expresses local properties of an image function. Borders and edge; arc related as well. One possibility for finding boundaries is chaining the t;ignifieant edges (points with high gradient of the image function). Methods of this kind are described in Section 6.2.
2.3 Digital image properties
23
The shape of a region can be qualitatively described using the property of being convex. If any two points within a region are connected by a straight line �gment, and the whole line lies within the region, then this region is convex-see Figure 2.14. The property of convexity decomposes all regions into two <"-'quivalellcc classes: convex and nOll-convex.
Figure 2.14: A convex region (left) and non-convex region (right).
A convex hull is a concept used to describe qualitative propertiC!:l of objects. The convex hull is the smallest convex region containing the input region, possibly noll-convex. For example, consider an object whose shape resembles thc letter 'R' (see Figure 2.15). Imagine a thin rubber band pulled around the object; the shape of the rubber band provides thc convex hull of the object. Calculation of thc convex hull is described in Section 8.3.3. Topological properties are not based on the distance concept. These properties are invariant to the homeomorphic transform which can be illustrated for images as rubber sheet transform. Imagine a small rubber balloon with an object painted on it; topological properties of the object are tho;;c which are invariant to arbitrary stretching of the rubber sheet. Stretching does not change contiguity of the object parts and does not change the number of holes in regions. One such image property is the Euler-Poincare characteristic, defined as thc difference between the number of regions and the number of holes in them. We use the term 'topological properties' of the region to describe its qualitative properties invariant to small changes, e.g., the property of being convex. Strictly speaking, an arbitrary homeomorphic transformation call change a convex region to a non-convex onc and vice versa. Following the rubber sheet transformation analogy, it lIleans that the stretching of the sheet is only gentle. Further properties of regions that are not rubber sheet invariallt are described in Section 8.3.1. An object with non-regular shape can be represented by a co!!ection of its topological components, Figure 2.15. The set inside the convex hu!! which does not belong to an object is calk>d the deficit of convexity. This call be split into t.wo subsets: lakes (dark gray) are fully surrounded by the object; and bays (light gray) are contiguous with the border of the convex hull of the object.
Convex
Regkln
hull
- Lakes = Bays
Description using topological components: All 'R' object, its convex hull, and the associated lakes alld bays. Figure 2.15:
The convex hull, lakes, and bays are sometimes used for object description; these features are IlS('
Chapter 2: The image, its representations and properties
24
l I I '�II�II:::;::�� o
(.)
�"" J
__ __ ' so 200
, 00
(b)
I
2!0
Figure 2.16: Original illLage (a) and its brightness histogram (b).
2.3.2
Histograms
brightness histogram hj(z) of an image provides the frequency of the brightness z in the image-the histogram of an image with L gray-levels is representt..>
The
valuc
Algorithm 2.2: Computing the brightness histogram
hj. 2. For all pixels (x,y) of the image j , increment hj(J(x,y)) 1.
Assign zero values to all elements of the array
by
1.
We might want to find a first-order probability function p\(z; x , y) to indicate the
The histogram provides a natural bridge between images and a probabilistic descrip
tioIl.
probability that pixel
(x, y)
has brightne&i
z.
Dependence on the position of the pixel is
not of interest in the histogram; a density function Pl
(z)
is of interest and the brightnes s
histogram is its estimate. The histogram is often displayed as a bar graph. An image and
its brightness histogram are given in Figure
2.16.
The histogram is usually t.he only global information about t.he image which is available. It. is used when finding optimal illumination conditiOlls for capturing an image, gra.y·scale transformations, and image segmentation to objects and background. Note that on€: histogram may correspond to several images; for instance, a change of the object position on a constant background does not affect the histogram. The histogram of a digital image typicaUy has many local minima and maxima, which may complicate its further processing. This problem can be avoided by local smoothing of t.he hi5togram; this may be done, for example, using local averaging of neighboring hi5togram clements as the base, so tha.t a new hi.,togram
h,(z)
is calculated according to
(2.7)
2.3 D igital image properties
25
where K is a constant representing the size of the neighborhood used for smoothing. This algorithm would need some boundary adjustment, and carries no guarantee of removing all local minima. Other techniques for smoothing exist, notably Gaussian blurring; in the case of a histogram, this would be a one-dimensional simplification of the 2D Gaussian blur, equation (5.47) , which will be introduced in Section 5.3.3.
2.3.3
Entropy
If a probability density p is known then image information content can be estimated regardless of its interpretation using entropy H. The concept of entropy has roots in thermodynamics and statistical mechanics but it took many years before entropy was related to information. The information-theoretic formulation of entropy comes from Shannon [Shannon, 1948] and is often called information entropy. An intuitive understanding of information entropy relates to the alUount of uncertainty about an event associated with a given probability distribution. The entropy can serve as an measure of 'disorder'. As the level of disorder rises, entropy increases and events are less predictable. The entropy is defined formally assuming a discrete random variable X with possible outcomes (called also states) X l , . . . , xn . Let p(Xk) be the probability of the outcome Xk , k = 1 , . . . n. Then the entropy is defined as (2.8) The entropy of the random variable X is the sum, over all possible outcomes k of X, of the product of the probability of outcome :J:k with the logarithm of the inverse of the probability of Xk . 10g2 (ljp(:Ek)) is also called the surprisal of the outcome Xk . The entropy of the random discrete variable X is the expected value of its outcome 's surprisal. The base of the logarithm in this formula determines the unit in which entropy is measured. If this base is two then the entropy is given in bits. Recall that the probability density P (Xk ) needed to calculate the entropy is often estimated using a gray-level histogram in image analysis, Section 2.3.2. Entropy measures the uncertainty about the realization of a random variable. For Shannon, it served as a proxy capturing the concept of information contained in a message as opposed to the portion of the message that is strictly determined and predictable by inherent structures. For example, we shall explore entropy to assess redundancy in an image for image compression (Chapter 14) .
2.3.4
Visual perception of the image
Anyone who creates or uses algorithms or devices for digital image processing should take into account the principles of human image perception. If an image is to be analyzed by a human the information should be expressed using variables which are easy to perceive; these are psycho-physical parameters such as contrast, border, shape, texture, color, etc. Humans will find objects in images only if they may be distinguished effortlessly from the background. A detailed description of the principles of human visual perception can be found in [Bruce et aI. , 1 996; Palmer, 1 999] . Human perception of images provokes many illusions, the understanding of which provides valuable clues about
26
Chapter 2: The image. its representations and properties
visual mechanisms. Some of the better-known i11llsiolls will be mentioned here-the topic is covered exha.ustively from the point of view of computer vision ill [Frisby, 19791. The situation would be relatively easy if the humall visual system had a linear response to composite iuput st.imuli--i.e., a simple slim of individual stimuli. A decrease of some stimulus, e.g., area of the object in the image, conld be compensated by its intensity, contrast, or duration. In fact, the sensitivity of huma.n senses is roughly logarithmically proportional to the inteusity of all input signal. In t.his case, after an initial logal"it.hmic transformation, response to composite stimuli call be treated as linear. Contrast
Contrast is the local change in brightness and is defined as the ratio between average brightnes,', of fLn object and the background. Strictly speaking, we should talk abont hnuinRIlce4 instead of brightnc8S if our aim is to be physically precise. The human eye is logarithmically sensitive t.o brightness, implying that for the same perception, higher briglitlless n'quires higher contrast.. Apparent. brightnc.'>.'I depend" very much on the brightncss of the local surrouudillgs; t.his effect is callex! conditional contrast. Figure 2.17 illustrates this with five circles of the same size surroulldex! by squares of different brightness. Humans perc:eive the brightness of the small circles as differcllt. ..
Figure 2.17: Conditional contrast effect. Circles inside squares have the same brightness and are perceived as havillg differellt brightness value;.
Acuity
Acuity is t.he ability to det.ect details in an image. The human eye is less sensitive to slow and fast cilallges ill brightness ill the image plane but is more sensitive to intermediate dlallges. Acuity also decreases with increasiug distance from the optical axis. Resolut.ion in an image is fit'mly bounded by the resolution ability of the human eye; there is no sense in represent.ing visual information with higher resolution thall that of the viewer. Resolution in optics is defiued as the inverse value of a maximum viewing allgle between the viewer and two proximate points whic:h humans cannot distinguish, and so fuS() together.. Human vision has t.he best resolution for objects which are at a distance of about 250 !lUll from an eye nnder illumination of about 500 lux; this illumination is provided by a 60 W bulb from a. dist.ance of 400 nun. Under these conditions the distance between two distinguishable points is approximately O.16 mm. ·jLuTninance describes the amount of light that pas;es through or is emitted from a particular area, amt ralls within a given solid angle. Lumill/mce is given clmdela per square meter [cdjm2].
2.3 Digital image properties
o
000 o
o�o o
Figure
27
2.18: The Ebbinghaus illusion.
Some visual illusions
Human perception of images is prone to many illusions. See [Palmer, 1999] for a com prehensive treatment of the subject. There are many other visual illusiolls caused by phenomena such as color or motion: an Internet search will produce examples easily. Object borders carry a lot of information for humans. Boundaries of objects and simple patterns such as blobs or lines enable adaptation effects similar to conditional contrast, mentioned above. The Ebbinghaus illusion is a well-known example---two circles of the same diamet.er in the center of images appear to have different diameters (Figure 2.18). Perception of one dominant shape can be fooled by nearby shapes. Figure 2.19 shows parallel diagonal line !:iegmcnts which are not perceived as paralleL Figure 2.20 contains rows of black and white squares which are all parallel. However, the vertical zigzag squares disfllpt our horimntal perception.
• • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • •
,
Figure
2.19:
Disrupted paralic! diagonal lines.
Perceptual grouping
..
Figure 2.20: Horimntal lines are paml!el, although not perceived
a.
such.
perceptual grouping [Palmer, 1999] is a priuciplc useel in computer vision to aggregate elements provided by low-level operations such as edgels, which are small blobs to bigger chunks having some meaning. The roots are in Gestalt psychology first postulated by Prague born scientist Wertheimer in 1912. Gestalt psychology is a theory proposing that l.he operational principle of the mind and brain is holistic, parallel, and with self-organizing tendencies. Gestalt theory was meant to have general applicability; its main tenets, however, were induced almost cxclu!:iively from observations on visual perception. The overriding theme of the theory is that stimulation is perceived in organized or configuration terms. Gestalt in German means configuration, structure or pattern of physical, biological, or
A
28
Chapter 2: The image. its representations and properties
psychological phenomena so integrated to constitute a functional unit with properties not derivable hy summation of its parts. Patterns take pre<:edence over elements and have properties that arc not inherent in the elements themselves. The human ability to group items according to various properties is illustrated in Figure •
2.21.
•
•
• • 0
0
•
•
•
•
•
• •
0
0
•
•
•
not grouped
• •
by proximity
•
• •
• • •
•
•
•
• •
, , , , , , , ,
by similarity by similarity Figure
by direction
2.21:
Grouping according to
properties of elements.
Perceived properties help people to connect elements together based on strongly perceived properties as parallelism, symmetry, continuity and closure taken in a loose sense as illustrated in Figure
2.22.
It has been demonstrated that mimicking perceptual grouping in machine vision system is a plausible technique. It permits the creation of more meaningful chunks of Such grouping is useful in image understanding. This principle will be used in this book
information from meaningless outcomes of low-level operations such as edge detection. mainly for image segmentation.
paralellism Figure 2.22:
symmetry
continuity
closure
Illustration of properties perceived il1 images which allow humans to group together
elements in cluttered scenes.
2.3.5
Image quality
An image might be degraded during captmc, transmis..<;ioll, or proee5..<;ing, and measures of image quality can be lIsed to assess the degree of degradation. The quality required naturally depends on the purpose for which an image is used. Methods for assessing image quality can be divided into two categories: subjective and objective. Subjective methods are often used in television technology, where the ulti11ll'l.te criterion is the perception of a selected group of professional and lay viewers. They appraise an image according to a list of criteria and give appropriate marks. Details about subje<:tive methods may be found in [Pratt,
1978J.
Objective quantitative methods mea<;uring image quality are more interesting for our purposes. Ideally such a method also provides a good subjective test, and is easy to apply; we might thell image
I(x, y)
[Rosenfeld
usc
it as a criterion in parameter optimization. The quality of the
is usually estimated by comparison with a known reference image
and Kak,
19821. A synthesized image is often used for this purpose.
g(x, y)
One class
2.3 Digital image properties
29
of methods uses simple measures such as the mean quadratic difference 'E (g 1) 2 . The problem here is that it is not possible to distinguish a few big differences from a lot of small differences. Instead of the mean quadratic difference, the mean absolute difference or simply maximal absolute difference may be used. Correlation between images f and g is another alternative. Another class measures the resolution of small or proximate objects in the image. An image consisting of parallel black and white stripes is used for this purpose; then the number of black and white pairs per millimeter gives the resolution. Measures of image similarity are also important since they are used in assisting retrieval from image databases. -
2.3.6
Noise in images
Real images are often degraded by some random errors-this degradation is usually called noise. Noise can occur during image capture, transmission, or processing, and may be dependent on, or independent of, the image content. Noise is usually described by its probabilistic characteristics. Idealilled noise, called white noise is often used. White noise has a constant power spectrum (to be explained in Section 3.2.3) , meaning that all noise frequencies are present and have the same intensity. For example, the intensity of white noise does not decrease with increasing frequency as is typical in real-world signals. White noise is frequently employed to model the worst approximation of degradation, the advantage being that the use of white noise simplifies calculations. A special case of white noise is a Gaussian noise. A random variable with a Gaussian (normal) distribution has its probability density function given by the Gaussian curve. In the 1D case the density function is (2.9) where f.l is the mean and (J" the standard deviation of the random variable. Gaussian noise is a very good approximation to noise that occurs in many practical eases. vVhen an image is transmitted through some channel, noise which is usually indepen dent of the image signal occurs. Similar noise arises in old-fashioned vidicon cameras. This signal-independent degradation is called additive noise and can be described by the model (2. 10) f (x, y) = g (x, y) + v(x, y) , where the noise v and the input image g are independent variables. Algorithm 2.3 will generate zero mean additive Gaussian noise in an image-this can often be of use in testing or demonstrating many other algorithms in this book which are designed to remove noise, or to be noise resistant.
Algorithm 2.3: Generation of additive, zero mean Gaussian noise 1 . Suppose an image has gray-level range [0, G - 1] . Select less noise effect.
(J"
>
0; low values generate
30
Chapter 2: The image, its representations and properties 2. For each pair of horizontally neighboring pixels (x, y), (x, y + 1 ) generate a pair of independent random numbers r, cP in the range [0, 1 ] .
3. Calculate
Zl = (7 cos (27rcP ) v-2 In r ,
(2. 1 1 )
Z2 = (7 sin(27rcP )v - 2 In r .
(This is the Box-Muller transform which assumes that Zl , Z2 are independently normally distributed with zero mean and variance (72 . )
4. Set f'(x, y) = g(x, y ) + Z l and f'(x, y + 1 ) = g(x, y + 1) + Z2 , where image. 5. Set
J(x, y) = J(X, y + 1) =
{� {�
-1 J'(x, y)
if f'(x, y) < 0 , if J' (x, y » G - 1 , otherwise,
-1 f' (x, y + 1)
6. Go to 3 until all pixels have been scanned.
if f' (x, y + 1) < 0 , if J' (x, y + 1 ) > G - 1 , otherwise.
9
is the input
(2.12) (2.13)
The truncation performed by equations (2.12) and (2.13) will attenuate the Gaussian nature of the noise; this will become more marked for values of (J that are high relative to G . Other algorithms for noise generation may be found in [Pitas, 1993] . Equation (2.10) leads to a definition of signal-to-noise ratio (SNR) ; computing the total square value of the noise contribution E=
L v2 (x, y)
( x , y)
we compare this with the total square value of the ohl"erved Hignal
F
=
L J2 (:r, y) .
(�;, y ) The signal-to-noise ratio is then
SNR =
F
E
(2. 14)
(strictly, we are comparing the mean observation with the mean error- the computation is obviously the same) . SNR represents a measure of image quality, with high values being 'good'. Signal-to-noise is often expressed in the logarithmic scale, in decibels SNRdB = 10 log l O SNR .
(2.15)
2.4
Color
images
The noise magnitude depends in many cases on the signal magnitude itself f = gv .
31
(2.16)
This model describes multiplicative noise. An example of multiplicative noise is television raster degradation, which depends on TV lines; in the area of a line this noise is maximal, and between two lines it is minimal. Another example of multiplicative noise is the degradation of film material caused by the finite sil';e of silver grains used in photosensitive emulsion. Quantization noise occurs when insufficient quantization levels are used, for exam ple, 50 levels for a monochromatic image. In this case false contours appear. Quantization noise can be eliminated simply, see Section 2.2.2. Impulse noise means that an image is corrupted wit.h individual noisy pixels whose brightness differs significantly from that of the neighborhood. The term salt-and-pepper noise is used to describe saturated impulsive noise--�an image corrupted with white and/or black pixels is an example. Salt-and-pepper noise can corrupt binary images. The problem of suppressing noise in images is addressed in Chapter 5. If nothing is known a priori about noise properties, local pre-processing methods are appropriate (Section 5.3). If the noise parameters are known in advance, image restoration techniques can be used (Section 5.4).
2.4
Color images
Human color perception adds a subjective layer on top of underlying objective physical properties- -the wavelength of electromagnetic radiation. Consequently, color may be considered a psychophysical phenomenon. Color has long been used in painting, photography and films to display the surrounding world to humans in a similar way to that in which it is perceived in reality. There is considerable literature on the variants in the naming of colors across languages, which is a very subtle affair [Kay, 2005] . The human visual system is not very precise in perceiving color in absolute terms; if we wish to express our notion of color precisely we would describe it relative to some widely used color which is used as a standard: recall, e.g., the red of a British public telephone box. There are whole industries which present images to humans- the press, films, displays, and hence a desire for color constancy. In computer vision, we have the advantage of using a camera as a measuring device, which yields measurements in absolute quantities. Newton reported in the 17th century that white light from the sun is a spectral mixture, and used the optical prism to perform decomposition. This was a radical idea to propose at time; over 100 years later influential scientists and philosophers such as Goethe refused to believe it.
2.4.1
Physics of color
The electromagnetic spectrum is illustrated in Figure 2.23. Only a narrow section of the electromagnetic spectrum is visible to a human, with wavelength A from approximately 380 nm to 740 nm. Visible colors with the wavelengths shown in Figure 2.24 are called spectral colors and are those which humans see when white light is decomposed using a Newtonian prism, or which are observed in a rainbow
32
Chapter 2: The image, its representations and properties 10"
, 1
.J
10-
!
.L. '
10"
I_I
Figure 2,23: Divs i ion of
Frequenci
10'
1' , , 1 ' -1 ' 1 1
!.....1.
10"
-1 ! r
! O'
10'·
.L..J
the whole electromagnctic spectrum
es),
Wa�tlen81h [mc.1CrlI[
10'
' I- ) ' -1
!....J..._ ' L-L l.J 1...J. I ..l.... ,
I .L...J
1 0'"
1
! "
,...l !
f,equeocy [Hz)
(ELF
means Extremely Low
on the sky. Colors can be represented as combinations of the primary colors, e.g., red, grecH, and blue, which for the purposes of standardization have been defined as 700 nrn, 546.1 11m, and 435.8I1m, respectively [Pratt, 1978], although this standardization does not imply that all colors ean be synthesized as combinations of these three. • -
8 • " "
•
" • �
•
• .. 5
I , I" 400
� m
0
, I,
Figure 2.24:
I,
500
"
" •
• "
,I
"
�
�
• a "
• "
<
• 0
II600 ,I, ,
� •
�
I
700
_
,
,
l. [llmJ
Wavelcngth >. of the spectrum vi�ible to humans.
The intensity of irradiation for different wavelengths >. usually changes. This variation is expressed by a power spectrum (called also power spectrum distribution) S(>'). Why do we see the world in color? There are two predominant physical mechanisms describing what happens when a surface is irradiated. First, the surface reflection rebounds incoming energy in a similar way to a mirror. The spectrum of the reflected light remains the same fl.'.; that of the illuminallt and it is independent of the surface--recall that shiny metals 'do not have a color'. Second, the energy diffuses into the material and reflects randomly from the internal pigment in the matter. This mechanism is called body reflection and is predominant ill dielectrics as plastic or paints. Figure 2.25 illustrates both sUJ'face rcflection (mirrorillg along surface Ilormal n) and body refiection. Colors arc caused by the properties of pigment particles which absorb certain wavelengths from the incoming iHuminant wavelength spectrum. in�id�m
illumi1l3lion air
o o
o body
o
o
o 0 o 0
n
surfac�
/ rcn<'CtiOll
body , _ r.7,; :� - rdC\:tiOn
00
o
0
color pigment
Figure 2.25: Observed color of objects is caused by certain wavelength absorptions by pigment
particl� in dielectrics.
2.4 Color images
33
Most sensors used for color capture, e.g., in cameras, do not have direct access to color; the exception is a spectrophotometer which in principle resembles Newton's prism. Incoming irradiation is decomposed into spectral colors and intensity along the spectrum with changing wavelength ,\ is measured in a narrow wavelength band, for instance, by a mechanically moved point sensor. Actual spectrophotometers use diffraction gratings instead of a glass prism. Sometimes, intensities measured in several narrow bands of wavelengths are collected in a vector describing each pixel. Each spectral band is digiti:ted independently and is represented by an individual digital image function as if it were a monochromatic image. In this way, multispectral images are created. Multispectral images are commonly used in remote sensing from satellites, airborne sensors and in industry. Wavelength usually span from ultraviolet through the visible section to infrared. For instance, the LANDSAT 4 satellite transmits digitized images in five spectral bands from near-ultraviolet to infrared. Seven or a dozen wavelength bands are common.
2 .4.2
Color perceived by h umans
Evolution has developed a mechanism of indirect color sensing in humans and some animals. Three types of sensors receptive to the wavelength of incoming irradiation have been established in humans, thus the term trichromacy. Color Hensitive receptors on the human retina are the cones. The other light sensitive receptors on the retina are the rods which are dedicated to sensing monochromatically in low ambient light conditionH. Cones are categorized into three types based on the sensed wavelength range: S (short ) with maximum sensitivity at � 430 nm, M ( medium ) at � 560 nm, and L ( long) at � 610 nm. Cones S, M, L are occasionally called cones B, G and R, respectively, but that is slightly misleading. We do not see red solely because an L cone is activated. Light with equally distributed wavelength spectrum 100kH white to a human, and an unbalanced spectrum appears aH some shade of color. The reaction of a photoreceptor or output from a senHor in a camera can be modeled mathematically. Let i be the specific type of sensor, i = 1 , 2, 3, ( the retinal cone type S , M, L i n the human case ) . Let Ri ( '\ ) b e the spectral sensitivity o f the sensor, J ( '\) b e the spectral density of the illumination, and 5 ( '\ ) deHcribe how the Hurface patch refiects each wavelength of the illuminating light. The spectral response qi of the i-th Hensor, can be modeled by integration over a certain range of wavelengths
qi =
A2
J J ('\ ) Ri ( '\) 5 ('\ ) d'\ .
Al
(2. 17)
Consider the cone types S , M, 1 . How does the vector ( qS, qM , qL) represent the color or the surface patch? It does not according to equation (2.17) since the output from the photosensors depends on the three factorH J ( '\), 5 ( '\ ) and R ('\). Only the factor 5 ( '\) is related to the surface patch. Only in the ideal case, when the illumination is perfectly white, i.e., J ('\) = 1, can we consider ( qS, qM , qL) as an estimate of the color of the surface. Figure 2.26 illustrates qualitatively the relative sensitivities of S, M, L cones. Mea surements were taken with the white light source at the cornea so that absorption of wavelength in cornea, lens and inner pigments of the eye is taken into account [Wandell,
1995] .
34
Cha pter 2: The image, its representations and properties
Relative sensitivity of S, cones of the human eye to wave length. Figure 2 . 26 :
400
450
500
550
600
650
700 A [nmJ
lVI , L
A phenomenon called color metamer is relevant. A metamer, in general, means two things that are physically different but perceived as the same. Red and green adding to produce yellow is a color metamer, because yellow could have also been produced by a spectral color. The human visual system is fooled into perceiving that red and green is the same as yellow. Consider a color matching experiment in which someone is shown a pattern consisting of two adjacent color patches. The first patch displays a test light-a spectral color of certain wavelength. The second patch is created as an additive combination of three selected primary lights, e.g. , colors red=645.2 nm, green=525.3 nm and blue=444.4 nm. The observer is asked to control the red, green and blue intensities until both patches look identical. This color matching experiment is possible because of the color metamer. The result of measurements ( redrawn from [Wandell, 1995] ) is in Figure 2.27. Negative lobes can be seen on the curves for red and green in this figure. This would seem to be impossible. For wavelengths exhibiting negative values the three additive lights do not perceptually match the spectral color because it is darker. If the perceptual match has to be obtained then the observer has to add the intensity to the patch corresponding to the spectral color. This increase of this intensity is depicted as a decrease in the color matching function. Hence the negative values . red . ,'
.,
.
... -.� ,
. .. .1... I ....../
. :
,
...
green I . . . . . • -... /.. . ..
.....
"
500
, ··· 1 I
,
, : ......
600
\, .
.
, r , .. . . . . . . , \ . ,
.
,
....
:
700
Figure 2 . 2 7 : Color matching functions ob tained in the color matching experiment. Intensities of the selected primary colors which perceptually match spectral color of given wavelength A.
Human vision is prone to various illusions. Perceived color is influenced, besides the spectrum of the illuminant, by the colors and scene interpretation surrounding the observed color. In addition, eye adaptation to changing light conditions is not very fast and perception is influenced by adaptation. Nevertheless, we assume for simplicity that the spectrum of light coming to a point on the retina fully determines the color. Since color can be defined by almost any set of primaries, the world cOlllmunity agreed on primaries and color matching functions which are widely used. The color model was introduced as a mathematical abstraction allowing us to express colors as tuples of numbers, typically as three or four values of color components. Being motivated by the press and the development of color film, in 193 1 , CIE (International Commission on
2.4 Color images
35
Illumination, still acting in Lausanne, Switzerland) issued a technical standard called XYZ color space. The standard is given by the three imaginary lights X =700.0 mIl , Y =546 . 1 11111, Z=435.8 nm and by the color matching functions X(A), Y (A) and Z(A) corresponding to the perceptual ability of an average human viewing a screen through an aperture providing a 2° field of view. The standard is artificial because there is no set of physically realizable primary light8 that would yield the color matching functions in the color matching experiment. Nevertheles8, if we wanted to characterize the imaginary lights then, very roughly 8peaking, X � red, Y � green and Z � blue. The CIE standard is an example of an ab801ute standard, i.e., defining unambiguous representation of color which doe8 not depend on other external factors. There are more recent and more preci8c ab801ute standards: CIELAB 1976 (ISO 13665) and HunterLab (http: //www.hunterlab.com) . Later, we will also discu88 relative color 8tandards such as RGB color space. There arc several RGD color 8paces used -two computer devices may display the 8ame RGD image differently. The XYZ color standard fulfi1l8 three requirements: Unlike the color matching experiment yielding negative lobes of color matching function8, the color matching functions of XYZ color 8pace are required to be non negative; The value of Y (A) should coincide with the brightne8s (luminance) ; Normalization is performed to assure that the power corresponding to the three color matching functions is equal (i.e., the area under all three curves is equal) .
•
• •
The re8ulting color matching functions are shown i n Figure 2.28. The actual color i s a mixture (more precisely a convex combination) of ex
X+
Cy
Y
+
Cz
Z,
(2. 18)
where 0 � Cx , Cy' , Cz � 1 are weights (intensities) in the mixture. The subspace of colors perceivable by Immal18 is called the color gamut and is demonstrated in Figure 2.29. I .X 1 .6
'" > '" .g C) =
E :�
�
1 .4 I .2 1 .0
-------
,
,,
° r - - - - -
1,
------i
, ,, .. _-
,,
r · - - - - -,
y
,, ,
o.x 0.6 0.4 0.2 0.0
400
500
600
700
; qnm]
Figure 2.28: Color matching functions for the CrE standard from 1931. X (>.. ) , Y (>.. ) , Z (>.. ) are color matching functions. Redrawn from [Wandell, 1995] .
Figure 2.29: Color gamut - a subspace of the X, Y, Z color space showing all colors perceivable by humans.
36
Chapter
2:
The image,
its representations and properties
GtE Chromaticity Diagram 1931 ,m
Figure 2.30: CIE chromaticity diagram is a projection of XYZ color space into a plane. The t.riangle depicts a subset of col ors spanned by n:d, green, and blue. These are TV colors, i.e., all possible color which can be seen on 1\ CRT display. A color ver· siun of this figm-e may be seen in the color
,,
.
inset-Plate 1.
3D figures are difficult to handle in publications, and so a planar view of a 3D color space is used. The proje<:tioll plane is given by the plane passing through extremal points on all three axes, i.e., points Y, Z. The new 20 coordinates x, y are obtained as
X,
x =
� X,--:-'i + y;-'--; + Z; ' x
y=
y
X+Y+Z'
z = l -x - y.
The result of this plane projection is the CIE chromaticity diagram, see Figure 2.30. The horseshoe like subspace contains colors which people are able to sec. All mono chromatic spectrA. visible to humans map into the curved part of the horseshoe-their wavelengths are shown in Figure 2.30. Disp\fty and printing devices use three selected real primary color!; (as opposed to three syntactic primary colors of XYZ color space). All possible mixtures of these primary <..'Olors fail to cover the whole interior of the hor:;eshoe in CIE chromaticity diagram. This situation is demonstrated qualitatively for three particular devices in Figure 2.31. ...
CRT monllot gamut
,n X
(a) CRT monitor
."
."
CIE C�rom&li<:ity Diagram 1931 .
'
(b) printer
o.
01 X
M
(c) film
II.' .r
Figure 2.31: Gamuts which ean be displayed using three typical display devices. A color versioTi of tllis figure may be seen irl the t:Qlor inset-Plate 2.
Color inset
A
Plate 1: Page 36, Figure 2.30.
�" ""oo••.., Diag'''"' 1931
I
CRT monitor gamu1
(a) CRT monitor
(hu9) •
0 • 0
fl >
>
..
-
saturation (chroma)
0.1 X
.. Plate
ChromatiOty Diagram 1931
(b) printer
U
07 X
Color film gamu,
(c) film
OJ
2: Page 36, Figure 2.31.
hue
�
• • • • • ••• ••••••• • saturation, • (chroma)
Plate 3: Page 38, Fi.gure 2.33.
0.7 X
B
Color inset
Plate
4;
Page 40, FiguI'e 2.34.
_ .....,.... I<9I_ .. .... ffT)
• .
.
r'·
f
I
I (0)
(b) Plate 5: Page 61.. FiguIT. 3.7.
____.....'"1
--..-_ ...",.. .'
':�$ .
-
-_.
•
•
(0)
-
-
-
-_.
--.,
.-
Plate 6: Page 62, Figure 3.9.
-
(b)
--..
Color inset
Plate 7: Page 160, Figure 5.37.
-
,
Plate 8: Page 161, Figure 5.38.
C
o
Color
inset
'00
(hi
(-I Plate
9: Page 261, Figure 7.2.
-20
20
3(1
(-I
"
-�
(01 Plate 10: Page 262, Figure 7.3.
(hi
•
, 00
Color inset
(b)
(.) Plate
11: Page 290, Figure 7.27.
(b)
(.)
(e)
(ei
Plate 12: Page 305, Figur'C 7.37.
(d)
E
F
Color inset
(0)
(b) Plate
13: Page 489, Figure /0,18.
Color inset
(0)
(b)
« )
(d)
Plate
14: Page 530. Fi!Jurr> 10.46.
/
/ (d)
« ) Plate 15: PIlge 630. FigU1'C 12.22.
G
H
Color inset
Plate 16: Page 647, Figure
1£.30.
Plate 17: Page 647, Figl£T"e
12.31.
-
,;.. .
Plate 18: Page 649. Figw-e 12.3..(.
2.4 Color images
2.4.3
37
Color spaces
Several different primary colors and corresponding color spaces are used in practice, and these spaces can be transformed into each other. If the absolute color space is used then the transformation is the one-to-one mapping and does not lose information (except for rounding errors) . Because color spaces have their own gamuts, information is lost if the transformed value appears out of the gamut. See [Burger and Burge, 2006] for a full explanation and for algorithms; here, we list several frequently used color spaces. The RGB color space has its origin in color television where Cathode Ray Tubes (CRT) were used. RGB color space is an example of a relative color standard (as opposed to the absolute one, e.g. , CIE 1 93 1 ) . The primary colors (R-red, G-green and B-blue) mimicked phosphor in CRT luminophore. The RGB model uses additive color mixing to inform what kind of light needs to be emitted to produce a given color. The value of a particular color is expressed as a vector of three elements--intensities of three primary colors, recall equation (2.18). A transformation to a different color space is expressed by a transformation by a 3 x 3 matrix. Assume that values for each primary are quantized to rn = 2n values; let the highest intensity value be k = rn - 1 ; then (0, 0, 0) is black, (k, k, k) is (television) white, (k, 0, 0) is 'pure' red, and so on. The value k = 255 = 28 - 1 is common, i.e. , 8 bits per color channel. There are 2563 = 2 24 = 16, 777, 2 16 possible colors in such a discretized space. - s :,
i
Blue (O, O,k)
Cyan (O,k,k)
Magenta (k, O, k) " White (k,k,k) , , , , , Black (O, O,0:J...'_-+___-:;j. .l
R
.. ,/
Green (O,k,O)
/e::------...... Red (k, O, 0)
G
Yellow (k,k,O)
Figure 2.32: RGB color space with primary colors red, green, blue and secondary colors yellow, cyan, magenta. Gray-scale images with all intensities lie along the dashed line connecting black and white colors in RGB color space.
The RGB model may be thought of as a 3D co-ordinatization of color space (see Figure 2 .32 ) ; note the secondary colors which are combinations of two pure primaries. There are specific instances of the RGB color model as sRGE, Adobe RGB and Adobe Wide Gamut RGB. They differ slightly in transformation matrices and the gamut. One of transformations between RGE and XYZ color spaces is
[�] [�] z
�
=
] [X H�i �] [�:�� �fi H�] [�] . - 1 .54 1 .88 0.20 -
0.02
- 0 : 50 0 04 1 .06
(2. 19)
The US and Japanese color television formerly used YIQ color space. The Y component describes intensity and I, Q represent color. YIQ is another example of
38
Chapter 2: The image, its representations and properties
additive color mixing. This system stores a luminance value with two chrominance values, corresponding approximately to the amounts of blue and red in the color. This color space corresponds closely to the YUV color mode! in the PAL television norm (Australia, Europe, except France, which uses SECAM). YIQ color !;pace is rotat<.x1 330 with respect to the YUV color space. The YIQ color model is useful since the Y component provides all that is neces!;ary for a monochrome display; further, it exploits advantageou!; propertie!; of the human visual sy!;tem, in particular our sensitivity to luminance, the perceiv(:."(1 energy of a light source. The CMY-·for Cyan, Magenta, Yellow-color model use;; subtractive color mixing which is used in printing processes. It describes what kind of inks need to be applied so the light reflected from the white substrate (paper, painter's canvas) and passing through the ink!; produce; a given color. CMYK stores ink values for black in addition. Black color can be generated froUl C, M, Y components but as it is abundant in printed documents, it is of advantage to have a special black ink. MallY CMYK colors spaces are used for different sets of inks, substrates, and pre;;s characteristics (which change the color tmnsfer function for each ink and thus <:hange the appearance).
HSV - Hue, Saturation, and Value (also known as HSB, hue, saturation, brightness) is often used by painters because it is closer to their thinking and technique. Artists commonly use three to four dozen colors (characterized by the hue; technically, the dominant wavelength). If another color is to be ohtained then it is mixed from the given ones, fOf example, 'purple' or 'orange'. The painter also wants colors of different saturation, e.g., to change 'fire brigade red' to pink. She will mix the 'fire brigade red' with white (and/or hlack) to obtain the desired lower saturation. The HSV color model is illustrated in Figure 2.33.
D •
saturation (chroma)
-
�
hoe
�
At
=••••••• •• • • • •
,
saturation (chroma)
Figure as
!\
2.33: HSV
A color be .�I!e71 in the
color 1lI0del illustrated
cylinder and unfolded cylin(lcr.
version of this figU7"e CO/Of inset-Plate 3,
may
HSV decouples intensity infofmation front color, while hue and saturation eot'respond to human perception, thus making this representation very useful for developing illlage processing algorithms. This will become clearer as we proceed to describe image en hancement algorithms (for example, equalizatioB Algorithm 5.1), which if applied to each component of an RGB model would corrupt the human st!nse of color, but which would work more or less as expected if applied to the intensity component of HSV (leaving the color information unaffected). HSL (hue, saturation, lightBess/lumill
I
Models
Color spaces
I
2.4 Color i mages
39
Applications
Colorimetric
XYZ
Colorimetric calculations
Device oriented, nonuniform spaces
RGB, UIQ
Storage, processing, coding, color TV
Device oriented, Uniform spaces
LAB, LUV
Color difference, analysis
User oriented
HSL, HSI
Color perception, computer graphics
2.4.4
Palette images
Palette images (called also indexed images) provide a simple way to reduce the amount of data needed to represent an image. The pixel values constitute a link to a lookup table (also called a color table, color map, index register, palette) . The lookup table contains as many entries as the range of possible values in the pixel, which is typically 8 bits == 256 values. Each entry of the table maps the pixel value to the color, so there are three values, one for each of three color components. In the typical case of the RGB color model, values for red, green and blue are provided. It is easy to see that this approach would reduce data consumption to one-third if each of the RGB channels had been using 8 bits (plUS size of the look up table ) . Many widely used image formats for raster images such as TIFF, PNG and GIF can store palette images. If the number of colors in the input image is less than or equal to the number of entries in the lookup table then all colors can be selected and no loss of information occurs. Such images may be cartoon movies, or program outputs. In the more common case, the number of colors in the image exceeds the number of entries in the lookup table and a subset of colors has to be chosen, and a loss of information occurs. This color selection may be done many ways. The simplest is to quantize color space regularly into cubes of the same size. In the 8 bit example, there would be 8 x 8 x 8 = 256 such cubes. If there is, e.g., a green frog in green grass in the picture then there will not be enough shades of green available in the lookup table to display the image well. In such a case, it is better to check which colors appear in the image by creating histograms for all three color components and quantize them to provide more shades for colors which occur in the image frequently. If an image is converted to a palette representation then the nearest color (in some metric sense) in the lookup table is used to represent the color. This is an instance of vector quantization (see Section 14.4) which is widely used in analyzing large multi-dimensional datasets. It is also possible to view the occupation by the pixels of RGB space as a cluster analysis problem (see Section 9.2.5 ) , susceptible to algorithms such as k-meam; (Algorithm 9.4) . The term pseudo color is usually used when an original image is gray-level and is displayed in color; this is often done to exploit the color discriminatory power of human vision. The same palette machinery as described above is used for this purpose; a palette is loaded into the lookup table which visualizes the particular gray-scale image the best. It could either enhance local changes, or might provide various views of the image. ·Which palette to choose depends on the semantics of the image and cannot be derived from image statistics alone. This selection is an interactive process. Almost all computer graphics cards work with palette images directly in hardware. The content of the lookup table will be filled by the programmer.
40 2.4.5
Chapter 2: The image, its representations and properties Color constancy
Consider the situation in which the salUe surface is seen under different illumination, e.g., for a Rubik's cube in Figure 2.34. The same surface COIOTS are shown fully illuminated and in shadow. The human vision system is able to abstract to a certain degree from the illumination changes and perceive several instances of a particular color as the same. This phenomenon is called color constancy. Of course, it would be desirable to equip artificial perception systems bast.>d on photosensors with this ability too, bllt this is very challenging.
0
y
B
B Y R IN 0 R ,G G B G W O Y R' Y B O' B G B' W 0 G' R
,
Figure 2.34: Color constancy: The Rubik cube is captured in sunlight, and two of three visible sides of the cube are ill shadow. The white balance was set in thc shadow area. Therc are six colors on the cube: R-red, G-green, B-blue, O-orange, W-white, and V-yellow. The assignment of the six available colors to 3 x 9 visible color patches is shown on the right. Notice how different the saIlle color
patch call be:
St.'C
RCB values for the three instances of orange. A color version
of thi� figure may be seen iTI the color in.set--Plute 4.
Recall equation (2.17) which models the spectral response (}i of the i-th sensor by integration over a range of wavelengths as a multiplicatioH of three factors: spectral sensitivity Rt(A) of the sensor i ;:; 1 , 2, 3, spectral density of the illumination f(A), and surface refk-'Ctance S(A). A color vision system has to calculate the vector (}i for each pixel as if J(A) = 1. Unfortunately, the spectrum of the illmnillallt J(A) is usually unknown. Assume for a while the ideal case in which the spectrum I(A) of the illuminant is known. Color colL"tancy could be obtained by dividing the output of each sensor with its scnsitivity to the illumination. Let q� be the spectral response after compensation for the iUuminant (caBed von Kries coefficients), q: Pi% where =
(2.20) Partial color constancy can be obtained by multiplying color responses of the three photosensors with von Kries coefficients Pi. In practice, there arc several obstacles that make this procedure intractable. First, the iIluminant spectrum J(A) s i not known; it can only be guessed indirectly from reRections in surfaces. Second, only the approximate spectrum is expressed by the spectral response
2.5 Cameras: a n overview
41
qi of the i-th sensor. Clearly the color constancy problem is ill-posed and cannot be solved without making additional assumptions about the scene. Several such assumptions have been suggested in the literature. It can be assumed that the average color of the image is gray. In such a case, it is possible to scale the sensitivity of each sensor type until the assumption becomes true. This will result in an insensitivity to the color of the illumination. This type of color compensation is often used in automatic white balancing in video cameras. Another common assumption is that the brightest point in the image has the color of the illumination. This is true when the scene contains specular reflections which have the property that the illuminant is reflected without being transformed by the surface patch. The problem of color constancy is further complicated by the perceptual abilities of the human visual system. Humans have quite poor quantitative color memory, and also perform color adaptation. The same color is sensed differently in different local contexts.
2.5 2 .5.1
Cameras: a n overview P hotosensitive sensors
Photosensitive sensors most commonly found in cameras can be divided into two groups:
Sensors based on photo-emission principles explore the photoelectric effect. An exter nal photon carried in incoming radiation brings enough energy to provoke the emission of a free electron. This phenomenon is exhibited most strongly in metals. In image analysis related applications, it has been used in photomultipliers and vacuum tube TV cameras.
Sensors based on photovoltaic principles became widely used with the development of semiconductors. The energy of a photon causes an electron to leave its valence band and changes to a conduction band. The quantity of incoming photons affects macroscopic conductivity. The excited electron is a source of electric voltage which manifests as electric current; the current is directly proportional to the amount of incoming energy ( photons ) . This phenomenon is explored in several technological elements as a photodiode, an avalanche photo diode ( an amplifier of light which has similar behavior from the user 's point of view as the photomultiplier; it also amplifies noise and is used, e.g. , in night vision cameras ) , a photorcsistor, and Schottky photodiode. There are two types of semiconductor photoresistive sensors used widely in cameras: CCDs ( charge-coupled devices ) and CMOS ( complementary metal oxide semiconductor ) . Both technologies were developed in laboratories in the 1 960s and 1970s. CCDs became technologically mature in the 1970s and became the most widely used photosensors in cameras. CMOS technology started being technologically mastered from about the 1990s. At the time of writing ( 2006 ) neither of these technologies is categorically superior to the other. The outlook for both technologies is good. In a CCD sensor, every pixel's charge is transferred through just one output node to be converted to voltage, buffered, and sent off-chip as an analog signal. All of the pixel area can be devoted to light capture. In a CMOS sensor, each pixel has its own charge-to-voltage conversion, and the sensor often includes amplifiers, noise-correction,
42
Chapter 2: The image. its representations and properties
and digitization circuits, so that the chip outputs ( digital) bits. These other functions increase the design complexity and reduce the area available for light capture. The chip can be built to require less off-chip circuitry for basic operation. The basic CCD sensor element includes a Schottky photodiode and a field-effect transistor. A photon falling on the junction of the photodiode liberates electrons from the crystal lattice and creates holes, mmlting in the electric charge that accumulates in a capacitor. The collected charge is directly proportional to the light intensity and duration of its falling on the diode. The sensor elements are arranged into a matrix-like grid of pixels-a CCD chip. The charges accumulated by the sensor elements are transferred to a horizontal register one row at a time by a vertical shift register. The charges are shifted out in a bucket brigade fashion to form the video signal. There are three inherent problems with CCD chips. •
•
•
The blooming effect is the mutual influence of charges ill neighboring pixels. Current CCD sensor technology is able to suppress this problem (anti-blooming) to a great degree. It is impossible to address directly individual pixels ill the CCD chip because read out through shift registers is needed. Individual CCD sensor elements are able to acclllllulate approximately 30-200 thou sands electrons. The usual level of inherent noise of the CCD sensor is on the level of 20 electrons. The signal-to-noise ratio (SNR) in the case of a cooled CCD chip is SNR = 20 10g(200000/20), i.e. , the logarithmic noise is approximately 80 dB at best. This causes that the CCD sensor is able to cope with four orders of magnitude of intensity in the best case. This range drops to approximately two orders of magnitude with common uncooled CCD cameras. The range of incoming light intensity variations is usually higher.
Here, current technology does not beat the human eye. Evolution equipped the human eye with the ability to perceive intensity (brightness) in a remarkable range of nine orders of magnitude (if time for adaptation is provided) . This range is achieved because the response of the human eye to intensity is proportional logarithmically to the incoming intensity. Nevertheless, among the sensors available, CCD cameras have high sensitivity (are able to see in darkness) and low levels of noise. CCD dements are abundant, also due to widely used digital photo cameras. The development of semiconductor technology permits the production of matrix-like sensors based on CMOS technology. This technology is used in mass production in the semiconductor industry because processors and memories are manufactured using the same technology. This yields two advantages. The first is that mass production leads to low prices; because of the same CMOS technology, the photosensitive matrix-like element can be integrated to the same chip as the processor and/or operational melllory. This opens the door to 'smart cameras' in which the image capture and basic image processing is performed on the same chip. The advantage of CMOS cameras (as opposed to CCD) is a higher range of sensed intensities (about 4 orders of magnitude) , high speed of read-out ( about 100 ns) and random access to individual pixds. The disadvantage is a higher level of noise by approximately one degree of magnitude.
2.5 Cameras: an overview
2.5.2
43
A monochromatic camera
The camera consists of the optical system (lens), the photosensitive scnsor(s) and electron ics which enables the processing of a captured image, and transfer to further processing. Analog cameras generate a complete TV signal which contains information about light intensity, and horizontal and vertical synchronization pulses allowing row by row display. The frame scan Clm be with interlaced lines a.'i in ordinary analog TV, which was introduced to reduce image flickering on cathode-ray tube (CRT) screens. A rate of 60 half-frame!:! per second is used in the USA and "apall, and 50 half-frames per second in Europe and elsewhere. The whole image has 525 lines in the USA and Japan, 625 lines in Europe and elsewhere. Analog cameras require a digitizer card (a frame grabber) to be plugged in to the computer. Analog cameras have problems with jitter which means that two neighboring lines are not aligned properly and 'float' in a statistical manncr olle against thc other. The human eye is insensitive to jitter because it smootbes out the statistical variation. However, jitter causes problems when the camera is used for measurement purposes such a.<; gauging. Non-interlaced analog cameras with an appropriate frame grabber suppress this problem. NOIl-intcrlaced cameras do not need to conform to TV norms, and usually provide higher resolution such as 1024 x 720 pixels. Nowadays, the preferred solution is to use digital cameras in measurement applications. CCD
;..
optics
.
III�..
camera
Figure 2.35:
: analog . cable
.....
..III
digitizer
. digit. . data in a ! cabl� compv/er
III:" ..:..
..
Analog CCD camera.
A block diagram of an analog camera with It CCD chip is in Figure 2.35. Thc block AGC (Automatic Gain Control) automatically changes the gain of the camera according to the amount of light in the scene. The gain is set as a compromise betweeu neccStiary sensitivity in low illuminated area.'i and the attempt to avoid saturation of bright areas in the scene. Cameras usually contain another block named '"Y correction which performs nonlinear tmusfOl"lnation of the intensity scale. The necessity for this in the display chain originates in television technology with cathode--ray tubes (CRT). The dependency betwElCn the grid bias voltage U and the resulting irradiance L (....... brightness) of the luminophore is exponential, L = UtJ-the typical value of (J is 2.2. The shape of the transfer curvc is roughly parabolic. Note that the intensity of modern flat Liquid Crystal Displays (LCD) depends linearly on the input voltage. In order to maintain a linear transfer function of the whole display chain with CRT, there is a need to compensate the non-linear transfer function by an inverse curve. It was
44
Chapter 2: The image, its representations and properties CCD
-
{(lmer(l
i 11;4
optics
;4
1I!4
digilal (lble
d(lt(l in (I : computer i
11:4
II'
Figure 2.36: Digital CCD camera. easier and cheaper to include compensation circuitry into a few cameras at the beginning of the television era than to pllt it into a.
mass
produced TV set. Due to the need for
the output voltage of the camera Uk on the input radiation E, Uk = E lJlj
E"f. The
backward compatibility, there is a module in cameras which modifies the dependency of =
typical valne is thus l' = 1/2.2 ::::: 0.45. Some cameras allow the 'Y-value to be set in the range (0, 1). The value 1'=1 corresponds to the correction being switched off.
Sometimes, it is necessary to use the camcra as an absolute measuring device of incoming intensities. The image capturing chain has to be radiometrically calibrated before the actual measurement starts. In such a case, there is a need to switch off AGe and 'Y-correction. Higher quality cameras allow both AGC and 'Y-corrcction to be switched on or off. In cheaper cameras, it may be possiblc to switch off AGe and l' correction by intervening into the camera electronics.
Analog cameras are equipped with video circuitry which adds frame synchronir,ation pulses to the signaL The high-pass filter in the camera compensates for a decrease of high frequencies in the optical part. The TV signal is usually conducted by a coaxial cable to a digitizer (fraille grabber) in a computer. At the input of the digitir,er, there are sometimes high-pass filter:; to compensate for the loss of high frequencies in the cable. A block diagram of a digital camera is in Figure 2.36. The conversion from photon energy to voltage is t,he same as in analog cameras including potential AGC and/or 'Y-correction. The analog-to-digital (A/D) converter provides a uumber proportional to the input intensit.y.
These numbers have to be transferred to the computer for
further proccssing··-the connection can be done using either parallel or serial hardware. Serial connections usually exploit widely used technology standardized in the (FireWire) or USB (Universal Serial Bus) protocols. only short cahles of length about
1
In
IEEE
1394
the case of parallel connection,
meter can he used.
Analog cameras
Digital cameras
+
Cheap webcams. Dropping price for others.
Multiple sampling of 1\ signal.
+
Shorter cable (� lOm for Firewire). Kilometers after conversion to optical cable. Any length for Intemel camera.s. Single sampli ng.
Noisy due to analog transmissioll.
+
No transmi ssion noise.
+
Lilles are vertically aligned.
+
Cheap.
+
Long cable possible (up to 300 m).
Line jitter.
2.5 Cameras: an overview
2 .5. 3
45
A color camera
Electronic photosensitive sensors are monochromatic. Three strategies are usually em ployed to capture color images: •
• •
Record three different images in succession by employing color filters in front of mono chromatic cameras. This approach is used only in precise laboratory measurements because it is impractical and impossible for any subject involving motion. Using a color filter array on a single sensor. The incoming light is split into several color channels using a prism-like device.
A color filter array mosaic is often combined with a single photosensitive sensor to create a color camera. Each pixel is covered with an individual filter which can be implemented either on a cover glasH on the chip package ( hybrid filter) or directly on the silicon ( monolithic filter ) . Each pixel captures only one color. Consequently, the color resolution is about one third of the geometric resolution which would correspond to a monochromatic camera with same number of pixels. The full color values for each pixel can be interpolated from pixel values of the same color in local neighborhood. The human eye is most sensitive to green, less to red, and least to blue. This property is used by the most common color filter for single chip cameras called the I3ayer filter mosaic or pattern ( Bryce E. Bayer, US patent dated 1976), sec Figure 2.37. It can be seen that the number of green-sensitive pixels is equal to the combined number of pixels sensitive to red and blue.
G B GJ B iii R I G GIB GIB R iG R iG
G R G R
B G B G TIG B GIB G R iG
-...---
Figure 2.37: Bayer filter mosaic for single chip color cameras.
A great advantage of a mosaic filter is its optical simplicity. It provides the single focal plane necessary for the usc of standard film lenses. Good mosaic filters provide excellent bandpass transmission. Many professional digital SLR ( Single Lens Reflex) and studio cameras use mosaic filters. Multiple-chip cameras use color filters to split incoming light into separate color channels. Photosensors are simple and preserve the spatial resolution. Aligning and registering the sensors to the color splitter to the prism requires high precision. For pixels of the same size, color splitter systems should allow higher sensitivity in low light conditions, since they should lose less light in the filters. In practice, this advantage is not always available. Color splitting device often include absorption filters because simple refraction may not provide sufficiently precise color separation. The beam splitter approach complicates the optical system and limits lens selection significantly. The additional optical path of the prism increases both lateral and longitudinal aberration for each color's image. The longitudinal aberration causes different focal lengths for each color; the photosensor could be moved independently to each color 's focal point, but then the lateral aberration would produce different magnification for each color. These aberrations can be overcome with a lens specifically designed for use with the prism, but such camera-specific lenses would be rare, inflexible, and expensive.
Chapter 2: The image, its representations and properties
46
2.6 •
•
•
Summary
Basic concepts A 2D image gray-scale image is represented by a scalar function f(x, y) of two variables which give coordinates in a plane. In many cases, a 2D image is formed as the result of a projection of a 3D scene into 2D. The domain of the digitized image is a limited discrete grid the coordinates of which are natural numbers. The range of the digitized image is a limited discrete set of gray values ( brightnesscil ) . A pixel represents the elemental part of an image. Image digitization Digitization ( sampling) of an image can be seen as a product of a sampling function and a continuous image function. Usually the grid consists of regular polygons ( squares or hexagons ) . The second aspect of sampling is setting the distance between the sampling points ( the smaller sampling distance the higher the resolution of the image ) . Gray level quantization governs the appearance of shading and false contour. A human is able to recognize about 60 gray levels at most. Images containing only black and white pixels are called the binary. Digital image properties - The neighborhood relation of a pixel has to be defined to be able to represent discrete geometry. - A function providing distance between two pixels has to be established-there are several definitions used. The most commonly used is 'city block ' , 'chessboard', and the Euclidean distance used in everyday life. If the neighborhood relation is ilet for a grid then a raster is obtained. Given a raster, topological properties are induced. These properties are based on the relation 'being contiguous' and lead to concepts of region, background, hole, and region border. The convex hull of a region is the minimal convex subset containing it. 4-neighborhoods and 8-neighborhoods lead to 'crossing line' paradoxes which complicate basic discrete geometry algorithms. However, there exiilt ilolutions to these paradoxes for both binary and grey-level images. The distance transform ( chamfering ) of a binary image provides the distance from each pixel to the nearest non-zero pixel. There is a computationally effective two-pass algorithm to compute this, the complexity of which depends linearly on the number of pixels. The brightness histogram is a global descriptor of the image giving the eiltimate of the probability density that a pixel has a given brightnesil. Human visual perception is vulnerable to various illusions. Some of the proper ties of human perception of images as perceptual grouping are inspirations for computer vision methods. - Live images as any other measurements or observations are always prone to noise. It is possible to assess the noise extent quantitatively using, e.g., signal-to-noise ratio.
2.7 References
47
•
- vVhite, Gamisian, impulse, and salt-and-pepper noise are common models. Color images
•
Human color perception is a subjective psychophysical layer on top of underlying objective physical properties-the wavelength of electromagnetic radiation. Three types of sensors receptive to the wavelength of incoming irradiation have been established in humans. Color sensitive receptors on the human retina are cones. The other light sensitive receptors on the retina are rods which are dedicated to sensing monochromatically in low ambient light conditions. Cones are categorized into three types based on the sensed wavelength range, approximately corresponding to red, green and blue . Cameras Most cameras use either CCD or CMOS photosensitive elements, both using photovoltaic principles. They capture brightness of a monochromatic image. Cameras arc equipped with necessary electronics to provide digitized images. Color cameras are similar to monochromatic ones and contain color filters.
2.7
References
Barrett H. H. and Myers K. .1 . Foundation of Image Science. Willey Series in Pure and Applied Optics. Wiley & SOilS, Hoboken, New Jersey, USA, 2004.
Barrow H. G . , Tenenbaum J. 1'1 . , Bolles R. C . , and Wolf H. C. Parametric correspondence and chamfer matching: Two new techniques for image matching. In 5th International JO'int Conference on Art4icial Intelligence, Cambridge, CA, pages 659-663. Carnegie-Mellon University, 1977. Borgefors G. Distance transformations in digital images. Comp'uter Vision Graphics and Image Processing, 34(3):344-371, 1 986. Bracewell
H.
N. Fourier- Analysis and Imaging. Springer-Verlag, 1st edition, 2004.
Breu H., Gil J . , Kirkpatrick D . , and Werman M. Linear time euclidean distance transform algorithms. IEEE Transactions on Pattcrn Analysis and Mach1:ne Intelligence, 17(5) :529-533, 1995.
Bruce V., Green P. Il., and Georgeson IVI. A. Visual Perception: Physiology, Psychology, and Ecology. Psychology Press, Boston, 3rd edition, 1 996.
Burger W. and Burge M . .J. Dig1:tale Bildvcrarbdtung, Einc Einfuehmng mit Java und ImageJ. Springer-Verlag, 2006. In German, English version Image processing with Java is due in July 2007.
Frisby Kay
P.
.1. P.
Secing --Illusion, Brain and Mind. Oxford University Press, Oxford, 1979.
Color categories arc not arbitrary. Cross-cultural Research, 39 ( 1 ) :39--55, 2005.
Klette R. and Rosenfeld A. D1:gital Geometr'Y, Geometric Methods for Digital Pict7J,re Analysis. Morgan Kaufmann , San Francisco, CA, 2004. Kovalevsky V. A. Finite topology as applied to image analysis. Computer Vision, Graphics, and Image Processing, 46: 141-16 1 , 1989. Maurer C. R., Qi R. , and Raghavan V. A linear time algorithm for computing exact Euclidean distance transforms of binary images in arbitrary dimensions. IEEE Tmnsactions on Pattern Analysis and Ma.chine Intelligence, 25(2):265-U 270, 2003.
Chapter 2: The image, its representations and properties
48
Montanari U. A method for obtaining skeletons using a quasi-euclidean distance. Journal of the Association fOT Computing Machinery, 1 5 (4) :600-624, 1968. Palmer S. E. Vision Science : Photons to Phenomenology. The MIT Press, Cambridge, MA, USA, 1999. Pitas
1.
Digital Image Processing Algorithms. Prentice-Hall, Hemel Hempstead, UK, 1993.
Pratt W. K. Digital Image Processing. Wiley, New York, 1978. Rosenfeld A. and Kak A. C. Digital Pictur'e Processing. Academic Press, New York, 2nd edition, 1982. Rosenfeld A. and Pfaltz 33 -62, 1968.
.J.
L. Distance functions on digital pictures. Pattern Recognition, 1 (1 ) :
Rosenfeld A. and Pfaltz J. L. Sequential operations in digital picture processing. Journal of the Association for Computing Machinery, 13(4):471-494, 1 966. Shannon C. E. A mathematical theory of communication. Bell System Technical Journal, 27: 379-423, 623-656, 1948. Wandell B. Foundation of Vision. Sinauer Associates, 1995.
Chapter
3
The image. its mathematical and physical background
3.1
Overview
This chapter considers various IlSpects of digital images in greater theoretical depth Lhan the last; we do not present all the necessary mathematics and physics since they are considered in thorough detail in many more relcvaut places. Readers unfamiliar with this background are recommended to consider the descriptive textual presentation only; this chapter may be omittl:d without detriment. to an understanding of the algorithms that appear later in the book. The chapter is divided into three parts: Section 3.2 is devoted to linear integral transforms which provide a different insight into an image and are often used in analysis. This material is usually taught ill university mathematics or signal processing courses. The text is written to be concise yet stil! to contain sufficient technical information to be of benefit to deeper understanding. Section 3.3 overvicws probabilistic mcthorls necessary if images cannot be represented detenninistieally. In this case, a more complicated approach is often needed in which images are understood as a rea.li�ation of stochastic proces.<;cs. The theory of stochastic processes is a well established, extensive branch of mathematics, and only basic notions are explailled here. Section 3.4 is an introduction to image formation physics. It is of advantage to understand how an image is created before its computer analysis; the section begins with basic geometric optics which illustrate how to realize an optical system which mimics the pin-hole camera. Then radiometric and photometric concepts which explain image formation from the point of view of physics are preseuted. In many practical cases, image formation physics is not directly explored because it is too complicated to determine all the parameters which describe a particular capture settiug, aud some related tasks are ill-posed. Instead, object/background segmentation is performed, which exploits semantic knowledge about a specific a.pplication. This approach will be explained in Chapters 6
50
Chapter 3: The image, its mathematica l and physical background
and 7. Nevertheless, it is recommended the reader browse this material to understand how physical knowledge of the image capturing process can contribute to analysis.
3.1.1
linearity
The notion of linearity will occur frequently in this book: this relates to vector (linear) spaces where commonly matrix algebra is used. Linearity also concerns more general elements of vector spaces, for instance, functions. The linear combination is a key concept in linear mathematics, permitting the expression of a new element of a vector space as a sum of known elements multiplied by coefficients (scalars, usually real numbers) . A general linear combination of two vectors x , y can b e written as ax + by, where a , b are scalars. Consider a mapping .c between two linear spaces. It is called additive if .c(x + y) = .cx + .cy and homogeneous if .c (ax) = a.cx for any scalar a. From a practical point of view, this means that the sum of inputs (respectively, multiple) results in the sum of the respective outputs (respectively, multiple) . This property is also called a superposition principle. We call the mapping .c linear if it is additive and homogeneous (i.e. , satisfies the superposition principle) . Equivalently, a linear mapping satisfies .c(ax + by) = a.cx + b.cy for all vectors x, y and scalars a, b, i.e. , it preserves linear combinations.
3.1.2
The Dirac distribution and convolution
Some formal background on moving from the continuous to discrete domains will be of help, as will a definition of convolution. These are fundamental motivators for appreciating the use of linear mathematical theory in considering image functions. An ideal impulse is an important input signal; the ideal impulse in the image plane is defined using the Dirac distribution o(x , y) ,
I: I: o(x, y) dx dy = l ,
(3.1 )
I: I: f(x, y) o(x - A , y - J1,) dx dy = f(A, /L) .
(3. 2)
I: I: f(a, b) o(a - x , b - y) da db = f(x , y) .
(3.3)
and o(x, y ) = 0 for all (x, y) -j. O. The following equation is called the 'sifting property' of the Dirac distribution; it provides the value of the function f(x, y) at the point (A, 'I)
The 'sifting equation' (3.2) can be used to describe the sampling process of a continuous image function f(x, V ) . We may express the image function as a linear combination of Dirac pulses located at the points a, b that cover the whole image plane; samples are weighted by the image function f(x, y)
Convolution is an important operation in the linear approach to image analysis. The convolution is an integral which expresses the amount of overlap of one function f (t)
3 . 1 Overview as it is shifted over another function finite range [0, is given by
tj
51
h(t ) . A 1D convolution f * h o f functions f, h over a
(f * ,L)(t) 10t f(t) h(t - T) dT . ==
(3.4)
To be precise, the convolution integral has bounds - DC , DC . Here we can restrict to the interval [0, t] , because we assume zero values for negative co-ordinates.
(3.5) (f * h)(t) I: f(t) h(t - T) dT = I: f(t - T) h(t) dT . Let f , g , h be functions and a a scalar constant. Convolution satisfies the following properties (3.6) f*h=h*f, (3.7) f * (g * 'L) = (.f * g) * h , (3.8) f * (g + h) = (f * g) + (f * h) , (3.9) a (f * g) = (a.f) * = f * (ag) . ==
9
Taking the derivative of a convolution gives
(3. 10) We will see later that the above derivative of the convolution proved useful, e.g. , in edge deteetion of images. Convolution can be generalized to higher dimensions. Convolution of 2D functions and is denoted by h, and is defined by the integral
h
f* (f * h)(;c, y) = I: I: f(a, b) h(.7: - Y - b) dadb j.-ococ 100_oc x - a,y - b a, b dadb f( ) h( ) = (h * .f )(x, y )
f
0"
=
(3. 1 1 )
In digital image analysis, the discrete convolution is expressed using sums instead of integrals. A digital image has a limited domain on the image plane. However, the limited domain does not prevent us from the use of convolutions as their results outside the image domain are zero. The convolution expresses a linear filtering process using the filter linear filtering is often llsed in local image pre-processing and image restoration. Linear operations calculate the resulting value in the output image pixel as a linear combination of image intensities in a local neighborhood () of the pixel in the input image. The contribution of the pixels in the neighborhood () is weighted by coefficients h (3.12) L
h;
g(ii,,j) f( j)
f('i ,j) =
(m,n ) E O
h(i - rn, j - n)g(m,n) .
Equation (3. 12) is equivalent to discrete convolution with the kernel h , which is called a convolution mask. Rectangular neighborhoods () arc often used with an odd number of pixels in rows and columns, enabling specification of the central pixel of the neighborhood.
Chapter 3: The image, its mathematical and physical background
52
3.2
Linear i ntegral transforms
Linear integral transforms are frequently employed in image processing. Using such transforms, images are treated as linear (vector) spaces. Same as when dealing with 1 D signals, there are two basic and commonly used representations of image functions: the spatial domain (pixels) and the frequency domain (frequency spectra) . In the latter case, the image is expressed as a linear combination of some basis functions of some linear integral transform. For instance, the Fourier transform uses sines and cosines as basis functions. If linear operations are involved in the spatial domain (an important example of such linear operation is convolution) then there is a one-to-one mapping between the spatial and frequency representations of the image. Advanced signal/image processing goes beyond linear operations, and these non-linear image processing techniques are mainly used in the spatial domain.
3. 2 .1
I mages as linear systems
Images and their processing can be modeled as superpositions of point spread functions which are represented by Dirac pulses 8 (equation 3 . 1 ) . If this image representation is used, well-developed linear system theory can be employed. An operator is a mapping from one vector space to another. A linear operator .c (also called linear system) has the property
.c{ah + bh } = a .c{ .fr } + b .c {h} ·
(3.13)
An image f can be expressed as a linear combination of point spread functions represented by Dirac pulses 8. Assume that the input image f is given by equation (3.3) . The response g of the linear system .c to the input image f is given by
f: f: f(a, b) .c { o(x = f: f: f(a, b ) h(x - a ,
g ( x , y) = .c { .t (x, y) } =
- a, Y Y
-
-
b) } d a d b
b) d a d b = (f * h) (�;, y) .
(3. 14)
where h is the impulse response of the linear system .c. In other words the output of the linear system .c is expressed as the convolution of the input image f with an impulse response h of the linear system .c. If the Fourier transform (explained in Sections 3.2.3 and 3.2 .4) is applied to equation (3.14) and the Fourier images are denoted by the respective capital letters then the following equation is obtained
G(u, v) = F(u, v ) H(u, v) .
(3. 15)
Equation (3.15) is often used in image pre-processing to express the behavior of smoothing or sharpening operations, and is considered further in Chapter 5. It is important to remember that operations on real images are not in fact linear- both the image co-ordinates and values of the image function (brightness) are limited. Real images always have limited size, and the number of brightness levels is also finite. Nevertheless, image processing can be approximated by linear systems in many cases.
3.2 Linear integral tra nsforms
3.2.2
53
Introduction to linear integral transforms
Linear integral transforms provide a tool which permits repreHcntations of signalH and images in a more Huitable domain, where information iH better visible and the solution of related problems is easier. Specifically, we are interested in the 'freqnency domain ' , and where the inverse transform exists. In snch a case, there is a one-to-one mapping between the spatial and frequency domains. The most commonly uHed linear integral transforms in image analysis are the Fourier, cosine, and wavelet tranHforms. The usual application of a linear integral transform in image proceHHing is image filtering, a term which comes from signal procesHing- -the input image iH processed by some filter to get the output image. Filtering can be performed in either the Hpatial or frequency domains, as illustrated in Figure 3.1. In the frequency domain, filtering can be seen as boosting or attenuating specific freqnencieH. input image
�
r - - - -
_ _ _ _ _ _ _ _ _ _ _ _
J I
spatial filter
_ _ _ _
_ _ _ _ _ _ _ _ _ _ _
Figure 3 . 1 : The image can be processed in either spatial or fre quency domains. For linear op erations, these two ways should provide equivalent results.
J
We begin by reviewing the simpler 1D Fourier transform [Karu, 1999] , and will then proceed to the 2D Fourier transform, and mention briefly cosine and wavelet transforms.
3.2.3
1 0 Fourier transform
Developed by the French mathematician Joseph Fourier, the 1D Fourier transform F transforms a function f(t) ( e.g., dependent on time) into a frequency domain represen tation, F{.f(t ) } = F(� ) , where � [Hz = S - l J is a frequency and 27f� [S - lJ is an angular frequency. The complex function F is called the ( complex) frequency spectrum in which it is easy to visualize relative proportions of different frequencies. For instance, the sine wave has a simple spectrum consisting of a Hingle spike for positive frequencies, indicating that only a single frequency is present. Let i be the usual imaginary unit. The continuous Fourier transform F is given by F {.f ( t ) } = F( � ) =
J f(t) e-27rif,t dt . 00
-
(3. 16)
00
The inverse Fourier transform F - 1 iH then
J F (�) e27rif,t d� . 00
F - 1 { F(� ) } = f(t) =
- 00
The conditions for the existence of the Fourier spectrum of a function .f are: ·
•
r�oo I f(t) 1 dt <
i.e., .f haH to decrease faster than an exponential curve. f can have only a finite number of discontinuities in any finite interval. 00,
(3.17)
Chapter 3: The image, its mat hematical and physical backgrou nd
54
The Fourier transform always exists for digital signals (including images) as they are bounded and have a finite number of discontinuities. We will see later that if we use the Fourier transform for images we have to adopt the assnmption that images are periodic. The fact that images are not typically periodic present problems which will be discussed later. Attempting to understand what equation (3.16) means, it is useful to express the inverse Fourier transform as a Riemannian sum (3.18) where �,; = �k+l - �k for all k. The inverse formula shows that any 1D function can be decomposed as a weighted sum (integral) of many different complex exponentials. These exponentials can be decomposed into sines and cosines (also called harmonic functions) becanse eiw = cos w + i sin w. The decomposition of f(t) into sines and cosines starts with some basic frequency �o. Other sines and cosines have frequencies obtained by multiplying (0 by increasing natural numbers. The coefficients F(�k) arc complex numbers in general and give both magnitude and phase of the elementary waves. The Fourier transform exhibits predictable symmetries. Recall the notion of even, odd, and conjugate symmetric function, illustrated in Table 3. 1 .
Even
f(t) = f( -t)
Odd
f(t) = - f( - t )
)!!tJ
-L-/ _L-I " t
f( 5) = 4 + 7i f(�) = .f* ( - O f( - 5) = 4 - 7i
Conjugate symmetric
Concepts of even, odd and conjugate symmetric funetions (de noted by a superscript * ) . Table 3 . 1 :
Note that any 1D function f(t) shape can always b e decomposed into its even and odd parts fe (t) and fo(t)
f(t) - f( - t ) . fo (t) = 2
rflt) �lt) CL t I t --il j(t)
(3.19)
The ability to form a function from its even and odd parts is illustrated in Figure 3.2. r
=
C'r\ -
+
Figure 3.2: Any ID function can be de composed into its even and odd parts.
The symmetries of the Fourier tra,nsform and its values are summarized (without proof) in Table 3.2. Table 3.3 summarizes some elementary properties of the transform, all easily obtained by manipulation with the definitions of Equation (3.16) .
3.2 Linear i ntegral transforms
real f (t)
values of F(O
symmetry of F(O
general
complex
conjugate symmetric
even
only real
even
odd
only imaginary
odd
55
Fourier transform symmetries if f (t) is a real function.
Table 3.2:
Some other properties are related to areas under the function f or its Fourier representation F. The DC offset (DC from Direct Current 1 ) is F(O) and is given by the area under the function f
F(O) =
J f(t) dt ,
(3.20)
J F(�) d� .
(3.21 )
00
- 00
and a symmetric property holds for the inverse formula. The value of f(O) is the area under the frequency spectrum F(O , f(O) =
00
- 00
Parceval ' s theorem equates the area under the squared magnitude of the frequency spectrum and squared function f(t) . It can be interpreted as saying that the signal 'energy' in the time domain is equal to the 'energy' in the frequency domain. Parceval 's theorem is often used in physics and engineering as another form of a general physical law of energy conservation. The theorem states ( for a real function f, which is our case for images, the absolute value can be omitted )
J
00
- 00
I f(t) 1 2 dt =
J I F(�) 1 2 d� . 00
(3.22)
- 00
1 1'he I D Fourier transform was first widely used in electrical engineering.
Property
f (t)
F(�)
a .fl (t) + b.f2(t) a Fl (� ) + b F2 ( �) Duality f( -�) F(t) Convolution (.f * g ) (t) F(� ) G(O Product (F * G) (�) f(t) g (t) c-211"il;to F ( �) Time shift f(t - to ) e 211"iEo t f (t) Frequency shift F(� - �o ) t df( ) Differentiation 27ri�F( �) CIt i dF(I;) Multiplication by t t f(t) 211" � Linearity
Time scaling
f( a t)
1;I F (Ua)
Properties of the Fourier transform. Table 3 . 3 :
56
Chapter 3: The image, its mathematical and physical background
Figures 3.3, 3.4 and 3.5 show some properties of transforms of simple signals.
10
.f(t)
1
1
0(1)
'r Fi9
0
r(tJ 0
!0
.
�
0(E,)
.
t
�
..··
1 1 0! ! t ....,
····
t t t 1 t- · · ·.
T 2T
-2 T -T
...L ...L o L L
-2 T -T
T 2T
1
�
Figure 3.3: ID Fourier transform of the Dirac pulse, constant value and infinite sequence of Dirac pulses.
-AMv � -�t ((t)=cos(21t�"t)
flo
Re
F(E,) Figure 3.4:
.f(t) =sin(21t�" t)
rm F(�
F(E,)
t I t
f(t)=cos(21t�" t)
Re
+ cos(41t�" t)
F(E,)
JtIt t .
-2�n -�u 0 �n 2�o �
ID Fourier transform of the sine, cosine, and mixture of two cosines with different
frequencies.
Let Re c denote the real part of a complex number c and 1m c its imaginary part. The formulas describing four function-spectrum definitions are as follows: Complex spectrum Amplitude spectrum Phase spectrum Power spectrum
F(�) = Re (F(�)) + i lm (F(�)) , IF(�) I = Re (F2 (� )) + 1m (F2 (O) ,
V
(
)
¢ (�) = argtan Im (F (�) ) / Re (F(�)) , if defined, ( 3.23 ) P ( �) = IF( � ) 1 2 = Re (F2 (O) + 1m (F2 (�)) .
It can be seen from Figures 3.4 and 3.5 that time signals of short duration or quick changes have wide frequency spectra and vice versa. This is a manifestation of the uncertainty principle which states that it is impossible to have a signal which is arbitrarily narrow in both time and frequency domains. If the duration of the signal in the time domain and the bandwidth in the frequency domain were expressed as statistical moments, then the following compact uncertainty principle can be proved, 1 . 'signal duration' . 'frequency bandWIdth ' 2: . ( 3. 24 )
1r
The uncertainty principle is also of theoretical importance, and has a relation to the Heisenberg uncertainty principle from quantum mechanics [Barrett and Myers, 2004J .
3.2 Linear integral tra nsforms J(t)
.f(t)
_ _
J(t) =(.�in 21t�.l)/1tt
b -T a
T
=
Re F(C,)=(sil1 21t�T)/1t�
�
o" o v�°=
=
�
A
.f(t)=exp(-l)
�
_A
A = � °�V()vo
__
a
Re F(9 =(it exp(-1t'�-)
Re F(9 1
'I 0I
_
�
57
I
�o
-� 0
�
�
Figure 3.5: ID Fourier transform of the idealized rectangular pulse of lcngth 2T in the time domain gives the spectrum (2 cos21f�T)/�. Symmetrically, the idealized rectangular spectrum corresponds to an input signal of the form (2 cos 21f�ot)/t. The right column shows that a Gaussian pulse ha.'l the same form as its Fourier spectrum.
There is also a related question of interest for practitioners: which function f has the smallest duration-bandwidth product? It can be shown that such a function is Gaussian in the form f(t) = exp( _ t2 ) . The uncertainty principle allows for qualitative questions, snch as which signal has the higher bandwidth in frequency domain: sin (t)/t or sin (3t) /3t? The answer is the latter, because it is narrower. If we need to process a non-stationary signal, one option is to divide it into smaller pieces (called often windows) , and assume that outside these windows the signal is periodic. This approach is called the short time Fourier transformation- -STFT-- and was first introduced by Gabor in 1946. The STFT has been used in many disciplines, such as speech recognition. Unfortunately, mere cutting of the signal by non-overlapping rectangular windows is not good as it introduces discontinuities which induce wide bandwidth in the frequency domain. This is why the signal at the bounds of the local window is smoothly damped to zero by, e.g., a Gaussian or Hamming window. Any signal processing textbook will provide a more detailed explanation of windowing. The Fourier spectrum expresses global properties of the signal (as information of the speed of signal changes) but it does not reveal in which time instant such a change appears. On the other hand, the time domain represents precisely what happens at certain instants but does not represent global properties of the signal. There are two ways to step towards having a little of both-global frequency properties and localization. The first is the STFT, and the second is the use of different basis functions in the linear integral transformation which are less regular than sines and cosines. The wavelet transformation is one example, see Section 3.2.7. Computers deal with discrete signals: the discrete signal f(n) , n = 0 . . N 1 , is obtained by equally spaced samples from a continuous function f. The Discrete Fourier Transform (DFT) is defined a..<; .
F(k)
=
1
L
N n O =
and its inverse is defined as f(n)
N -l
=
N -l
L F(k) exp
k=O
(
f(n) exp -21fi
The spectrum F(k) is periodic with period N.
(
21f'l
nk N
;;k )
)
-
(3.25)
(3.26)
58
Chapter 3: The image, its mathematical and physical background
Computational complexity issues have to be tackled with the Discrete Fourier Transform. We will be interested in the time complexity as opposed to memory complex ity- -we would like to know how many steps it takes to calculate the Fourier spectrum as a functioll of the si7.e of the input. Computational complexity theory abstracts from the specific computer and the implementation language by working with qualitative, asymptotic behaviors of algorithms. The purpose is to characterize a function's ( or algorithm's ) behavior for large inputs in a simple form that enables comparison to other functions ( algorithms ) . An asymptotic upper bound for the magnitude of a function in terms of another, usually simpler, function is sought. In doing this it is customary to use the 'Big 0' notation; for example, 0(n2 ) means that the number of steps will be roughly proportional to the square of the number of samples in the worst case. Additional terms and multiplicative constants are not taken into account because a qualitative comparison is sought. This quadratic complexity is worse than say O(n) ( linear ) or 0(1) ( constant, independent of the length n), but is better than 0 (n3 ) ( cubic ) . If the complexity is exponential, e.g., 0(2n ) , then it often means that the algorithm cannot be applied to larger problems ( in practical terms ) . The Discrete Fomier Transform ( DFT ) , if it is computed from its definition for the samples discrctized into n samples, see equations (3.25), (3.26 ), has time complexity 0(n 2 ). The result can be calculated much faster if the Fast Fourier Transformation ( FFT) algorithm is used. This algorithm was proposed in the early 1940's, and depends on the nnmber of samples used to represent a signal being a power of two. The basic trick is that a DFT of length N can be expressed as a sum of two DFTs of length N/2 consisting of odd or even samples. This scheme permits the calculation of intermediate results in a clever way. The time complexity of the FFT is O ( n log n ) ; any signal processing textbook will provide details. As an example, consider a computer with I ns CPU cycle and a seqnence 107 samples long. The FFT would be calculated in approximately 0.23 second, and the DFT in more than a day. The FFT is implemented in many software tools and libraries.
3.2.4
2D Fourier transform
The ID Fourier transform can be easily generalized to 2D [Bracewell, 2004] . An image f is a function of two coordinates (:1: , y) in a plane. The 2D Fourier transform also uses harmonic functions for spectral decomposition. The 2D Fourier transform for the contilluous image f is defined by the integral F (u, v)
= -oc . J
(CJO j.CJO f(:c, y) e - 27ri(xu+yv) dx dy -
(3.27)
00
and its inverse transform is defined by
f(x, y) =
I: I: F(u, v ) e27ri(X1L+YV) du dv .
(3.28)
Parameters ( 11, v ) are called spatial frequencies. The function f on the left-hand side of equation (3.28) can be interpreted analogously to the ID case (sec equation ( 3. 18 ) ) , i.e., as a linear combination of simple periodic patterns e27ri(xv, +yv) . The real and imaginary components of the pattern arc cosine and sine functions. The complex spectrum F(u, v ) is a weight function which represents the influence of the elementary patterns.
3.2 Linear integral transforms
59
Equation (3.27) can be abbreviated to
F{J(x, y) } = F(u , v) . From the image processing point of view, the following properties ( corresponding to the 1D case ) are easily derived: •
•
Linearity:
F{a f1 (x , y) + b h (x , y) }
=
Shift of the origin in the image domain:
a F1 (u , v) + b F2 (u , v) .
F {J( x - a, y - b) } = F( v) c - 2 7ri(au+ bv) 11"
•
•
•
Shift of the origin in the frequency domain:
F { f(x , y) e2 7riCuO:L+ VOY) }
If f(x, y) is real-valued then
= F(u - uo , v
'00
-
.
)
(3.29) ( 3.30 )
.
( 3.31 )
F( -u , -v) = F* (u, v) .
(3.32)
The image function is always real-valued and we can thus Ui:>e the results of its Fourier transform in the first quadrant, i.e., u ;::: 0, v ;::: 0, without loss of generality. If in addition the image function has the property f(x , y) = f( -x , -V) then the result of the Fourier transform F( u , v) is a real function. Duality of the convolution: Convolution, equation ( 3 . 1 1 ) , and iti:> Fourier transform are related by
= F(u, v) H(u, v) , = (F * H) (u, v) .
F{ (f h)(x, y) } F{J(x , y) h(x, y) } *
This is the convolution theorem.
( 3.33 )
The 2D Fourier transform can be used for discrete images too : integration ii:> changed to summation in the respective equations. The discrete 2D Fourier transform ( spectrum) is defined as 1
F(u, v) =
MN
[ .(
Af - l N - 1
'" '" f(m, n) exp -271'2 mu � �
m=O n =O
JlI1
and the inverse Fourier transform is given by
m
=
N- 1
L L F(u, v) exp [ 271'i (rr;;
11,[ - 1 n=O
v= o
0, 1 , . . . , ]1.£
-
nOv
v = 0, 1 , . . . , N - 1 ,
u = 0, 1 , . . . , M - 1 , f(m, n) =
+N
1,
+
)]
;)] ,
n = 0, 1 , . . . , N - 1 .
( 3.34 )
( 3.35 )
Considering implementation of the dii:>crete Fourier transform, note that equation ( 3.34 ) can be modified to 1
F(u, v) = M
[ f
( ( 1 -271'inv ) -271'imu ) f(m, n) N M N; ...,M v= ...,N-
M- l
u = 0, 1 ,
o
1
N- 1
1,
exp
exp
0, 1 ,
1.
( 3.36 )
Chapter
60
3:
The image, its mathematical and physical background
The term in square brackets correspollds to the one-dimensional Fourier transform of the
mth line and can be computed using the standard fast Fourier transform (FIT) procedures (assuming N is a power of two). Each line is suhstituted with its Fourier transform, and
the one-dimensional discrete Fourier transform of each column is computed. Periodicity is an important property of the discrete Fourier transform. A periodic transform F is derived and a periodic function f defined F(u, -v) � F(u, N - v) , F(-u,v) � F(M - u, v) , and
F(aM + U,bN + v) = F(u, v) ,
!(-m,n) � f(M - m,n) , f(m, -n) f(m, N - n ) ,
(3.37)
f(aM + m,bN + n) = f(m,n) ,
(3.38)
=
where a and b are iutegers. The outcome of the 2D Fourier transform is a complex-valued 2D spectrum. Consider the input gray-level image (before the 2D Fourier transform was applied) with intensity values in the range, say, [0, . . . , 255J. The 2D spectrum has the same spatial resolution. However, the values in both rea! and imaginary part of the spectrum usually span a bigger range, perhaps millions. The existence of real and imaginary components and the range spanning several orders of magnitude makes the spectrum difficult to visualize and also to represent precisely in memory because too many bits are needed for it. For ea..<;ier visualization, the range of values is usually decreased by applying a mOllotonic function, e.g., vIF(",v)1 DC iog l F( u, v) l . It is also useful to visualize a centered spectrUIll, i.e., with the origin of the coordinate system (0,0) in the middle of the spectrum. This is because centering has the effect of placing the low frequency information in the center and the high frequencies near the comers-consider tile definition givell in equation (3.34). .A •
"
X (a)
-.
0 C
•
f
C 0
"
•
A
(b)
Figure 3.6: Centeri ng of the 2D fourier spectrum places the low frequencies around the coordinates origin. (a) Original spectrum. (b) Centered spcctrum with the low frequencies in the middle.
Assume the original spectrum is divided into four quadrants, see figure 3.6a. The slllall gra.y-filled squares in the corners represent po!;itions of low frequencies. Due to the symmetries of the spectrum the quadrant positions can be swapped diagonally and the low frequencies locations appear ill the middle of the image, see Figure 3.6b. The spectrum is demonstrated in Figure 3.8, an image of the Saint Vitns Cathedral, part of the Prague Castle. The original is of size 256 x 256 in 256 gray levels. Figure 3.7 illustrates the spectrum. The left image demonstrates the non-centered power spectrum and the right image the centered power spectrum. The latter option is ugcd more often. The range of the spectrum values ha... to be decreased to allow an obscrver to perceive the spectrum better; log P(u,v) is used here. For illustration of the particular range of this power spectrum, the pair of (minimum, maximum) for the P(u, v) is (2.4 . 10-1, 8.3 . 106) and the (minimum, maximum) for the log P(u,v) is (-0.62, 6.9).
3.2 Linear integral tr
61
..• .
.
r
i
1 150' •
• ,
-.• • •• ••
(.)
(b)
3.7: Power sp(.'ctrum displayed as an intensity image. Lighter toues mean higher values. (a) Non-centered. (b) Centered. A color version of this figUH� may be seen in the colo1' insct Plate 5. Figure
A quite distinct light cross can be Reen in the centered power spectrum on the right of Figure 3.9. This cross is caused by discontinuities on the limits of the image while assuming periodicity. These abrupt changes arc easily visible in Figure 3.8. The usc of the Fourier transform in image analysis is pervasive. We will see in Chapter 5 how it can assist in noise filtering, in the detection of edges by locating high frequencies (sharp changes) in the image function; it also has applications in restoring images from corruption (Section 5A.2), fast matching using the cOllvolution theorem (Section GA.l), boundary characterization (Scction 8.2.3), image compression (Chapter 14), and several other area.'i.
3.2.5
Sampling and the Shannon constraint
Equipped with understa.nding of the Fourier transform, we can now discuss more fully the surrounding sampling. A continuous image function f(x,y) can be sampled using
issues
Figure 3.8: Input. image in the spatial domain is flSSumed periodic. Notice induced discolltinuities on t.he borders of the image which manifl..'Sts badly in the Fourier spectrum.
62
Chapter 3: The image, its mathematical and physical background __
---"'-""''''1
..._ .. ... .'1.
'. -'-'
•
(.)
•
•
'. -_.
•
'.
-'-'
-_ .
(b)
Figure 3.9: Power spectrum dhspiayed as height in a 3D mesh; lighter tones mean higher values. (a) Non-centered. (b) Centered. A r-olor version of this figu� may be seen in the colQr in.yet-Plate 6.
a discrete grid of sampling points in the plane, but a second possibil ity is to expand the image fUliction using some orthonormal functions as a basis-the Fourier transform is an example·-and the coefficients of this expansion then represent the digiti�ed image. The image is sampled at point:; x = j Ax, y = k 6.y, for j = 1, . . . , M and k = 1, . . . , N Two neighboring sampling points are separated by distance 6.x along the x axis and 6.y along the y axis. Distances 6.x and 6.y are called the sampling intervals (on the x or y axis) , and the matrix of samples /(j Ax, k 6.y) constitutes the discrete image. Thc ideal sampling S(XIY) in the regular grid can be represented I.l$ing a collection of Dirac distributions 0 .
s(" , Y)
�
M
N
j=1
k=]
L L o(x - j t!.x, y - k t!.y) .
(3.39)
The sampled image f8(X,y) is the product of the continuous image sampling function s{:c ,y)
f(x,y)
and the
1.(x,1/) � I(x,y) ,(x,y) �
M
N
j=l
k=]
I(x, y) L L o(x - j t!.x, y - k t!.y) .
}
(3.40)
We may consider an infinite sampling grid which is periodic with periods Ax, Ay and expand the sampling into Fourier series. We obtain (see [Oppenheim et al., 19971) F
{j�OO= k�OO 00
H.
I
J (x - j 6.x , y - k 6.y) = Ax A U
00
00
m�oo ...�oo
0
(
U-
�
n v x' -
)
;y .
(3.41)
Equation (3.40) can be expressed in the frequency domain I.l$ing equation (3.41): (3.42)
3.2 Linear i ntegral transforms
63
Thus the Fourier transform of the sampled image is the sum of periodically repeated Fourier transforms F( u, v) of the image. We can demonstrate this effect in 1D case: assume that the maximal frequency of the signal is fm , so the signal is band-limited, meaning that its Fourier transform F is zero outside a certain interval of frequencies I f I > fm - The spectra will be repeated as a consequence of discretiJlation--see Figure 3.10. In the case of 2D images, band-limited means that the spectrum F(u, v) = 0 for I u I> U, I v I> V, where U, V are maximal frequencies.
Figure 3.10:
is 2: 2 fm .
000&000
�t: ([Hz] o /.. .I: 2f -f Repeated spectra of the ID signal due to sampling. Non-overlapped case when
Periodic repetition of the Fourier transform result F( u, v) may under certain conditions cause distortion of the image, which is called aliasing; this happens when individual digitized components F(u, v) overlap. Overlapping of the periodically repeated results of the Fourier transform F(u, v) of an image with band-limited spectrum can be prevented if the sampling interval is chosen such that 1
�x < 2U '
1
(3.43)
�'" < - . 11 2V
This is the Shannon sampling theorem, known from signal processing theory or control theory. The theorem has a simple physical interpretation in image analysis: The sampling interval should be chosen in size such that it is less than half of the smallest interesting detail in the image. The sampling function is not the Dirac distribution in real digitizers-limited impulses (quite narrow ones with limited amplitude) are used instead. Assume a rectangular sampling grid which consists of AI x N such equal and non-overlapping impulses h s (.T, y) with sampling period � x, � y; this function realistically simulates real image sensors. Outside the sensitive area of the sensor, hs (x , y) = O. Values of image samples are obtained by integration of the product f hs --ill reality this integration is done Oll the sensitive surface of the sensor elemellt. The sampled image is then given by fs ( x, y) =
N
!If
L L f (x, y) hs(x - j �x, y
j=l k=l
-
k �y) .
(3.44)
The sampled image f.. is distorted by the convolution of the original image f and the limited impulse hs . The distortion of the frequency spectrum of the function Fs can be expressed using the Fourier transform 1
00
L L 00
F Fs ( 1L, v) = � uX uy m=-oo n= - oo
(
n ) Hs ( rn n )
'lJ. - � , 'U - � rn
uX
uy
�, �
u X uy
(3.45)
where Hs = F{hs } . In real image digitizers, a sampling interval about ten times smaller than that indicated by the Shannon sampling theorem, equation (3.43), is used--this is because algorithms
64
Chapter 3:
The image, its mathematical and physical background
(b)
(d)
« )
3.11: Digitizing. (a) 256 x 256. (b) 128 x 128. (c) 64 been enlarged to till! samc size to illustrate the JO�iS of detail. Figure
x
64. (d) 32 x 32. Images havc
which reconstmct the continuous image on a display from the digitized image function use only a step functiolJ, i.e., a line in the image is created from pixels represented by individual squares. A demonstration with an image of 256 gray-levels will illustrate the effect of sparse sampling. Figure 3.11a shows a monochromatic image with 256 x 256 pixels; Figure 3.11b shows the same scelle digitized into a reduced grid of 128 x 128 pixels, Figure 3.l1c into 64 x 64 pixels, and Figure 3.11d into 32 x 32 pixels. Decline in image quality is clear from Figures .3.11a--d. Quality may be improved by viewing from a distance and with screwed-up eyes, implying that the uuder-sampled images still hold substantial information. Much of this visual degradation is caused by aliasing in the reconstruction of the continuous image function for display. This can be improved by the reconstruetion algorithm interpolating brightness values in neighbming pixels and this technique is called anti-aliasing; this is often used in computer graphics [Rogers, 1985]. If anti-aliasing is used, the sampling interval can be brought near to the theoretica1 value of Shannon's
3.2 Linear integral transforms
65
theorem [equation (3.43)]. In real image processing devices, anti-aliasing is rarely used because of its computational requirements.
3.2.6
Discrete cosine transform
The discrete cosine transform (DCT) is a linear integral transformation similar to the discrete Fourier transform (DFT) [Rao and Yip, 1990] . In 1D, cosines with growing frequencies constitute the basis functions used for function expansion: the expansion is a linear combination of these basis cosines, and real numbers suffice for such an expansion (the Fourier transform required complex numbers) . The DCT expansion corresponds to a DFT of approximately double length operating on a function with even symmetry. Similarly to the DFT, the DCT operates on function samples of finite length, and a periodic extension of this function is needed to be able to perform DCT (or DFT) expansion. The DCT requires a stricter periodic extension (a more strict boundary condition) than the DFT-it requires that the extension is an even function. Two options arise in relation to boundary conditions for a discrete finite sequence. The first one is whether the function is even or odd at both the left and right boundaries of the domain, and the second is about which point the function is even or odd. As illustration, consider an example sequence w.'Eyz. If the data are even about sample w, the even extension is zyxwxyz. If the sequence is even about the point halfway between w and the previous point, the extension sequence is that in which w is repeated, i.e., zyxwwxyz. Consider the general case which covers both the discrete cosine transform (with even symmetry) and the discrete sine transform (with odd symmetry). The first choice has to be made about the symmetry at both left and right bounds of the signal, i.e., 2 x 2 = 4 possible options. The second choice is about which point the extension is performed, also at both left and right bounds of the signal, i.e., an additional 2 x 2=4 possible options. Altogether 4 x 4=16 possibilities are obtained. If we do not allow odd periodic extensions then the sine transforms are ruled out and 8 possible choices remain yielding 8 different types of DCT. If the same type of point is used for extension at left and right bounds then only half the options remain, i.e., 8/2=4. This yields four basic types of DCT-·they are usually denoted by suffixing Roman numbers as DCT-I, DCT-II, DCT-III, DCT-IV .
. . Jll l lil nnulWIlj�UIl l l li.. . o
10
Illustration of the periodic extension used i n DCT-ll. The input signal o f length 1 1 i s denoted by squares. Its periodic extension is shown as circles. Courtesy of Wikipedia. Figure 3 . 1 2 :
We choose DCT-II because it is the most commonly used variant of DCT in image processing, mainly in image compression (Chapter 14). The periodic extension is even at both left and right bounds of the input sequence. The sequence is even about the point halfway between the bound and the previous point: the periodic extension for the input sequence is illustrated in Figure 3.12. The figure demonstrates the advantage of periodic extension used in DCT-II-mirroring involved in periodic extension yields
Chapter 3: The image. its mathematical and physical background
66
a smooth periodic function, which means that fewer cosines are needed to approximate the signal. The DCT can easily be generalized to two dimensions which is shown here for the square image, M = N. The 2D DCT-II is [Rao and Yip, 1990]
F(u, v) where u
=
( 2 c ( u) c v) N
= 0, 1,
...,N
-
� � f(m, n) ( 2m N-l N-l
1, v = 0, 1, . . . , N
1
U7r
) ( 2n
+
1
cos 2NV7r
)
(3.46)
1 and the normalization constant c(k) is for k = 0 , otherwise.
� � c(u) c(v) F(u, v) cos ( 2�N+ 1 U7r ) cos ( 2'�� 1 V7r)
The inverse cosine transform is 2 N
{�
-
+
2N
.
c(k) =
f(m, n) =
cos
N-l N-l
(3.47)
where m 0, 1, . . . , N 1 and n = 0, 1, . . . , N l . There is a computational approach analogous to the FFT which yields computational complexity in the 1D case of O ( N log N ) , where N is the length of the sequence. Efficacy of an integral transformation can be evaluated by its ability to compress input data into as few coefficients as possible. The DCT exhibits excellent energy compaction for highly correlated images. This and other properties of the DCT have led to its widespread deployment in many image/video processing standards, for example, JPEG ( classical ) , MPEG-1, MPEG-2 , MPEG-4, MPEG-4 FGS, H.261, H.263 and JVT (H .2 6L ) . =
3.2.7
-
-
Wavelet transform
The Fourier transform ( Section 3.2.3) expands a signal as a possibly infinite linear combination of sines and cosines. The disadvantage is that only information about the frequency spectrum is provided, and no information is available on the time at which events occur. In another words, the Fourier spectrum provides all the frequencies present in an image but does not tell where they are present. We also know that the relation between the frequency and spatial resolutions is given by the uncertainty principle, Equation (3.24). One solution to the problem of localizing changes in the signal ( image) is to use the short time Fourier transform, where the signal is divided into small windows and treated locally as it were periodic ( as was explained in Section 3.2.3) . The uncertainty principle provides guidance on how to select the windows to minimize negative effects, i.e., windows have to join neighboring windows smoothly. The window dilemma remains-a narrow window yields poor frequency resolution, while a wide window provides poor localization. The wavelet transform goes further than the short time Fourier transform. It also analyzes the signal ( image ) by multiplying it by a window function and performing an orthogonal expansion, analogously to other linear integral transformations. There are two directions in which the analysis is extended. In the first direction, the basis functions ( called wavelets, meaning a small wave, or mother wavelets) are more complicated than sines and cosines. They provide localization
3.2 Linear integral transforms
(a) Haar
(c) Morlct
(b) Meyer Figure 3.13:
(d) Daubcchies-4
67
(e) Mexican hat
Qualitative examples of mother wavelets.
in space to a certain degree, not entire localization due to the uncertainty principle. The shape of five commonly used mother wavelets is illustrated in Fig1ll'e 3.13 in a qualitative manner and in a single of lIlany scales; due to lack of space we do not give the formulas for these. In the second direction, the analysis is performed at multiple scales. To understand this, note that modeling a spike in a function (a noise dot, for example) with a sum of a huge number of functions will be hard because of the spike's strict locality. Functions that are already local will be naturally suited to the task. This means that such functions lend themselves to more compact representation via wavelets -sharp spikes and discontinuities normally take fewer wavelet bases to represent as compared to the sine-cosine basis functions. Localization in the spatial domain together with the wavelet's localization in frequency yields a sparse representation of many practical signals (images). This sparseness opens the door to successful applications in data/image compression, noise filtering and detecting features in images. We will start from the ID and continuom; case--thc so called 1D continuous wavelet transform. A function f(t) is decomposed into a set of basis functions W- -wavelets
(;(8, T) =
l f(t) W:.r (t) dt ,
8 E R+ - {O} ,
TER
(3.48)
(complex conjugation is denoted by ) The new variables after transformation are 8 (scale) and T (translation) . Wavelets are generated from the single mother wavelet w(t) by sca.ling 8 and translation T t-T 1 Ws.r. (t) = r;. W (3.49) . 8 VS *
.
(-)
The coefficient I/.;s is used because the energy has to be normalized across different scales. The inverse continuous wavelet transform serves to synthesize the 1D signal f(t) of finite energy from wavelet coefficients C(8, T)
f(t) = r r c(s, T) Ws,r(t) d8 c1T . JR+ JR
(3.50)
The wavelet transform was defined generally in equations (3.48)-(3.49) without the need to specify a particular mother wavelet: the user can select or design the basis of the expansion according to application needs. There are constraints which a function W s,r must obey to be a wavelet, of which the most important are admissibility and regularity conditions. Admissibility requires that
68
Chapter 3: The image, its mathematical and physical background
the wavelet has a band-pass spectrum; consequently, the wavelet must be oscillatory a wave. The wavelet transform of a 1D signal is two dimensional as can be seen from equation (3.48), and similarly, the transform of a 2D image is four dimensional. This is complex to deal with, and the solution is to impose an additional constraint on the wavelet function which secures fast decrease with decreasing scale. This is achieved by the regularity condition, which states that the wavelet function should have some smoothness and concentration in both time and frequency domains. A more detailed explanation can be found in, e.g. , [Dallbechies, 1992] . We illustrate scaling and shifting on the oldest and the most simple mother wavelet, the Haar wavelet, which is a special case of the Dallbechies wavelet. Scaling functions are denoted by
=
i) , i = 0, . . , 2j - 1 , where
(3.51 )
for 0 ::; x < 1 , o otherwise.
(3 5 2 )
{I
2j/2
=
.
.
and 2j/2 is a normalilmtion factor. The example of four instances of scaling function which constitute a basis of the appropriate vector space are shown in Figure 3.14.
:� :� :Lrr: :r:u o
0.5
o
1 x
0.5
Figure 3 . 1 4:
1 x
o
0.5
I
'I3ox-like' scaling functions
x
o
0.5
I
x
The wavelets corresponding to the box basis are called the Haar wavelets and are given by (3.53) W i (:r: ) = 2)/2 W (2jx - i ) , i = 0, . . , 2j - 1 , where j w (x) �
H
ftr-; I �
.
for 0 ::; x < � for � ::; x < 1 otherwise,
,
(3.54)
,
and 2.i /2 is a normalization factor. The example of Ham wavelets W 1 1 , W 1 2 is given in Figure 3.15. The transform which uses Haar wavelets is called the Haar transform. I
o
-I
0.5
W
1 x
-
o I
0.5
1
\}III x
Figure 3 . 1 5 :
Haar wavelets
w u , W1 2 .
Returning t o the general wavelet transform, i t is not practical to use equation (3.48) for computation for three reasons: •
There is much redundancy because the calculation is performed by continuously scaling the mother wavelet, shifting it and correlating it with the analyzed signal.
69
3.2 Linear integral transforms • •
The intention is to reduce the infinite number of wavelets taking part in calculations. The final result of the transform is not possible to calculate analytically. Moreover, an efficient numerical solution is needed which would be of comparable complexity to, e.g., the FFT.
The solution is the discrete wavelet transform. If the scales and positions are based on a power of two (dyadic scales and positions) then the wavelet analysis becomes much more computationally efficient and just as accurate. Mallat [Mallat, 1989J developed an efficient way to calculate the discrete wavelet transform and its inverse. The scheme is actually a variant of the classical scheme--a two-channel sub-band coder-known in signal processing. This method yields a fast wavelet transform which can be imagined as a box into which a signal (an image) enters and the wavelet coefficients c appear quickly at its output. Consider a discrete 1D signal s of length N which has to be decomposed into wavelet coefficients c. The fast wavelet transform consists of log2 N steps at most. The first decomposition step takes the input and provides two sets of coefficients at level 1: approximation coefficients CAl and detail coefficients cDl . The vector s i s convolved with a low-pass filter for approximation and with a high-pass filter for detail. Dyadic decimation follows which down samples the vector by keeping only its even elements. Such down sampling will be denoted by 1 2 in block diagrams. The coefficients at level j + 1 are calculated from the coefficients at level j analogously, see Figure 3.16. This procedure is repeated recursively to obtain approximation and detail coefficients at further levels. The structure of coefficients for level j = 3 is illustrated in Figure 3. 17. cAl
levelj
low pass filter high pass filter
Figure 3.16: A single decomposition step of the ID discrete wavelet transform consists of the convolution of coefficients from previous level j by a low/high pass filter and down sampling by dyadic decimation. Approximation and detail coefficients at level j + 1 are obtained.
cD, cA , Figure 3.17: Example illustrat ing the structure of approximation and detail coefficients for levels up to a level j = 3.
The inverse discrete wavelet transform takes as an input the approximation coefficients
cAj and detail coefficients cDj and inverts the decomposition step. The vectors are
extended (up sampled) to double length by inserting zeros at odd-indexed elements and convolving the result with the reconstruction filters. Analogously to down sampling, up sampling is denoted i 2 in the block diagram which illustrates 1D inverse discrete wavelets transformation pictorially, Figure 3.18. Similar wavelet decomposition and reconstruction algorithms were developed for 2D signals (images) . The 2D discrete wavelet transformation decomposes a single approxima tion coefficient at level j into four components at level j + 1: the approximation coefficient cAj + l and detail coefficients at three orientations--horizontal cDj'+ ! , vertical cDj+l and diagonal eDt+ !. Figures 3.19 and 3.20 illustrate the 2D transform. The symbol coI l 2 stands for down sampling columns by keeping only the even indexed columns.
70
Chapter
3:
The image, its mathematical and physical background high pass filter low pass filter
reconstruction filter
level j
levelj
-
Figure 3.18:
l
ID discrete inverse wavelet transformation.
Similarly, row 1 2 meallS down sampling rows by keeping only evenly indexed rows. The symbol col T 2 stands for up sampling columns by inserting zeros at odd-indexed columns. Similarly, row T 2 means up sampling rows by inserting zeros at odd-indexed rows. Figure 3.21 illustrates the decomposition of the previolls example-this was computed with the MATLAB Wavelet toolbox. The resolution of levels 2 and 3 is insufficient qualitatively to see the character of wavelet coefficients. Figure 3.22 shows the same data for all three levels in a different form. The wavelet transform which has been discussed so far is a special case of a more versatile wavelet packet transform. Wavelet packets are particular linear combinations columns low pass filter rows
low pass tilter
columns high pass filter columns low pass filter columns high pass filler
level)
level)+!
Figure 3 . 1 9 :
2D discrete wavelet transform. A decomposition step.
Icvc!j-'- j
Icvclj Figure 3.20:
2D inverse discrete wavelet transform. A reconstruction step.
3.2 linear integral transfOl'ms
71
Figure 3.21: Decomposition by the 2D discrete wavelet t.ransform. The Haar wavelet was used, and dC(;omposition to three levels performed. On the left is tile original 256 x 256 gray-scale image, and Oli the right four qultdrants. The undivided southwestern, southeastern and northeastern quadrallts correspond to detailed coefficients of level 1 at resolution 128 x 128 ill vertical, diagonal and horizontal directions, respectively. The lIorthwesteru quadrant displays the same structure for level 2 at resolution 64 x 64 pixels. The northwestern quadrant of level 2 fihows the same structure at level 3 at resolution 32 x 32 pixelfi. Tile lighter intensity 32 x 32 image ill top left corner corresponds to approximation coefficients at level 3.
>\1l111""O�iIl13rions
lIori:WIIIHt
l}(ol..ils
\"l'rric�t
Udails
Figure 3.22: 2D wavelet decomposition; another view of the same data as ill Figure 3.21.
72
Chapter 3: The image, its mathematical and physical background
of wavelets which retain many of the locali�ation, smoothness and orthogonality properties of their parent wavelets. The coefficients in linear combinations arc again calculated in a recursive way. Using discrete wavelets, only the detail branch of the decomposition tree is split, but both detail and approximation branches can be split in wavelet packet analysis. Applications have proved the value of the approach. Wavelets have been used with enormous success in data compression, feature detection and in image noise suppression it is possible to erase to zero the contribution of wavelet components that are 'small' and correspond to noise without erasing the important small detail in the underlying image. The interested reader is referred to specialized texts for a fuller exposition on this topic [Chui, 1992; Daubechies, 1992; Meyer, 1993; Chui et al., 1994; Castleman, 1996J.
3.2.8
Eigen-analysis
Many disciplines, including image analysis, seck to represent observations, signals, images and general data in a form that enhances the mutual independence of contributory components. Linear algebra provides very appropriate tools for such representations. One observation or measurement is assumed to be a point in a linear space; this space will have some 'natural ' basis vectors which allow data to be expressed as a linear combination in a new coordinate system consisting of orthogonal basis vectors. These basis vectors are the eigen-vectors, and the inherent orthogonality of eigen-vectors secures mutual independence. For an n x n square regular matrix A, eigen-vectors are solutions of the equation A x = AX , (3.55) where A is called an eigen-value (which may be complex). We will review eigen-analysis from linear algebra which approaches the task from a deterministic standpoint, and in a later section, we will develop a statistical view based on covariance matrices and principal component analysis. A system of linear equations can be expressed in a matrix form as Ax = b, where A is the matrix of the system. The extended matrix of the system is created by concatenating a column vector b to the matrix A, i.e. , [Al b] . Frobenius' theorem (known in linear algebra) says that this system has a unique solution if and only if the rank of the matrix A is equal to the rank of the extended matrix [AlbJ . If the system of equations is not degenerate then it has as many equations as unknown variables x = ( X l , . . . , Xn ) T and the system has a unique solution. Gaussian elimination is the commonly used method to solve such a system. The method performs equivalent transformations of [AlbJ which do not change the solution of the system of equations, and the extended matrix is finally expressed in upper triangular form. When the elimination is finished, the last row of the matrix provides the solution value of :Cn- This solution allows the stepwise calculation of Xn- l , . . . , X l ' There is another class of matrix transformation called similar transformations. Let A be a regular matrix: matrices A and B with real or complex entries are called similar if there exists an invertible square matrix P such that p- l A P B. Similar matrices share many useful properties -they have the same rank, determinant, trace, characteristic polynomial, minimal polynomial and eigen-values (but not necessarily the same eigen-vectors) . Similarity transformations allow us to express regular matrices in several useful forms.
=
3.2 Linear integral transforms
73
Let I be the unitary matrix having values 1 only on the main diagonal and zeros elsewhere. The polynomial of degree n given as det(A AI) is called the characteristic polynomial. Then the eigen-equation (3.55) holds if det(A AI) = O. The roots of the characteristic polynomial are the eigen-values A. Consequently, A has n eigen-values which are not necessarily distinct-multiple eigen-values arise from multiple roots of the polynomial. Here we will be interested in the Jordan canonical form. Any complex square matrix is similar to a matrix in the Jordan canonical form -
-
[: ,;,]
, where Ji are Jordan blocks
A1.'
1
0
0
Ai
0
0 0
0 0
1
(3.56)
Ai
and A'i are the multiple eigen-values. The multiplicity of the eigen-value gives the size of the Jordan block. If the eigen-value is not multiple then the Jordan block degenerates to the eigen-value itself. This happens very often in practice. Consider the case when the linear system is over-constrained, meaning that there are more equations than variables to be determined; this case is very common in practice, when abundant data comes from many observations or measurements. Strictly speaking, the observations are likely to be in contradiction with respect to the system of linear equations. In the deterministic world, the conclusion would be that the system of linear equations has no solution, but the practical need is different. There is an interest in finding the solution to the system which is in some ilenile 'closest ' to the observations, perhaps compensating for noise in observations. We will usually adopt a statistical approach by minimizing the least square error. This leads to the principal component analysis method, explained in Section 3.2.10. Seeking roots of the characteristic polynomial is usually rather poor computationally, and more effective methods such as singular value decomposition (SVD) are used.
3.2.9
Singular value decomposition
Eigen-values and eigen-vectors are defined on square matrices; a generalization--singular values- -operatcs on rectangular matrices, and is approached via the singular value decomposition (SVD ) . A non-negative real number (J iil a singular value of a matrix A (not necessarily ilquare) if and only if there exist unit-length vectors 'U and v such that2 A v = (J 'U and A * 'U =
(J V .
Note the similarity to the cigen-equation (3.55). The vectors 'U and v are called left singular and right-singular vectors for (J, respectively. SVD is a powerful linear algebra factorization technique of a rectangular real or complex matrix; it works even for singular or numerically near-singular matrices. SVD is used with many applications for solving linear equations in the least-square sense, e.g., in signal processing and statistics. It can be viewed as a generalization of the 2 For a matrix A, A* will be the conjugate transpose ( also called the adjoint) which is the transpose of the complex conjugate of A.
74
Chapter
3:
The image, its mathematical and physical background
transformation to the Jordan canonical form to arbitrary, not necessarily square, matrices. Basic information necessary to use SVD can be found in many texts: for example, [Press et al., 1992] and Wikipedia, and a rigorous mathematical treatment is given in [Golub and Loan, 1989] . Most software packages for numerical calculations such as MATLAB contain SVD. SVD proceeds by noting that any Tn x n matrix A, Tn 2:: n, (with real or complex entries) can be decomposed into a product of three matrices, A = U D VT , (3.57) where U is Tn x 'Tn with orthonormal columns, D is a non-negative diagonal matrix, and VT has orthonormal rows. SVD can be understood as decoupling input of size Tn into output of size n. The matrix V contains a set of orthonormal 'input' or basis vector directions (left-singular vectors) for the matrix A, and the matrix U contains a set of orthonormal 'output ' basis vector directions (right-singular vectors) for A. The matrix D contains the singular values, which can be understood as scalar 'gains' by which each corresponding input is multiplied to give the corresponding output. It is cOllventional to reorder the input and output values to have the diagonal entries of the diagonal matrix D non-increa.sing, making D uniqne for any given A. The matrices U and V are not unique in general. There is a relation between singular values and vectors, and eigen-values and vectors. In the special case, when A is Hermitian (also self-adjoint, A = A * ) , all eigen-values of A are real and non-negative. In this case, the singular values and singular vectors coincide with the eigen-values and eigen-vectors, A = V D V* . SVD can be used to find a solution of a set of linear equations corresponding to a singular matrix that has no exact solution -it locates the closest possible solution in the least-square sense. Sometimes it is required to find the 'closest ' singular matrix to the original matrix A �this decreases the rank from n to n 1 or less. This is done by replacing the smallest diagonal element of D by zero--this new matrix is closest to the old one with respect to the Frobenius' norm (which is calculated as a sum of the squared values of all matrix elements). SVD is very popular also because of its numerical stability and precision [Press ct al. , 1992]. -
3.2.10
P rincipal component analysis
Principal component analysis (PCA) is a powerful and widely used linear technique in statistics, signal processing, image processing, and elsewhere. It appears under several names: it is also called the (discrete) Karhunen-Loeve transform (KLT, after Kari Karhunen and Michael Loeve) or the Hotelling transform (after Harold Hotelling) . In statistics, PCA is a method for simplifying a multidimensional dataset to lower dimensions for analysis or visualization. PCA is a linear transform that represents the data in a new coordinate system in which basis vectors follow modes of greatest variance in the data: it is the optimal linear transformation which divides an observed space into orthogonal subspaces with the largest variance. Thus, new basis vectors are calculated for the particular data set. One price to be paid for PCA's flexibility is in higher computational requirements as compared to, e.g., the fast Fourier transform. As it produces dimensionality reduction, PCA can be used for lossy data compres sion while retaining those characterif:,tics of the dataset which contribute most to its
3 . 2 Linear
integral
transforms
75
variance. p eA transforms a number of possibly correlated variables into the same number of uncorrelated variables called principal components. The first principal component accounts for as much of the variability in the data as possible, and each succeeding component accounts for as much of the remaining variability as possible. If the dataset has to be approximated in a lower dimension then lower-order principal components are considered and higher-order ones are omitted. Suppose a data set comprising N observations, each of AI variables ( dimensions ) . Usually N » NI. The intention is to reduce the dimensionality of the data so that each observation can be usefully represented with only L variables, 1 :::; L < A1 . Data are arranged as a set of N column data vectors, each representing a single observation of AI variables: the n-th observations is a column vector Xn = ( X l , ' " , X A f ) T , n = 1 , . , N. We thus have an NI x N data matrix X. Such matrices are often huge because N may be very large: this is in fact good, since many observations imply better statistics. This procedure is not applied to the raw data R but to normalized data X as follows. The raw observed data is arranged in a matrix R and the empirical mean is calculated along each row of R. The result is stored in a vector u the elements of which are scalars .
'IL(m) =
N L R(m, n) , N 1
n= 1
where m = l , . . . , M .
.
(3.58)
The empirical mean is subtracted from each column of R: if e is a unitary vector of size N ( consisting of ones only ) , we will write X = R - ue . Y
If we approximate X in a lower dimensional space 111 by the lower dimensional matrix of this approximation is given by
( of dimension L ) , then the mean square error c2
(3.59 ) where bi , = 1 , . . , L are basis vector of the linear space of dimension L. If c 2 is to be minimized then the following term has to be maximized
i
.
L
L bJ i= l
cov (x ) bi ,
where cov ( x ) =
N L Xn x� ,
n= l
is the covariance matrix. The covariance matrix cov (x ) has special properties: it is real, symmetric and positive semi-definite and so can be guaranteed to have real eigen-values. Matrix theory tells us that these may be sorted ( largest to smallest ) and the associated eigen-vectors taken as the basis vectors that provide the maximum we seek. In the data approximation, dimensions corresponding to the smallest eigen-values arc omitted. The mean square error c2 of equation (3.59) is given by c
2
= trace ( cov (x ))
L
- L Ai i= l
=
A!
L Ai ,
i =L+ l
Chapter 3: The image, its mathematical and physical background
76
where tracc(A) is the trace-sum of the diagonal elements--of the matrix equals the slim of all eigenvalues.
A.
The trace
As an example, consider the use of PCA on images-this approach was popularized by the application of PCA to face recognition (Turk and Pentland, 19911. The image is considered as a very long 10 vector by concatellat.ing image pixels column by column (or alternatively row by row) . Figure 3.23 is an example where the image is 321 x 261 = 83781 pixels 'long'. In this example, we have 32 examples of this long vector (this is contrary to the discussion above in which the number of examples is expc'Cted to exceed the dimensionality) . If we have fewer obselvations than unknowns, the systcm o f linear equations i s not over-constrained but PCA is still applicable. The number of principle components is less than or equal to the number of observations available; thifl is because the (square) covariance matrix has a size corresponding to the number of obflervations. The eigen vectors we derive are called
eigen-images,
after rearranging back from the
ID
vector to
a rectangular image.
Figure 3.23: 32 original images of a boy's face, each 321 x 261 pixels.
One image is treated as a single point (a single observation) in a high-dimensional fea.ture space. The set of images analyzed populates only a tillY fraction of the feature space. Considering Figure 3.23, Hote that the images were geometrically aligned; this wa.s done manually by cropping to 321 the same pixeL
x
261 and approximately positioning the nose tip to
PCA applied to images hru:; also drawbacks. By rearranging pixels column by columll to a
ID vector,
relations of !\ givclI pixel to pixels in llcighboring rows are not taken into
account. Another disadvantage
s i
ill the global nature of the representation; small change
or error in the input images infiuences the whole eigen-representation. However, this property is inherent in all linear integral transforms. A more detailed treatment of PCA
3.3 Images as stochastic processes
+ q, Figure 3.24:
+ q,
+ q,
Reconstruction or the image from four basis vectors hi,
displayed as images. The linear combination was computed as q,b1 O.078b]
+ O.062hz - O. 182b3 + O.179b1.
applie<J to illlages can be found in [Leonardis and Bischof, four basis vectors is shown in Figure
3.2.11
3.24.
77
2000].
i = 1, . . . , 4 which can be + (/�bz + f/3hJ + q4b4 =
The reconstruction from
Note that basis vectors are images.
Other orthogonal image transforms
Many other orthogonal image t.ransforms exist. The
Hadamard-Haar transform
is a
combination of the Haar and Hadamard transforms, and a modified Hadamard-Haar
Slant transform a.nd its modification the Siant-Haar transform slant base vectors; a fast algorithm is also available. The discrete sine transform is very similar
transform is similar. The
repr(.>sent 31l0ther trallsform conhdning S<1.wtooth waveforms or computational
to the discrete cosine transform. All transforms mentioned here are discussed in detail in [Gonzalez and Woods, 1992; Barrett and Myers,
2004], where references
for computational
algorithms call also he foulld. The Paley and
Walsh transforms
are both very similar to the Hadamard transform,
using matrices consisting of ±1 elements only. Details can be found in [Gonzalez and Woods,
1992].
Tbe significance of image reconstruction from projections can be seen in computer tomography (CT), magnetic resonance imaging (MRI), positron emission tomography (PET), astronomy, holography, etc. In these a.pplications the image formation can be modeled using the
Radon
transform [Bracewell, 1995; Barrett and Myers,
20041.
In
image reconstruction, projections in different directions are acquired by sensors and the two-dimensional image must be reconstructed. The inverse Radon transform is of particular interest. The main Radon inverse transform techniques are based on Fourier transforms, convolution, or algebraic formulations. Note that the Hough transform (sec Section
3.3
6.2.6)
has been show n to be an adaptation of the Illore general Radon transform.
Images as stochastic processes
Images are st.atist.ieal in nature due to random changes and noise, and it is sometimes of advantage to treat image functions as realizations of a stocbastic process [Papoulis, 1991; Barrett and Myers,
2004].
In such an approach, questions regarding image information
content and redundancy can be answered using probability distributions, and simplifying probabilistic characterizations as the mean, dispersion, correlation functions, etc. A
stochastic process
(random process, random field) is a generalization of the
random variable concept. We will constrain ourselves to stochastic processes of with two
independent va.riables
x, y which are the coordinates in the image.
We denote a stochastic
process by ¢ and ¢(x,y) is a random variable representing the gray�level at pixel
(x,y) .
78
C hapter 3:
The image. its mathematical and physical background
A specific image is obtained as a realization of the stochastic proce&<; ¢ and it is a real deterministic function f which provides the gray�level values which the image finally has. We illustrate the notion of an image as the realization of a stochastic process on an example. The original input image was the image of Prague Castle, Figure 3.11(a}. Figure 3.25 illustrates three of many pO$Sible rea1izations of a stochastic process ¢. 111 this example, the realizations were generated artificially from the input image by corrupting images with Gaussian noise with zero mean and standard deviation 0.1 in the scale of [0, 1]. The noise at each pixel is stltt.istically independent of noise at other pixels. After realizations are created, each image is deterministic. However, the corresponding pixels ill images arc three different realizations of thc same stochastic process. There are dependencies among brray-level valucs of pixcls in the same image. The exact description of these depcnrlcncies would mqnire a finite and extremely large number of joint distribution functions. A stochastic process f is entirely described by a collection of k�dimensiollltl distri bution functions Pk, k = 1 , 2 , . . The distribution fuuctiou of k arguments ZI , · · . ,Zk i, Pk(Zl , . . . , Zk; XI, y" . . . ,Xk, yi,;) = P{ ¢(XI' yd < Zl, .;t>(X2, 1/2) < Z:/, . . . , .;t>(Xk, Yk) < zd ' (3.60) where P denotes the probability of the conjunction of events listed in the brackets. The above equation expresses the dependence of k pixels (XI, y,), . . , (Xb Yk). For a complete probabilistic description, we would need these joint distribution functions for k equal to the number of pixels in the image. .
Figure 3.25: Three 256 x 256 images are shown
of these crop
as
realizations of a stochastic process ¢ in the
windows is marked by the white squares in the three images. The content willdows is clllargcd in three images below. Notice that pixels really differ in the
upper row. The crop
same locations in three realizations.
3.3 Images as stochastic processes
79
The probability distributions of order k are not used in practice. They express a complex relation among many events. These descriptors are of theoretical importance and would need very many realizations ( experiments ) to be estimated. Most often, not more than a pair of events is related. The second-order distribution function is used to relate pairs of events. Even simpler characterization of the stocha.<-;tic process is the first-order distribution func tion which expresses probabilistic properties of the gray-level value of a single pixel independently of the others. The probabilistic relations described by the distribution function P1 (z ; X, y) can be equivalently expressed using the probability density defined as Pl (z; :r , y) =
oP1 (z ; x, y) oz .
(3.61 )
The distribution is often roughly represented by simple characteristics. The mean of the stochastic process ¢ is defined using the first-order probability density by the equation fl·¢ (X, y)
= E{ ¢(:r, } = L: y, )
z PI (z; X, y) dz ,
(3.62)
where E is the mathematical expectation operator. The autocorrelation and cross correlation functions [Papolllis, 1991] are often used in searching for similarities in images or image parts. The autocorrelation function R¢¢ of the random process ¢ is defined as a mean of the product of the random variables ¢(X I , YI ) and ¢(X2 ' Y2 )
(3.63) The auto covariance function G¢¢ is defined as
(3.64) The cross correlation function R,/ry and cross covariance function G,/ry nse similar definitions to equations (3. 6 3) and (3. 6 4). The only difference is that a point from one image ( process ) ¢( :J:l , yI ) is related to a point from another image ( process) "Y( X2 , Y2 ) . Two stochastic proeesses are uncorrelated if their cross covariance function equals zero for any two points (:J:l , Y1 ) , (X2, Y2) . A stationary process is a speeial stoehastic process. Its properties are independent of absolute the position in the image plane. The mean fl'! of a stationary process is a constant. The autoeorrelation function R¢¢ of a stationary stochastic process is translation invariant and depends only on the difference between co-ordinates a X l - X2, b = Yl - Y2 : R¢¢ (Xl , YI , :J:2 , Y2 ) = Rq,
=
=
==
Rq,q, (a , b) ,
L: L: ¢(x + a, y + b) ¢(x , y) dx dy .
(3.65)
Similarly, the cross correlation function between samples of processes ¢(X I , y d and , (X2 , Y2) is defined as
80
Chapter 3: The image, its mathematical and physical background
Rq,"((a, b)
= L: L: (
¢ x + a, y + b) , ( x, y ) dx dy .
(3.66)
Note that infinitely many functions have the same correlation function and therefore the same power spectrum as well. If an image is shifted then its power spectrum remains unchanged. Let , ( x, y ) be the result of the convolution of the functions ¢ ( x, y ) and T) ( x, y ) , Equation (3.11 ). Assume that ¢ ( x, y ) , , ( x, y ) are stationary stochastic processes and Sq,q" S"("( are their corresponding power spectral densities. If the mean of the process ¢ ( x, y ) is zero, then
(3.67) where S'f}'f} (u, v) is the power spectrum of the stochastic process T) (x, y ) . Equation (3.67)
is used to describe spectral properties of a linear image filter T). The properties of correlation functions of stationary processes are interesting after a transform into the frequency domain. The Fourier transform of the cross correlation function of a stationary stochastic process can be expressed as the product of the Fourier transforms of involved processes ( images in image analysis ) ,
F { Rq,"( (a, b) } = F * ('u, v ) G (u, v) .
(3.68)
The notation P* denotes a complex conjugate of the function P. Similarly, the autocor relation function can be written as
F { Rq,q, (a, b) }
= P* (u, v) P(u, v)
=
2
I p(u , v ) 1 .
(3.69)
The Fourier transform of the autocorrelation function, equation (3.65) , is given by the following expression-the result is called the power spectrum3 or spectral density.
Sq,q, (u, v) =
L: L: Rq,q, (a, b)
e-21fi( a u+ bv)
da db ,
(3.70)
where u , v are spatial frequencies. The power spectral density communicates how much power the corresponding spatial frequency of the signal has.
3.4
I mage formation physics
Humans, using their eyes, comprehend intensities and colors in a relative sense as they compare within an image, while the camera can be used as a measuring device which is able to provide absolute measurements. If we want to understand the quantities measured, then we have to look at the physical principles of image formation. We will survey some basic concepts and principles to be able to understand how an image is created. These principles are straightforward and easy to explain; they are widely used in computer graphics to create visually appealing 2D images from 3D models. Unfortunately, the inverse task is under-constrained; having as input the observed image intensities and aiming at determination of physical quantities such as light sources ( their types, radiance, direction ) , shapes of surfaces in the scene, surface reflectance, and 3 The concept of power spectrum can also be defined for functions for which the Fourier transform is not defined.
3.4 I m age formation physics
81
direction to the viewer is difficult. This inverse task is of prime interest in computer vision. Because of its complexity, practitioners often try to avoid its solution by finding a shortcut in segmenting objects corresponding to some semantically appealing entities in the scene. The price they have to pay for this approach is the loss of generality. The segmentation usually works only in their application domain, image capturing setting, etc. There are special cases, in which the inverse task to image formation is of practical use. These application domains are mainly 'shape from shading' and 'photometric stereo' and we will explain them in Chapter 11. Direct measurement of radiance-like quantities is also used in quality control checks in industrial production, medical imaging, etc.
3.4.1
I mages as radiometric measurements
Three types of emitted energy can be used to image objects: 1. Electromagnetic radiation including { rays, X-ray, ultraviolet radiation, visible light, infrared radiation, microwaves, and radio waves. Radiation propagates in vacuum at the speed of light, and through matter at lower speeds which also depends on wavelength. In this book, we concentrate on the visible spectrum unless said otherwise. 2. Radiation of particles, e.g. , electrons or neutrons. 3. Acoustic waves in gases, liquids and solids. Only longitudinal waves are spread in gases and liquids, and transverse waves may be evident in solids. The speed at which such waves propagate is directly proportional to the elastic properties of the medium which they traverse. Radiation integrates with matter on the surface of objects or in its volume. The energy ( radiation ) is sent out from objects either because of thermal motion of molecules ( hot radiant body ) or because of external stimulation (e.g, refiected radiance, luminescence ) . Radiation is accompanied by information which can be used to identify observed objects and to assist in measurement of some of their properties. Examples of such information are: 1 . Frequency of radiation expressed by wavelength. 2. Amplitude, i.e. intensity of the radiation. 3. Polarization mode for transverse waves. 4. Phase which is accessible only if coherent imaging techniques are used, as in interfer ometry or holography. Vve
will consider an explanation of image formation in the case of refiection of radiation from the surface of nontransparent objects in the visible spectrum.
3.4.2
Image capture and geometric optics
We begin with a simple model of image capture in which geometric optics play a key role. \�Te consider a photographic or video camera-a device for capturing intensity images. The camera consists of a lens, a photosensitive image sensor converting photons to electrical signals, and electronics that will provide image data for further processing.
82
Chapter 3: The image, its mathematical and physical background
The lens concentrates incoming light to the image sensor. The physical quantity measured is irradiance, often informally called brightness or intensity. We wish the lens to mimic ideal perspective projection (a pin-hole model, see Figure 2.1), and will usc geometric optics which match the pin-hole model. The key concept of the pin-hole model is that of a ray which is a straight line segment mapping a point on a scene to a point on the image plane (or a photosensitive sensor of a camera) . More complicated phenomena, which require more sophisticated mathematical models of wave or quantum optics, are not considered. Wave optics (due to Maxwell in the 19th centnry) permit the explanation of phenomena such as light diffraction, interference, and polarization. The classical book about optics [Hecht, 1998] is recommended if the reader seeks more detail. Here, we will follow conventions used in optical literature; light propagates from left to right. The pin-hole model (camera obscura) is an unrealistic idealization because a very small hole prevents energy passing through it. Wave properties of light cause another deviation from the pin-hole modcl---diffraction. The direction of light propagation is bent if the obstacles are of a siz;e comparable to the wavelength. Strictly speaking, only planar mirrors comply with the geometric optics model. The ideal geometric pin-hole model is more or less valid for the ideal thin lens, sec Figure 3.26. A ray passing through the center of the lens (called the principal point) does not change its direction. If the lens is focused, then incoming rays which are not coincident with the optical axis refract. Incoming rays parallel with the optical axis intersect the optical axis in a single point called the focal point. This process is described by the thin lens equation which can be derived using similar triangles in Figure 3.26. The lens equation in Newtonian form says 1 z' + f
1
-
f
-
1
--
f+z
or in a simpler form z z ' = f2 ,
( 3 71 ) .
where f is the focal length, the distance between the principal point and the (object, image) focal point, z is the distance between the object plane and the object focal point, and z' is the distance between the objeet plane and the image focal point. Let X be the size of the object (the length of the arrow in the object plane in Figure 3.26) and .7: be the size of this object in the image plane. The magnification m of the optical system is z'
f m = X = -; = y ' a::
Figure 3.26:
The thin lens.
3.4 I mage formation physics
83
The disadvantage of the thin lens is that the only rays it maps sharply are those starting from points in a plane perpendicular to the optical axis within a distance z of the principal point.
.
- _ ..
-
..
- - -
, ,
-
- - -
-
I
- - -
d
- - -
"
object space
I
_
.'....
- - -
- - -
'
principal point " : I � • t- - - - - - - . - - -: - _ . - . - image /:"1: i focal point . �t.. --.;/:�-"':
-: :-� : :'_ i / - - f
I
-E
depth of focus .......--- ... --- - ....
.. .
I
..
:
:
:
-
: �
=
image space
-
,
--...
e
_"
Depth of focus in optical system. Figure 3.27:
an
Consider what happens if the image plane is shifted off the focal point [Jiihne, 1997] ; imagine a bundle of rays intersecting in the image focal point. The point will be displayed as a small circle (the circle of permitted defocus) with diameter E, see Figure 3.27. Value �z is the distance between the shifted image plane and the image focal point, d is the diameter of the aperture stop, J if the focal length of the lens, and J + z' is the distance between the principal point and the image focal point. The diameter E of the circle can be calculated using similar triangles
d J + z'
d �z J + z"
E - - -
Recall that 'nf = fld is the f-number of the lens, introduced at the end of the Section 3.4.4. The previous equation can be rewritten as
�z f - T/.f (J + z ')
E -
�z 'n f (1 + z l f)
- --�--�� -
The concepts depth of focus and depth of field are based 0 1 1 the understanding that it is of advantage if the image is a little off-focus. The range of depth in the scene which will be focused in the image will be effectively bigger. It does not make sense to require E to be equal to zero--it is reasonable to be the size of a pixel. The smaller the pixels are, the smaller the effect this improvement has. The depth of focus is the interval of permitted shifts of the image plane [-�z, �z] for which the diameter of the circle E is smaller than a predefined value corresponding to the pixel size. �z is calculated from the previous equation
( �;)
�z = nf 1 +
E
= nf ( 1 + m ) E ,
( 3 . 7 2)
where m is the magnification of the lens. Equation (3.72) demonstrates an important role played by the f-number. The smaller the diameter of the aperture stop, the bigger the depth of focus is. A more important concept from the user 's point of view is the depth of field on the object side of the lens. This governs the permitted range of positions of observed objects
84
Chapter 3: The image, its mathematical and physica l background
L
depth of field
aperture
stop circle of the allowed defocus
•
I
object space
a) normal lens
J fl
.
-
J.
apenure SlOp
image space
I
Figure 3.28: Depth of field on the object side of the lens.
image space •
r,
I
1
b) telecentric lens
l Tl
object space
aperture stop •
J.
•
If.
- .-
image space
I
.J I
c) hypercentric lens
aperture stop
J. •
•
•
f
image space
1
Figure 3.29: Normal, telcccntric and llypercentric lens. The focal point on the object side of the lens is denoted /l IUld the focal point Oil the image side is denoted h .
in the scene which will be effectively in focus; i.e., with allowed defocus of maximal c. The depth of field is illustrakd in Figure 3.28. Real lenses (objectives) are composed of several individual lenses and their model in geometric opti cs is called a thick lens. It has two parallel principal axes and two principal points, one on each side. The ray coming to the lens through the object principal point, which passes the system of lenses, and leaves it from the image principal point under the same angle. The distance between the object and the image principal points gives the effective length of the thick lens. Otherwise, mathematical expressions for the ray passing the lens remain almost the same. In optical gauging, it is often difficult to guarantee that the measured object lies in the object plane. If it comes closer to the lens it looks bigger and if it recedes then it appears smaller. There is a practically useful optical trick which makes gauging easi er-- a telecentric lens. A small aperture stop is positioned into the image focal point; in a
3.4 Image formation physics
85
normal lens the aperture stop is in the principal point; Figure 3.29a. In a tdecentric lens the image is formed only by rays which are approximately collinear to the optical axis; this is ilInstrated in Figure 3.29b. Only part of the rays awl irradiation is passed through the tek>centric lens to its image sidc, and this energy reduction is the reason why obscrved scenes have to bc illuminated more strongly. In industl'ial gauging setting, stronger illumination is nsually !lot difficult to provide. TIl() disadvantage of telecentric lenses is that the diameter of the lens has to be grcater than the measured distances. Telecentric lenses of larger diameters (approx. > 50 mm) are expensive becaw;e they typically use the Fresnel lens principle, used in lighthouses since the 1820s. If the aperture stop is positioned between the image focal point and the image plane then a hypercentric lens is obtained, Figure 3.29c. The properties of normal, teiccentric, and hyperccntric lenses are illustrated by considering a tube viewed ,Liong its axis, see Figure 3.30. A !lormal lens sees the cross section of the tube and its inner surface due to divergent rays. The telecentric lens sees only the cross section because only rays approximately pill'alle! to the optical axis were selected. The hypercentric lens sees the cross section and the outer smface of the tube. It does not M.'€ the inner surface. inner lube surface
cross se<:lion only
and cross section
ouler lube surface and eros.!! se<:lioo
•
•
normal lens
3.4.3
telecentric lens
hypercenlric lens
Figure 3.30: Axial view of a tube by a. normal, a I.elecentric and a hypercentric lens. The cross sec· tion is shown in light gray, the inner surface in dark gray and the ouler sllffacc is hatched.
Lens abberations and radial distortion
Lenses and other optical systems such as mirrors or prisms have defects which lead to blur, color changes, gt:.'ometric distortion frolll the ideal ray, et.c. Thel:ie errors are usually called aberrations in optics. Rays have to pass through some medium, such as air, which also causes blur. Sometime:->, blur can be roughly modeled as a drop of high frequencies in the Fourier spectrum. These effects can be roughly cOIJlpensated for by a high·pass freql1ellcy filter. In an ideal optical system, every point on the object will focus to a single point of zero size on the image. In reality, a point 011 the object side is not a. point in the illlage plane. The result is a distribution of intensities in the volume which is not symmetrical in shape. Blurring occurs because a lens is not a perfect image producer. The output is close to the ideal mathematical model given by equation (3.71) for lenses having spherical surfaces and for rays passing through its priucipai point and rays making only small angles with the optical axis. Six main groups of aberrations can be distinguished: (1) spherical aberration, (2) coma, (3) astigmatism, (4) curvature of field, (5) geometric distortion (radial distortion is of biggest practical importance, described in detail below), and (6) color aberration occurring for light mixed from many wavelengths. The first five abenations also occur for light of a sillgle wavelength.
86
Chapter 3: The image, its mathematical and physical background
Spherical aberration prevents rays from meeting at the same image point. Rays passing throngh the lens close to its center are focused farther away than rays passing its rim.
Coma is produced when rays from an off-axis object point arc imaged by different zones of the lens. The name arises because a point on the object side of the lens is blurred into a comet shape. In spherical aberration, images of an on-axis object point that fall on a plane at right angles to the optical axis are circular in shape, of varying size, and superimposed about a common center. In coma, images of an off-axis object point are circular ill shape, of varying size, but displaced with respect to each other. Coma is usually reduced by a diaphragm which eliminates the outer cones of rays.
Astigmatism occurs when an optical system has different foci for rays that propagate ill two perpendicular planes. If an optical system with astigmatism is used to form an image of a cross, the vertical and hori%ontal lines will be in sharp focus at two different distances.
Curvature of field (which manifests in geometric distortion, both radial and tangen tial ) refers to the location of image points with respect to one another. The first three aberrations are usually corrected by lens designers. Geometric distortion usually remains. Curvature of field expresses the phenomenon that the image of a plane object perpendicular to the optical axis on the object side of the lens projects to a paraboloidal surface called the Petzval surface4. Geometric distortion refers to deformation of an image. If the object on the object side is a fiat grid consisting of squares then it is projected either as a barrel or pincushion, see Figure 3.31 . In barrel distortion, magnification decreases with distance from the axis. In pincushion distortion, magnification increases with distance from the axis .
(a)
• (b)
Figure 3 . 3 1 : Radial distortion il lustrated on a 1 2 x 12 square grid. (a) Barrel distortion. (b) Undis torted. (c) Pincushion distortion.
( c)
Chromatic aberration expresses the failure of a lens to foclls all colors in the same plane. Because the refractive index is least at the red end of the spectrum, the focal length of a lells in air will be greater for red than blue. Computer visioll users of optical systems usually do not have any influence on abberations beyond the right lens. The exception is radial distortion, which often has to be estimated and corrected in computer vision applications. We will explain this in a little more in detail. A typical lens performs distortion of several pixels which a human observer does not notice while looking at a natural scene. However, when an image is used for measurements, compensation for the distortion is necessary. The practical model of lens geometric aberration includes two distortion components. The first is radial distortion which is caused because the lens bends a ray more or less 1 Petzval surface-after Slovak mathematician Jozef Petzval, 1807-1891.
3.4
'\
, , ,
,
f I 'I' IX ,Y h '
, ,
,
,
, ,
,
I
I
I
,
,
,
,
x
\\(x,y) \
,
,
,
,
I
,
,
, ,
,
L1 \,
Ax � . '
,
I
,
I
,
, , ,
,
,
87
,
,
,
Image formation physics
,
Y
.
.
1-_ _ _ _ ---..-- .----- .
Figure 3.32: Radial distortion model; (x' , y') are pixel coordinates measured in the image ( uncorrected ) ; (x, y) are pixel coordinates after correction; (XQ , yo) are coordinates of the principal point, and (.6.x , .6.y ) are components of the necessary correction; r is the distance between pixel (xo, Yo ) and pixel (x', y' ) .
than in the ideal case. The second is the shift of the principal point with respect to the image midpoint. We will not discuss the second component here but leave it to Section 1 1 .3.1 where the intrinsic parameters of a single 3D camera will be explained. It can be seen that the pincushion and barrel distortions in Figure 3.31 are centrally ( radially symmetric. A simple mathematical model is used which approximates the necessary correction by a low order polynomial depending on the distance l' of the observed point (x', y') from the principal point ( xo , Yo) of the image. The variables involved are introduced in Figure 3.32. The coordinates of a pixel after the correction are x = x' + box and y = y' + boy . Radial distortion is approximated as a rotationally symmetric function with respect to the principal point and dependent on the distance l' of the measured pixel (x', y') from the principal point (xo, Yo ) )
7' =
J( ;r xo ) 2 + (y - YO ) 2 .
(3.73)
-
Low order polynomials with even order dependent only on l' are used to assure rotational symmetry. Polynomials with order at most six are commonly used. The approximation is box
= (x' - xo ) (11:17'2 + 11:2 7'4 + 11:37'6 ) , bo y = (y' - Yo ) (11: 1 1'2 + 11:2 1'4 + 11:37'6 )
(3.74)
•
The distortion is represented by the coefficients 11:1, 11:2 , 11:3 which are obtained experimen tally for a particular lens by observing a known calibration image, e.g. , covered with some regular pattern of blobs or lines. Often it is sufficient to use only one nonzero coefficient 11:1 in the approximation. The effect of the radial distortion model applied to a real image is illustrated in Figure 3.33. More complicated lens models cover tangential distortions that model such effects as lens de-centering [Jain et al., 1995] , which we shall not describe in detail here. The reader can consult the original paper [Tsai, 1987] or the treatment in [Jain et al., 1995] . An alternative procedure was proposed in [Prescott and McLean, 1 997] .
3 .4.4
I mage capture from a radiometric point of view
A TV camera and most other artificial vision sensors measure the amount of received light energy in individual pixels as the result of interaction among various materials
88
Chapter 3: The image, its mathematical and physical background
(b)
« )
Figure 3.33: Radial distortion illustrated on t.he real image of a book shelf. (a) Barrel distortiOIl.
(b) Undistorted. (c) Pincushion dir;tortiou.
and light somcc(s); the
vailic measured is informally called a gray-level (or brightness).
Radiometry is a branch of physics that deals with the measurement of the flow and transfer of radiant energy, and is the appropriate tool to consider the m(.'Chanism of image creation. The gray-level corresponding to a point on a 3D surface depends, informaJly
speaking, on the shape of the object, its reflectance properties, the position of the viewer, and properties and p�ition of the illuminants. The radiometric approach to understanding gray-levels is very often avoided in practical applications because of its complexity and numerical instability. The gray-level measured typically does not provide a precise quantitative measurement (one reason is that commonly used cameras are much morc precise geometrically than radiometrically; another, more serious, reason is that the relation between
the gray-level and
shape is
too complex). One way to circumvent this is to lise task-specific illumination that allows
the locatioll of objects of interest on a qualitative level,
and their separation from the
background. If this attempt is successful then all object/background separation task is
!!DIved which is usually much simpler than a complete inversion of the image formation
task from a radiometric point of view. Of course, SOlJie information is lost which could be providl.'
Photometry is
a discipline closely related to radiometry that studies the sensation
of radiant light energy in the human eye; both disciplines describe similar phenomena using similar quantitie;;.
Herein, we shall
describe physical units using square brackets; when there is a danger
of confusion we shall dClJote photometric quantities lIsing the subscript ph, and leave
radiometric ones with no subscript.
luminous flux �ph [1m (
The basic radiometric quantity is part is
=
radiant flux �[WJ,
and its photometric counter
lumen)). For light of wavelength >.
daylight vision, we can convert between these quantities with the relation
= 55SJ,tm and 1 W = 680 1m.
Different people have different abilities to perceive light, and photometric quantities
depend on the spectral characteristic of the radiation source and on the sensitivity of the photoreceptive cells of a human retina. For this reason, the international standardization body Commission International de l'Eclairage (eIE) defined a 'standard observer' corre sponding to average abilities. Let K(>.) be the
luminous efficacy
[1m
W- lj, 3(>') [Wj
the spectral power of the light source, and >. [m], the wavelength. Then luminous flux
3.4 Image formation physics
o:f.:Iph
is proportional
to the intellsity of perception and is given by "ph �
Since photometric
ones.
89
1 J( A) SeA) dA
(3.75)
.
Quantities are too o bserver dependellt, we shall consider ntdioillctric
From a viewer's point of view, the surface of all object can reflect energy into a half sphcre, differently into different directions. The spatial angle is given by tile area on the surface of the unit sphere that is bounded by a cone with au apex in the center of the
sphere. The whole half-sphere corresponds to the spatial angle of 211" [sr (= steradians)]. A small area A at distance R from the origin (i.e., R2 » A) and with angle e between the normal vcctor to the arca and the radius vector betweell t.he origin and the area
corresponds to the spatial
angle n [sr)
(sec Figure 3.34).
fl = A cos9 R'
(3.76)
Irradiance E !Wm-2] describes t.he power of the light energy that falls onto a u nit area of the object surface, E = J
n
Irradiation E of the sensor
R.o
n
(0,0) Figure 3.34: Spatial angle for elelllentary surface area.
all
Figure 3.35: The relation between irradiance E and radiance L.
Irradiance is given by t.he amount of energy that an image-capturiug device gets
per unit of a.n efficient sensitive area of the camera [Horn,
1986]- ·then
gray-levels of
image pixels are quantiy..ed estimates of image irradiance. The efficient area copes with
foresbortening that is cau.<;ed
by the mutual rotation between the elemelltary patch on
the emitting surface and the elementary surface patch of the sensor. We shall consider the relationship between thc irradiance E measured in the image and the radiance produced by a small patch on the object surface. by the lens
of the camera.
Only
The geometry of thc setup is given in Figure 3.35.
the horizontal axis Z, and a lens with focal length
L
part of this radiance is captured
The
optical rods is aligned with
f is placed at the co-ordinate origin
90
Chapter 3: The image, its mathematical and physica l background
(the optical center) . The elementary object surface patch 00 is at distance z . We are interested in how much light energy reaches an elementary patch of the sensor surface 01. The off-axis angle a spans between the axis Z and the line connecting 00 with OJ; as we are considering a perspective projection, this line must pass through the origin. The elementary object surface patch 00 is tilted by the angle 8 measured between the object surface normal n at the patch and a line between 00 and OJ. Light rayi:i passing through the lens origin are not refracted; thus the spatial angle attached to the elementary surface patch in the scene is equal to the spatial angle corresponding to the elementary patch in the image. The foreshortened elementary image patch as seen from the optical center is OJ cos a, and its distance from the optical center is f / cos a. The corresponding spatial angle is
OJ cos a . (.f / cos a) 2
Analogously, the spatial angle corresponding to the elementary patch 00 on the object snrface is 00 cos E>2 (z/ cos a) As the spatial angles are equal,
00 OJ
cos o Z2 cos E> f2 .
(3.77)
Consider how much light energy passes through the lens if its aperture has diameter d; the i:ipatial angle DL that sees the lens from the elementary patch on the object is 2 3 d2 cos a 7r ( _ d) cos a . D L = �4 = 4 (3.78) z (z/ cos 0)2 Let L be the radiance of the object surface patch that is oriented towards the lens. Then the elementary contribution to the radiant flux
O
4
(3.79)
TIle lens concentrates the light energy into the image. If energy losses in the lens are neglected and no other light falls on the image element, we can express the irradiation E of the elementary image patch as
()
O
,
COS,l
0 cos 8 .
(3.80)
If we substitute for 00/ OJ from equation (3.77) , we obtain an important equation that explains how scene radiance influences irradiance in the image:
E=L
� (y)2 cos4
(� .
(3.81 )
The term cos4 a describes a i:iystematic lens optical defect called vignetting5 , which implies that optical rays with larger span-off angle a arc attenuated more; this means 5 0ne of the meanings of vignette is a photograph or drawing with edges that are shaded off.
3.4 I mage formation physics
91
that pixels closer to image borders are darker. This effect is more severe with wide-angle lenses than with tele-Ienses. Since vignctting is a systematic error, it can be compensated for with a radiometrically calibrated lens. The term dj I is called the I-number of the lens and describes by how much the lens differs from a pinhole model.
3.4.5
S urface reflectance
In many applications, pixel gray-level is constructed as an estimate of image irradiance as a result of light reflection from scene objects. Consequently, it is necessary to understand different mechanisms involved in reflection. Here we give just a brief overview that will later permit us to explain the main ideas behind shape from shading -see Section 1 1.7.1. The radiance o f an opaque object that does not emit its own energy depends on irradiance caused by other energy sources. The illumination that the viewer perceives depends on the strength, position, orientation, type (point or diffuse) of the light sourccs, and ability of thc object surface to reflect energy and the local surface orientation (given by its normal vector) . An important concept is that of a gradient space which is a way of describing surface orientations. Let z (x , y) be the surface height. We proceed by noting that at nearly every point a surface has a unique normal n. The components of the surface gradient oz oz and p= (3.82) q=ox oy can be used to specify the surface orientation. We shall express the unit surface normal using surface gradient components; if we move a small distance b.T: in the .T: direction, the change of height is bz = p bx. Thus the vector [1 , O, p] T is the tangent to the surface, and analogously [0, 1 , q] T is also tangent to the surface. The surface normal is perpendicular to all its tangents, and may be computed using the vector product as (3.83) The unit surface normal n can be written as (3.84) Here we suppose that the z component of the surface normal is positive. Consider now spherical co-ordinates used to express the geometry of an infinitesimal surface patch-see Figure 3.36. The polar angle (also called zenith angle) is e and the azimuth is 'P. We wish to describe the ability of different materials to reflect light. The direction towards the incident light is denoted by subscript (i.e., ei and 'P; ) , while subscript v identifies the direction toward the viewer ( ev and 'Pv)-see Figure 3.37. The irradiance of the elementary surface patch from the light source is dE( e i , 'Pi) , and the elementary contribution of the radiance in the direction towards the viewer is dL( e,,, 'Pv) . In general, the ability of the body to reflect light is described using a bi-directional reflectance
i
92
Chapter 3: The image, its mathematical and physical background
%*f
' z
X
_'10 _
\ ::;.1....:...
J'
e,
L
n
e,
V
_
-------
�
Figure 3.36: Spherical angles arc used to de;;cribe orientfltion of fl. surface patch.
Figure 3.37: Directions towards the viewer and the light source.
distribution function fr [SCi], abbreviated BRDF [Nicodemus et al., 1977J (3.85) The BRDF fr· describes the brightness of an elementary surface patch for a specific material, light source, and viewer dircctions. The domain of the BRDF is the Cartesian product of all incident and reflectcd directions which are traditiollally represented in spherical coordinates. Modeling of the BRDF is also important for realistic rendering in computer graph ics [Foley et al., 1990j. The BRDF in its full complexity (equation (3.85») is IISed for modeling reflection properties of materials with oriented microstructure (e.g., tiger's eye-a semi-precious golden-brown stone, a peacock's fcather, a. rough cut of aluminum). The extension of DRDF to color is straightforward. All quantities are expressed 'per ullit wavelength' and the adjective 'spectral' is added. Radiance beconll.. "'S spectral radiance and is expressed in 'watts per square meter, per steradian, per unit wavelength'. Irradiance beeomes spectral irradiance expressed in 'watts per square meter, per unit wavelength'. Dependellce on wavelength ). is introduced into spectral BRDF SRDF =
� 8 e, � /(0 ;, 'l'i, '4'�, ).) =
dL(8;, <1>;, A} rlE(8�, �, A} '
(3.86)
The observed color depends on the power spectrum of the illuminant and reflectance and/or transparency properties of objects in the scenc. There is often morc interl.'St ill the relative spectral composition than in the absolute spectral radiation or spectral irradiation. Instead of spectral DRDF, the reflectance or transpa.rency properties are 1lI0dck'd by wavelength-by-wa.vclength multiplication of the corresponding relative energies (intensities) in each surface point manifested in each pixel of the image. Fortullately, for most practically applicable surfaces, the BROF remains constant if t.he elemelltary surface patch rotates along the normal vect.or to the surface. In this case it. is simplified and depellds on "Pi - "P", i.e., fr(6i, 6", ("Pi - "P,,) ) . This simplification holds for both ideal diffuse (Lambertian) surfaces and for ideal mirrors. Let Ei()..) denote the irradiance caused by the illumination of the surface element, and E,.()..) the energy flux per unit area scattered by the surface element back to the
3.4 I mage formation physics
whole half-space. The ratio P
(A) = E.,. (A) Ei (A)
93
(3.87)
is called the reflectance coefficient or albedo. Albedo is the proportion of incident energy reflected back to the half-space. For simplicity, assume that we may neglect color properties of the surface, and that albedo does not depend on the wavelength A . This proportion is then an integral of the surface radiance L over the solid angle D representing the half-space
in L(D) dD .
(3.88)
r R(D) dD = 1 . in
(3.89)
R = R(n L, nV, V L) .
(3.90)
Er =
Now define a reflectance function R(D) that models the influence of the local surface geometry onto the spatial spread of the reflected energy. Angle D is an infinitesimal solid angle around the viewing direction
In general, surface reflectance properties depend on three angles between the direction to the light source L, the direction towards the viewer V, and the local surface orientation given by the surface normal n (recall Figure 3 . 3 7) . The cosines of these angles can be expressed as scalar (dot) products of vectors; thus the reflectance function is a scalar function of the following three dot products
A Lambertian surface (also ideally opaque, with ideal diffusion) reflects light energy in all directions, and thus the radiance is constant in all directions. The BRDF Aambert is constant: (3 .9 1) If albedo peA) is assumed constant and unitary then the Lambertian surface reflectance can be expressed as 1 1 R(n, L, V) = - n L = cos 8i . (3.92 ) 7r
-
7r
Because of its simplicity, the Lambertian reflectance function has been widely accepted as a reasonable reflectance model for shape from shading (see Section 1 1 .7 . 1 ) . Notice that the reflectance function for the Lambertian surface is independent of the viewing direction V. The dependence of the surface radiance on local surface orientation can be expressed in gradient space, and the reflectance map R(p, q ) is used for this purpose. Reflectance map R(p, q ) can be visualized in the gradient space as nested iso-contours corresponding to the same observed irradiance. Values of the reflectance map may be: 1. Measured experimentally on a device called a goniometer stage that is able to set angles 8 and
94
Chapter 3: The image, its mathematical and physical background
2. Set experimentally if a calibration object is used. Typically a half-sphere is used for this purpose.
3. Derived from a mathematical model describing surface reflecting properties. The best-known surface refiectance models are the Lambertian model for ideal opaque sur faces, the Phong model which models reflection from dielectric materials, the Torrance Sparrow model which describes surfaces as a collection of planar mirror-like micro-facets with normally distributed normals, and the wave theory-based Beckmann-Spizzichino model. A survey of surface reflection models from the point of view of computer vision, and their recent modifications, can be found in [Ikeuchi, 1994] . The irradiance E(x, y) of an infinitely small light sensor located at position x, y in the image plane is equal to the surface radiance at a corresponding surface patch given by its surface parameters u, v if the light is not attenuated in the optical medium between the surface and the sensor. This important relation between surface orientation and perceived image intensity is called the image irradiance equation;
E(x , y)
=
p(u, v ) R(N ( -u , v)L, N(u, v)V, VL) .
(3.93)
In an attempt to reduce complexity, several simplifying assumptions [Horn, 1990] are usually made to ease the shape from shading task. It is assumed that: • •
•
The object has uniform reflecting properties, i.e. p ( u , v) is constant. The light sources are distant; then irradiation in different places in the scene is approximately the same and the incident direction towards the light sources is the same. The viewer is very distant. Then the radiance emitted by scene surfaces docs not depend on position but only on orientation. The perspective projection is simplified to an orthographic one.
We present the simplified version of the image irradiance equation for the Lambertian surface, constant albedo, single distant illuminant, distant viewer in the same direction as illuminallt, and the reflectance function R expressed in gradient space (p, q) ;
E(x, y)
=
(3.94)
(3R(p(x, y), q(x, y)) .
R(p, q ) gives the radiance of the corresponding point in the scene; the proportionality constant (3 comes from equation (3.81 ) and depends on the I-number of the lens. The vignetting degradation of the lens is negligible as the viewer is aligned to the illuminant. The measured irradiance E can be normalized and the factor (3 omitted; this permits us to write the image irradiance equation in the simplest form as E (x, y)
=
R(p(x, y), q(x, y))
= ( R
OZ Oz O:E ' oy
)
.
(3.95 )
The image irradiance equation in its simplest form is a first-order differential equation. It is typically nonlinear as the reflectance function R in most cases depends nonlinearly on the surface gradient. This is the basic equation that is used to recover surface orientation from intensity images.
3.5 Summary
3.5 •
•
•
•
•
95
Summary
Dirac impulse is an idealiz:ed infinitely narrow impulse of a finite area. In image processing, Dirac impulse helps to express image digitization in an elegant way. There is a linear operation called convolution which is often used in image processing. The convolution expresses the relation between two overlapped images. Linear integral transforms - Linear integral transforms provide a rich representations of signals, images in a frequency domain. Some application ta..<;ks are easier in the frequency domaill. The inverse transforms permit the conversion of data back to signals or images. The commonly used transforms in image analysis are the Fourier, cosine, wavelet transforms, and principal component analysis ( PCA ) . The Fourier transform expands a periodic ID function or a 2D image as a possibly infinite linear combination of sines and cosines. The basis of the expansion are waves with some basic frequency Wo and sequence of waves with growing frequencies wo, 2 wo, 2 wo, 3 wo, etc. The complex frequency spectrum F(w) gives both magnitude and phase of the elementary waves. The necessary distance between sampling points is given by the Shannon sampling theorem; sampling has to be twice as dense as the smallest detail to be seen in the image ( at least ) . If the Shannon sampling theorem is violated then aliasing occurs. The wavelet transform analyzes the signal ( image ) by multiplying it by a window function and performing an orthogonal expansion with more complex basis functions, allowing localization of events not only in frequency ( as the Fourier transform does ) but also in time. The expansion is performed at multiple scales. Principal Component Analysis ( PCA ) is the optimal linear transformation which divides an observed space into orthogonal subspaces with the largest variallce. The new basis vectors are calculated for the particular data set. PCA is used for dimensionality reduction of data. Images as a stochastic processes Images are statistical in nature due to random changes and noise. It is sometimes of advantage to treat image functions as realizations of a stochastic process. Such analysis is performed using statistical descriptors as the Illean, dispersion, covariance function or correlation function. Image formation physics Image formation is well understood in radiometry, which is a branch of physics. Observed irradiation from a surface patch by a human or camera depends on light sources, surface reflectance, and mutual relation betweell directions towards observer, towards the illuminator ( s ) , the surface patch normal and its refiectance. Computer vision is interested in the inverse task which is ill-posed in many cases. Image formation physics is not directly explored in many applications becanse it is too complicated to get all the parameters which describe the particular image formation process. Instead, objects are segmented based on semantic knowledge about a specific application. Geometric optics models lens systems used commonly in computer vision.
Chapter 3: The image, its mathematical and physica l background
96
3.6
References
Barrett H. H. and 1Iyers K J. F01lndation of Image Science. Willey Series in Pure and Applied Opties. Wiley & Sons, Hoboken, New Jersey, USA, 2004. 13racewell
13racewell
R..
R.
Castleman
N. 'Two-dimensional Imaging. Prentice-Hall, Englewood Cliffs, NJ, 1 995.
N. Fou.r-ier Analysis and Imaging. Springer-Verlag, 1st edition, 2004.
K.
R. Digital Image Pmces8ing. Prentice-Hall, Englewood Cliffs, NJ, 1996.
Chili C. K An Introil'action to Wavelets. Academic Press, New York, 1992. Chui C. K, Montefusco L., and Puccio L. Wavelets: Theory, A lgorithms, and Applicat?:ons. Academic Press, San Diego, CA, 1994 . Daubechies
1.
Ten Lectures on Wavelets. SIAM, Philadelphia, eSA, 2nd edition, 1992.
Foley J. D., Dam A . v, Feiner S. K, and Hughes J. F. Compufer Gmph?:cs - --Principles and Pmctice. Addison-Wesley, Reading, MA, 2nd edition, 1990. Golub G. H. and Loan C. F. V. Matrix Computations. Johns Hopkins University Press, Baltimore, MD, 2nd edition, 1989. Gonzale
Horn B. K . P. Height and gradient from shading. International Journal of Computer Vision, 5 ( 1 ) :37--75, 1990.
Jkellchi K . Surface reHection mechanism. In Young T. Y., editor, Handbook of Patter'n Recognition and Image P'f'Ocessing: Computer' Vis?:on, pages 1 31--160, San Diego, 1994. Academic Press.
,Hihue
B. Pmctical Handbook on Image Pmcessing for Scientific Applications. CRC Press, Boca Raton, Florida, 1997.
Jain R.. , Kasturi R., and Schunk 13. G. Machine Vision. McGraw-Hill, New York, 1 995. Karu Z. Z. S?:gnals and Systems, Made R'idicnlously Simple. ZiZi Press, Cambridge, MA, USA, 3rd edition, 1999. Leonardis A. and I3ischof H. Robust recognition using eigenimages. Computer Vision and Image Understanding, 78 (1) :99-1 18, 2000. rvlallat S. G. A theory of multiresolution signal decomposition: The wavelet representation. IEEE Transact'ions on Pattern Analysis and Machine Intelligence, 1 1 :674--693, 1989.
Meyer Y. Wavelets: Algor"ithms and Applications. Society for Industrial and Applied Mathematics, Philadelphia, Hl93. Nieodemm; F. E., Richmond .J. C . , Hsia J. J., Ginsberg 1. W., and Limperis T. Geometrical considerations and nomenclature for reflectance. US Department of Commerce, National Bureau of Standards, Washington DC, 1 977.
Oppenheim A. V., Willsky A. S., and Nawab S. Signal and Systems. Prentice Hall, Upper Saddle River, NJ, USA, 2 edition, 1997. Papolliis A. P1'Obability, Random Variables, and Stochastic Pmcesses. McGraw-Hill International Editions, 3rd edition, 1991 . Prescott 13 . and McLean G. F. Line-based correction of radial lens distortion. Oraphical Models and Image Processing, 59 ( 1 ) :39-77, 1 997. Press W. H . , , Teukolsky S. A., Vet terling W. T., and Flannery B. P. Numerical Recipes in Cambridge University Press, Cambridge, England, 2nd edition, 1992.
C.
3.6 References
97
Rao K . R. and Yip P. Discr·e te Cosine Transform, A lgorithms, Advantages, Applications. Academic Press, Boston, 1990. Rogers D. F. Pmceduml Elements of Computer Graphics. McGraw-Hill, New York, 1 985. Tsai R. Y. A versatile camera calibration technique for high-accuracy 3D machine vision metrology using off-the-shelf cameras and lenses. IEEE Journal of Robotics Ilnd Automat?:on, RA-3 (4):323-344, 1987. Turk M. and Pentland A. Eigenfaces for recognition. Journal of Cognitive Neuroscience, 3 ( 1 ) : 71-86, 1991.
Chapter
4
Data structures for image analysis
Data. and an algorithm are the two basic related parts of any program. Data organization often considerably affects the simplicity of the selection and the implementation of an algorithm, and the choice of data structures is therefore a fundamental question when writing a program [Wirth, 1976]. Information about the representation of image data, and the data which can be deduced from them, will be introduced here before explaining different image processing methods. Relations between different types of representations of image data will then be clearer. First we shall deal with basic levels of representation of information in image analysis taskfl; then with traditional data structures such as matrices, chains, and relational structures. Lastly we consider hierarchical data structures such as pyramids and quadtrecs.
4.1
Levels of image data representation
The aim of computer visual perception is to find a relation between an input image and models of the real world. During the transition from the raw input image to the model, image information becomes denser and semantic knowledge about the interpretation of image data is used more and more. Several levels of visual information representation are defined on the way between the input image and the model; computer vision then comprises a design of the: • •
Intermediate representations (data structures) . Algorithms used for the creation of representations and introduction of relations between them.
The representations can be stratifi(.x\ in four levels [Ballard and Brown, 1982J--however, there are no otrict bordero between them and a more detailed classification of the representational levels is used in some applications. These four representational levels are ordered from signals at a low level of abstraction to the description that a human can perceive. The information flow between the levels may be bi-directioual, and for some specific uses, wme representations can be omitted.
4.2 Traditional image data structures
99
The first, lowest representational levcl-iconic images -consists of images containing original data: integer matrices with data about pixel brightness. Images of this kind are also outputs of pre-processing operations (e.g., filtration or edge sharpening) used for highlighting some aspects of the image important for further trcatment. The second level of representation is segmented images. Parts of the image are joined into groups that probably belong to the same objects. For instance, the output of the segmentation of a scene with polyhedra is either line segments coinciding with borders or two-dimensional regions corresponding with faces of bodies. It is useful to know something about the application domain while doing image segmentation; it is then easier to deal with noise and other problems associated with erroneous image data. The third representational level is geometric representations holding knowledge about 2D and 3D shapes. The quantification of a shape is very difficult but also very important. Geometric representations are useful while doing general and complex simulations of the influence of illumination and motion in real objects. We need them also for the transition between natural raster images (gained, for example, by a TV camera) and data used in computer graphics (CAD-computer-aided design, D TP -desktop publishing). The fourth level of representation of image data is relational models. They give us the ability to treat data more efficiently and at a higher level of abstraction. A priori knowledge about the case being solved is usually used in processing of this kind. AI techniques are often explored; the information gained from the image IIlay be represented by semantic nets or frames [Nilsson, 1982] . An example will illustrate a priori knowledge. Imagine a satellite image of a piece of land, and the task of counting planes standing at an airport; the a priori knowledge is the position of the airport, which can be deduced, for instance, from a map. Relations to other objects in the image may help as well, e.g., to roads, lakes, or urban areas. Additional a priori knowledge is given by geometric models of planes for which we are searching.
4.2
Tra d itional image data structu res
Traditional image data structures such as matrices, chains, graphs, lists of object prop erties, and relational databases arc important not only for the direct representation of image information, but also as a basis for more complex hierarchical methods of image representation.
4. 2 .1
Matrices
A matrix is the most common data structure for low-level representation of an image. Elements of the matrix arc integer numbers corresponding to brightness, or to another property of the corresponding pixel of the sampling grid. Image data of this kind are usually the direct output of the image-capturing device, e.g., a scanner. Pixels of both rectangular and hexagonal sampling grids can be represented by a matrix; the correspondence between data and matrix clements is obvious for a rectangular grid; with a hexagonal grid every even row in the image is shifted half a pixel to the right. Image information in the matrix is accessible through the co-ordinates of a pixel that correspond with row and column indices. The matrix is a full representation of
100
Cha pter 4: Data structures for image analysis
the image, independent of the contents of image data-it implicitly contains spatial relations among semantically important parts of the image. The space is two-dimensional in the case of an image-a plane. One very natural spatial relation is the neighborhood relation. A representation of a segmented image by a matrix usually saves more memory than an explicit list of all spatial relations between all objects, although sometimes we need to record other relations between objects. Some special images that are represented by matrices are: •
•
•
A binary image (an image with two brightness levels only) is represented by a matrix containing only zeros and ones. Several matrices can contain information a�out one multispectral image. Each of these matrices contains one image corresponding to one spectral band. Matrices of different resolution are used to obtain hierarchical image data struc tures. This hierarchical representation of the image can be very convenient for parallel computers with the 'processor array' architecture.
Most programming languages use a standard array data structure to represent a matrix, and most modern machines provide adequate physical memory to accommodate image data structures. If they do not, they are usually provided with virtual memory to make storage transparent. Historically, memory limitations were a significant obstacle to image applications, requiring individual image parts to be retrieved from disk independently. There is much image data in the matrix, so processing takes a long time. Algorithms can be speeded up if global information is derived from the original image matrix first global information is more concise and occupies less memory. We have already mentioned the most popular example of global information-the histogram �in Section 2.3.2. Looking at the image from a probabilistic point of view, the normalized histogram is an estimate of the probability density of a phenomenon: that an image pixel has a certain brightness. Another example of global information is the co-occurrence matrix [Pavlidis, 1982], which represents an estimate of the probability of two pixels appearing in a spatial relationship in which a pixel (i1 , jd has intensity z and a pixel (i2 , h) has intensity :y. Suppose that the probability depends only on a certain spatial relation r between a pixel of brightness z and a pixel of brightness y; then information about the relation T is recorded in the square co-occurrence matrix Cr , whose dimensions correspond to the number of brightness levels of the image. To reduce the number of matrices Cr, introduce some simplifying assumptions; first consider only direct neighbors, and then treat relations as symmetrical (without orientation) . The following algorithm calculates the co-occnrrence matrix Of' from the image f( i, j ) .
Algorithm 4.1: Co-occurrence matrix Cr (z, y) for the relation 1. Assign
r
Cr ( z, y) = 0 for all z, y E [0, LJ , where L is the maximum brightness.
2. For all pixels (i1 , jd in the image, determine (i2 , h) which has the relation r with the pixel (i1 , jd , and perform
4.2 Traditional image data structu res
101
If the relation 7' is to be a southem 07' eastem 4-neighbo7' of the pixel (i} , j l ) , 07' identit:tl , elements of the co-occurrence matrix have some interesting properties. Values of the elements at the diagonal of the co-occurrence matrix Cr (k, k) are equal to the area of the regions in the image with brightness k. Thus the diagonal elements correspond to the histogram. The values of elements off the diagonal of the matrix Cr (k,j) are equal to the length of the border dividing regions with brightnesses k and j, k i- j . For instance,
in an image with low contrast, the elements of the co-occurrence matrix that are far from the diagonal are equal to zero or are very small. For high-contrast images the opposite is true. The main reason for considering co-occurrence matrices is their ability to describe texture. This approach to texture analysis is introduced in Chapter 15. The integral image is another ma�rix representation that holds global image infor mation [Viola and Jones, 2001]. It is constructed so that its values ii(i, j) in the location (i , j) represent the sums of all the original image pixel-values left of and above (i, j):
ii (i, j) = L f(k, l) , k-:;'i,l-:;'j
( 4. 1 )
where f is the original image. The integral image can be efficiently computed in a single image pass using recurrences:
Algorithm 4.2: Integral image construction 1. Let s (i, j) denote a cumulative row sum, let s (i, - 1 ) = O. 2. Let ii( i, j) be an integral image, let ii( - 1, j ) = O. 3. Using a single row-by-row pass through the image, for each image pixel (i , j) calculate the cumulative row sums s (i, j ) and the integral image value ii(i, j) using the recurrences
s (i, j) = s (i, j - 1) + f (i, j) , ii(i, j) = ii(i - l, j) + s (i, j) .
( 4.2) (4.3)
4. After reaching the lower right image corner pixel after a single pass through the image, the integral image ii is constructed. The main use of integral image data structures is in rapid calculation of simple rectangle image features at multiple scales. This kind of features is used for rapid object identification (Section 10.6) and for object tracking (Section 16.5) . As shown in Figure 4.1, any rectangular sum can be computed using four array references. Therefore, a feature reflecting a difference between two rectangles requires eight references. Considering the rectangle features shown in Figure 4.2a,b, the two rectangle features require only six array references since the rectangles are adjacent. Similarly, the three- and four-rectangle features of Figure 4.2c,d can be calculated using eight and nine references to the integral image values, respectively. The rectangle features can be computed extremely efficiently and in constant time once the integral image is formed. 1 For the purpose of co-occurrence matrix creation we need to consider the identity relation (iI , h ) = (i2, h ) , or individual pixels would not contribute to the histogram.
102
Chapter 4:
Data
structures for
A
image analysis
a
C
B
�
D .Y
3
Figure 4.1: Calculation of rectangle features from an integral image. The sum of pixels within rectangle D can be ohtained using four array references. D."m ii(tI) + ii(o:) - (ii(fJ) + ii(-y»), where ii(o:) is the value of the integral image at point a, Le., the SUJIl of image value; within the rectangle A. Similarly, thc valuc ii({J) is t.he sum of values in rectangles A and B , etc. =
[[[J EB
CD (a)
(b)
(0)
(d)
Figure 4.2: Rectangle-based feat.ures are calculated from an integral image. These features are calculated by subtraction of the sum of the shaded rectangle(s) from the nOli-shaded rectangle(s) . The figure shows (a,b) two-rectangle, (e) t hree-rect.angle, and (d) four-n.:etangle features. The fom-rectangle features can be co mputed in two di agon al direction!;. The size;; of the individufl.! recta ngles call be varie<1 to yield different features as well as features at different scales. The contributions from the shaded and non-shaded regions can be normalized to acCOUllt for possibly unequal region sizes. 4.2.2
Chains
Chaills arc used for the description of object borders ill computer vision. One element of the chain is a basic symbol; this approach permits the application of formal language theory for computer vision tasks. Chains are appropriate fol' data that can be arranged as a !;Cquellce of symbols, and the neighboring symbols in a chain usually correspond to the neighborhood of primitives in the image. The primitive is the basic descriptive element that is used in sYlltactie pattern recognition (see Chapter 9). This rule of proximity (neighborhood) of symbols and primitives has exceptions-for example, the first alld the last symbol of the chain describing a closed border are not neighbors, but the corresponding primitives in the image are. Similar inconsistencies are typical of image description languages [Shaw, 19691, too. Chains arc linear struc� tures, which is why they cannot describe spatial relations in the image on the basis of ueighborhood 01' proximity. Chain codes (and Freeman codes) [Freeman, 19611 are often used for the description of object borders, or other one-pixel-wide lines in images. The border is defined by the
4.2 Traditional image data structures
103
co-ordinatcs of its reference pixel and the sequence of symbols corresponding to the line of the unit length in several pre-defined orientations. Notice that a chain code is of a relative nature; data arc expressed with respect to some rcference point. An example of a chain codc is shown in Figure 4.3, where 8-neighborhoods are used·_···it is pos..<;ible to define chain codes using 4-neighborhoods as well. An algorithm to extract a chain code may be implemented as an obvious simplification of Algorithm 6.7; chain codes and their properties are described in more detail in Chapter 8.
i marked by an arrow: Figure 4.3: An example chain code; the reference pixel starting the chain s
00077665555556600000006444444442221111112234445652211.
If local information is needed from the chain code, then it is necessary to search through the whole chain systemat.ically. For instance, if we want to know whether the border turns somewhere to the left by 90", we must just find a sample pair of symbols in the chain it is simple. On the other hand, a question about the shape of the border near the pixel (io,jo) is not trivial. rt is nece&>ary to investigate all chains until the pixel (io,jo) is found and only then we can start to analyze a short part of the border that. is close to the pixel (io, io ). The description of an image by chains s i appropriate for syntactic pattern recognition that is based on formal language theory methods. When working with real images, the problem of how to deal with uncertainty caw;ed by noise arises, which is why several syntactic analysis techniques with dcformatiolt correction have arisen [Lu and Fu, 1978\. Another way to deal with noise is to smooth the border or to approximate it by another curve. This new border curve is then described by chain codes [Pavlidis, 1977]. Run length coding is quite often used to represent strings of symbols in an image matrix (for instance, FAX machines use fUll length coding). For simplicity, consider a binary image first. Run length coding records only are/tl:i that belong to the object in thc image; the area is then represented as a list of lists. Various schemes exist which differ ill detail - a representative one describes each row of the image by a sublist, the first element of which is the row Humber. Subsequent terms are co-ordinate pairs; the first element of a pair is the beginning of a mil and the second is the end (the begiulling and the end are described by column coordinates). There can be several such sequences in the row. Run length coding is illustrated ill Figure 4.4. The main advantage of run length coding is the existence of simple algorithms for intersections and unions of regions in the imagc. Run length coding can be used for an image with multiple brightness levels as well in this case sequences of neighboring pixels in Il. row that has constant brightness are eom:iidered. In the sublist we must record not only the beginning and the end of the sequence, but its brightness, too. -
Chapter 4: Data structures for image analysis
104 o
D
2
3
5
6
•
•
2
4
• • • •
3
4 5
• •
6
• Figure 4.4:
Run length coding; the code is ( ( 1 1 144) (214) (52355) ) .
From the implementational point of view, chains can be represented using static data structures (e.g., 1D arrays) ; their size is the longest length of the chain expected. This might be too memory consuming, and so dynamic data structures are more advantageous. Lists from the LISP language are an example.
4.2.3
Topological data structures
Topological data structures describe the image as a set of elements and their relations; these relations are often represented using graphs. A graph G (V, E) is an algebraic structure which consists of a set of nodes V {Vl ' V2 , . . . , vn } and a set of arcs E = { e 1 ' e2 , . . . , em }. Each arc ek is incident t o an unordered (or ordered) pair of nodes {Vi , Vj } which are not necessarily distinct [Even, 1979] . The degree of the node is equal to the number of incident arcs of the node. An evaluated graph ( also weighted graph) is a graph in which values are assigned to arcs, to nodes, or to both--these values may, for example, represent weights, or costs. The region adjacency graph is typical of this class of data structures, in which nodes correspond to regions and neighboring regions are connected by an arc. The segmented image (see Chapter 6) consists of regions with similar properties (brightness, texture, color, . . . ) that correspond to some entities in the scene, and the neighborhood relation is fulfilled when the regions have some common border. An example of an image with areas labeled by numbers and the corresponding region adjacency graph is shown in Figure 4.5; the label 0 denotes pixels out of the image. This value is used to indicate regions that touch borders of the image in the region adjacency graph. =
=
o
'0
2
3
ko 2 4
5
Figure 4.5:
An example region adjacency graph.
The region adjacency graph has several attractive features. If a region encloses other regions, then the part of the graph corresponding with the areas inside can be separated by a cut in the graph. Nodes of degree 1 represent simple holes.
4.2 Traditional i mage data structures
105
Arcs of the region adjacency graph can include a description of the relations between neighboring regions-the relations to be to the left or to be inside are common. The region adjacency graph can be used for matching with a stored pattern for recognitioll purposes. The region adjacency graph is usually created from the region map, which is a matrix of the same dimensions as the original image matrix whose elements are identification labels of the regions. To create the region adjacency graph, borders of all regions in the image are traced, and labels of all neighboring regions are stored. The region adjacency graph can easily be created from an image represented by a quadtree as well (see Section 4.3.2) . The region adjacency graph stores information about the neighbors of all regions in the image explicitly. The region map contains this information as well, but it is much more difficult to recall from there. If we want to relate the region adjacency graph to the region map quickly, it is sufficient for a node in the region adjacency graph to be marked by the identification label of the region and some representative pixel (e.g., the top left pixel of the region). Construction of the boundary data structures that represent regions is not trivial, and is considered in Section 6.2.3. Region adjacency graphs can be used to approach region merging (where, for instance, neighboring regions thought to have the same image interpretation are merged into one region)-this topic is considered in Section 10.S. In particular, note that merging representations of regions that may border each other more than once can be intricate, for example, with the creation of 'holes ' not present before the merge-sec Figure 4.6.
o (a) Figure 4.6:
4.2.4
(b)
Region merging may create holes: (a) Before a merge; (b) After.
Relational structures
Relational databases [Kunii et al., 1974] can also be used for representation of information from an image; all the information is then concentrated in relations between semantically important parts of the image-objects-that are the result of segmentation (Chapter 6). Relations are recorded in the form of tables. An example of snch a representation is shown in Figure 4.7 and Table 4 . 1 , where individual objects are associated with their names and other features, e.g., the top-left pixel of the corresponding region in the image. Relations between objects are expressed in the relational table as well. In Figure 4.7 and Table 4 . 1 , such a relation is to be inside; for example, the object 7 (pond) is situated inside the object 6 (hill). Description by means of relational structures is appropriate for higher levels of image understanding. In this case searches using keys, similar to database searches, can be used to speed up the whole process.
106
Chapter 4: Data structures for image analysis
2
6
4
5
C
=>,
_ _ _
Figure 4.7: Description of objects \Ising relational stl'uctm·c. No
1 2 3 4 5 6 7
Slln
white
sky
blue
cloud
gray
tree trunk
brown
tree crown
green
hill
light green
pond
blue
Table 4.1:
4.3
I Mill
I Object u&me I Color
row
5 0 20 95 53 97 100
I Min
col
I Inside 2
40 0 180 75 63 0 160
-
2 6
-
-
6
Relational table.
H ierarchical data structures
Computer visioll is by its uature very computationally expensive, ir for
110
other reason
than the large amount or data to be processed. Systems which we might call sophisticated must process considemble quantitiL-'S of image data. Usually a very quick response is {�xpected because interactive systems are desirable. One of the solutions is to usc parallel computers (in other words brute force) . Unfortunately there are ITIl\uy computer vision
problems that are very difficult to divide among processors, or decompose in any way. Hierarchical data structures make it possible to use algorithms which decide a strategy for pr()CCl;."iug on the basis of relatively small quantit.ies of data. They work at the finest resolution only with those parts of the image for which it is CS&)ntial, using kuowledge
instead of brute force to ease and speed up the processing. We are going to introduce two typical structures, pyramids and quadtrees.
4.3.1
Pyramids
Pyramids are among the simplest hierarchical data structures. We distinguish betwt-"ell
M-pyramids (matrix-pyramids) and T-pyramids (tree-pyramids) . A Matrix-pyramid (M-pyramid) is a sequence {A1,., ML. _I ,
. . •
, Mo} of images,
where ML has the same dimensions and elements as the original image, and Ali_I is derived from the M; by reducing the resolution by one-half. When creating pyramids, it is customary to work with square matrices having dimensions (.'qua! to powers of 2- -then
AIo
corresponds to one pixel only.
4.3 H ierarchical data structures
107
M-pyramids are used when it is necessary to work with an image at different resolutions simultaneously. An image having one degree smaller resolution in a pyramid contains four times less data, so it is processed approximately four times as quickly. Often it is advantageous to usc several resolutions simultaneously rather than choose just one image from the M-pyramid. For such algorithms we prefer to use tree-pyramids, a tree structure. Let 2 £ be the size of an original image (the highest resolution) . A tree pyramid (T-pyramid) is defined by: 1. A set of nodes P = {p = (k, i )) such that level k E [0, L] ; i, ) E [0 2 " 2 . A mapping F between subsequent nodes Pk- 1 , Pk of the pyramid ' ,
F (k , i , ) ) '
,
=
(k
-
- In .
l , i div 2 , ) div 2) ,
where 'div' denotes whole-number division. 3. A function V that maps a node of the pyramid P to Z, where Z is the subset of the whole numbers corresponding to the number of brightness levels, for example, Z = {0, 1 , 2, . . . , 255} . Nodes of a T-pyramid correspond for a given k with image points of an M-pyramid; elements of the set of nodes P = { (k, i, j)} correspond with individual matrices in the M-pyramid-k is called the level of the pyramid. An image P = { (k, 'i, j)} for a specific k constitutes an image at the kt h level of the pyramid. F is the so-called parent mapping, which is defined for all nodes Pk of the T-pyramid except its root (0, 0, 0). Every node of the T-pyramid has four child nodes except leaf nodes, which are nodes of level L that correspond to the individual pixels in the image. Level 0 Level 1 Level 2
Figure
4.8: T-pyramid.
Values of individual nodes of the T-pyrarnid are defined by the function V. Values of leaf nodes are the same as values of the image function (brightness) in the original image at the finest resolution; the image size is 2 10- 1 • Values of nodes in other levels of the tree are either an arithmetic mean of four child nodes or they are defined by coarser sampling, meaning that the value of one child (e.g., top left) is used. Figure 4.8 shows the structure of a simple T-pyramid. The number of image pixels used by an lvI-pyramid for storing all matrices is given by N
2(
1 1 +... 1 + 4" + 16
)
�
1.33 N2 ,
( 4.4)
where N is the dimension of the original matrix (the image of finest resolution)-usually a power of two, 2 £ . The T-pyramid is represented in memory similarly. Arcs of the tree need not be recorded because addresses of the both child and parent nodes are easy to compute due to the regularity of the structure. An algorithm for the effective creation and storing of a T-pyramid is given in [Pavlidis, 1982] .
Chapter 4: Data structures for i mage a n alysis
108
4.3.2
Quadtrees
Quadtrees are modifications of T-pyramids. Every node of the tree except the leaves has four children (NvV, north-western; NE, north-eastern; SW, south-western; SE, south eastern) . Similarly to T-pyramids, the image is divided into four quadrants at each hierarchical level; however, it is not necessary to keep nodes at all levels. If a parent node has four children of the same value (e.g. , brightness), it is not necessary to record them. This representation is less expensive for an image with large homogeneous regions; Figure 4.9 is an example of a simple quadtree. 11
10 0
2
120
121
122
123
13
3 1 20
121
122
123
Figure 4.9:
Quadtree.
An advantage of image representation by means of quadtrees is the existence of simple algorithms for addition of images, computing object areas, and statistical moments. The main disadvantage of quadtrees and pyramid hierarchical representations is their dependence on the position, orientation, and relative size of objects. Two similar images with just very small differences can have very different pyramid or quadtree representations. Even two images depicting the same, slightly shifted scene, can have entirely different representations. These disadvantages can be overcome using a normalized shape of quadtree in which we do not create the quadtree for the whole image, but for its individual objects. Geometric features of objects such as the center of gravity and principal axis are used (see Chapter 8); the center of gravity and principal axis of every object are derived first and then the smallest enclosing square centered at the center of gravity having sides parallel with the principal axes is located. The square is then represented by a qlladtree. An object described by a normalized quadtree and several additional items of data (co-ordinates of the center of gravity, angle of main axes) is invariant to shifting, rotation, and scale. Quadtrees are usually represented by recording the whole tree as a list of its individual nodes, every node being a record with several items characterizing it. An example is given in Figure 4.10. In the item Node type there is information about whether the node is a leaf or inside the tree. Other data can be the level of the node in the tree, position in the picture, code of the node, etc. This kind of representation is expensive in memory. Its advantage is easy access to any node because of pointers between parents and children. It is possible to represent a quadtree with less demand on memory by means of a leaf code. Any point of the picture is coded by a sequence of digits reflecting successive divisions of the quadtree; zero means the NW (north-west) quadrant, and likewise for other quadrants: 1-NE, 2-SW, 3-SE. The most important digit of the code (on the left) corresponds to the division at the highest level, the least important one (on the right) with the last division. The number of digits in the code is the same as the number of
4.3 H ierarchical d ata structures
109
Node type Pointer to the NW son Pointer to the NE son Pointer to the SW son Pointer to the SE son Pointer to the father Other data
Figure
4.10: Record describing a quadtree node.
levels of the quadtree. The whole tree is then described by a sequence of pairs-the leaf code and the brightness of the region. Programs creating quadtrees can use recursive procedures to advantage. T-pyramids are very similar to qlladtrees, but differ in two basic respects. A T pyramid is a balanced structure, meaning that the corresponding tree divides the image regardless of the contents, which is why it is regular and symmetric. A quadtree is not balanced. The other difference is in the interpretation of values of the individual nodes. Qlladtrees have seen widespread application, particularly in the area of Geographic Information Systems (GIS) where, along with their three-dimensional generalization octrees, they have proved very useful in hierarchical representation of layered data [Samet, 1989, 1990j .
4.3.3
Other pyramidal structures
The pyramidal structure is widely used, and has seen several extensions and modifi cations. Recalling that a (simple) M-pyramid was defined as a sequence of images {lIh , N1£ - l , . . . , lvIa } in which Mi is a 2 x 2 reduction of NIH I , we can define the notion of a reduction window; for every cell c of lvIi , the reduction window is its set of children in NIH 1 , w ( c). Here, a cell is any single element of the image Mi at the corresponding level of pyramidal resolution. If the images arc constructed such that all interior cells have the same number of neighbors (e.g. , a square grid, as is customary) , and they all have the same number of children, the pyramid is called regular. A taxonomy of regular pyramids may be constructed by considering the reduction window together with the reduction factor A , which defines the rate at which the image area decreases between levels;
A :::;
HI IM 1 M; ! I , �.
=
0, 1 , . . . , L - 1 .
In the simple case, in which reduction windows do not overlap and are 2 x 2, we have A = 4; if we choose to let the reduction windows overlap, the factor will reduce. The notation used to describe this characterization of regular pyramids is ( reduction win dow)/ ( reduction factor) . Figure 4.11 illustrates some simple examples. The reduction window of a given cell at level i may be propagated down to higher resolution than level i + 1 . For a cell Ci at level i, we can write VP (Ci) = W(Ci), and then recursively define ( 4.5) Wk+ 1 (Ci) = U Wk (q ) , qEW(Ci)
110 Chapter 4: Data structures for image analysis w k (Ci) is the eqlLivalent 'Windo'W that covers all cells at level i + k + 1 that link to the cell Ci . Note that the shape of this window is going to depend on the type of pyramid-for example, an n n/2 pyramid will generate octagonal equivalent windows, while for an n n/4 pyramid they will be square. Use of non-square windows prevents domination of square features, as is the case for simple 2 2/4 pyramids. x
x
x
F;;l F;;l
��
F;;l F;;l
�� (a)
0 0 0 0
• •
0 0 0
0 •
0
0 0 0
(b)
• •
0
0
0 0
0
0
0
0
0 0
0
Figure 4 . 1 1 : Several regular pyramid definitions. (a) 2 x 2/4. (b) 2 dots are at the higher level, Le., the lower-resolution level. )
•
•
0
x
0
0
0
•
0
0
0
0
0
(c)
3
0
0
(c) 2/2.
• •
0 0
x
3/2. (Solid
The 2 x 2/4 pyramid is widely used and is what is usually called an 'image pyramid'; the 2 x 2/2 structure is often referred to as an 'overlap pyramid '. 5 x 5/2 pyramids have been used [Burt and Adelson, 1983] in compact image coding, where the image pyramid is augmented by a Laplacian pyramid of differences. Here, the Laplacian at a given level is computed as the per-pixel difference between the image at that level, and the image derived by 'expanding ' the image at the next lower resolution. The Laplacian may be expected to have zero (or close) values in areas of low contrast, and therefore be amenable to compression. IrreglLlar pyramids are derived from contractions of graphical representations of images ( for example, region adj acency graphs) . Here, a graph may be reduced to a smaller one by selective removal of arcs and nodes. Depending on how these selections are made, important structures in the parent graph may be retained while reducing its overall complexity [Kropatsch, 1995] . The pyramid approach is quite general and lends itself to many devclopments-- for example, the reduction algorithms need not be deterministic [Meer, 1989] . A brief survey of pyramidal segmentation algorithms may be found in [Bister et al., 1990] .
4.4 •
Summary
Level of image data representation Data structures together with algorithms are used to devise solutions to compu tational tasks. Data structures for vision may be loosely classified as * Iconic * Segmented * Geometric * Relational Boundaries between these layers may not be well defined.
4.5 References •
111
Traditional image data structures The matrix (2D array) is the most common data structure used for low-level representations, implemented as an array. Matrices hold image data explicitly. Spatial characteristics are implicitly available. Binary images are represented by binary matrices; multispectral images are represented by binary matrices; Hierarchical image structures are represented by matrices of different dimensions; The co-ocwrrcncc matrix is an example of global information derived from an image matrix; it is useful in describing texture. Chains may be used to describe pixel paths, especially borders. Chain codes arc useful for recognition based on syntactic approaches. Run length codes arc useful for simple image compression. Graph structures may be used to describe regions and their adjacency. These may be derived from a region map, a matrix of the same size as the image. Relational structures may be used to describe semantic relationships between image regions.
•
Hierarchical data structures Hierarchical structures can be used to extract large-scale features, which may be used to initialize analysis. They can provide significant computational efficiency. M-pyramids and T-pyramids provide data structures to describe multiple image resolutions. Quadtrees are a variety of T-pyramid in which selected areas of an image are stored at higher resolution than others, permitting selective extraction of detail. Many algorithms for manipulation of quadtrees are available. Quadtrees are prone to great variation from small image differences. Leaf codes provide a more efficient form of quadtree. Many ways of deriving pyramids exist, dependent on choice of reduction window.
4.5
References
Ballard D. H. and Brown C.
1\11.
ComputeT Vision. Prentice-Hall, Englewood Cliffs, N.J, 1982.
Bister M . , Cornelius .1 . , and Rosenfeld A. A critical view of pyramid segmentation algorithms. Pattern Recognition Letters, 1 1 (9):605-6 1 7, 1 990.
Burt P. J . and Adelson E. H. The Laplacian pyramid as a compact image code. IEEE Tran8o,ctions on Compnters, COM-3 1 (4):532-540, 1983. Even S. Graph Algorithms. Computer Science Pres!;, Rockville, MD, 1 979.
Freeman H. On the encoding of arbitrary geometric configuration. IRE Tmnsactions on Elcctr-onic Compntc'rs, EC-10(2) :260 268, 1961. Kropatsch W. G . Building irregular pyramids by dual graph contraction. lEE Proceedings: Vision, Image and Signal Processing, 142(6) :366-374, 1 995. Kuuii T. L" Weyl S" and Tenenbaum 1. M. A relation database schema for describing complex scenes with color and texture. Tn Proceedings of the 2nd International Joint Conference on Pattern Recognition, pages 310-3 16, Copenhagen, Denmark, 1974.
112
Cha pter 4: Data structures for image ana lysis
Lu S. Y. and Fu K. S. A syntactic approach to texture analysis. Comp'uter Graphics and Image Processing, 7:303-330, 1978. Meer P. Stochastic image pyramids. Computer Vision, Graphics, and Image Processing, 45(3) : 269-294, 1989. Nilsson N. J. Principles of Art'ijic'ial InteUigence. Springer Verlag, Berlin, 1982. Pavlidis T. Structural Pattern Recognition. Springer Verlag, Berlin, 1 977, Pavlidis T. Algorithms for Graphics and Image Processing. Computer Science Press, New York, 1982. Samet H . The Design and Analysis of Spatial Data Str"uctu'res. Addison-Wesley, Reading, MA, 1989. Samet H. Applications of Spatial Data Structures. Addison-Wesley, Reading, MA, 1990. Shaw A. C . A formal picture description schema as a basis for picture processing systems. Information and Control, 1 4:9-52, 1969. Viola P. and Jones M. Rapid object detection using a boosted cascade of simple features. In Proceedings IEEE Conf. on Comp'uter' Vision and Pattern Recognition, pages 5 1 1 0-5 18, Kauai, Hawaii, 200 1 . IEEE. Wirth N. Algorithms
+
Data Structures
=
Programs. Prentice-HaU, Englewood Cliffs, N.J, 1976.
Chapter
5
I mage pre-processi ng
Pre-processing is the name used for operations on images at the lowest level of abstraction both input and output are intensity images. These iconic images are usually of the same kind as the original data captured by the sensor, with an intensity image usually represented by a matrix or matrice; of image function values (brightnesses). Pre-processing docs not increase image information content. using entropy (Section
3.3),
If information is measured
then pre-processing typically decreases image information
content. From the informatioIl-theoretic viewpoint it. can thus be concluded that the best pre-processing is no pre-proa."lSing, and without que;tion, the best way to avoid (elaborate) pre-processing is to concentrate on high-quality image acquisition. Nevertheless, pre processing is very useful in a variety of situations since it helps to suppress information that is not relevant to the specific image procesi:iing or analysis task. Therefore, the aim of pre-proce&;ing is an improvement of the image data that suppresses undesired distortions or enhances some image features important for further processing, although geometric transformations of images (e.g., rotation, 5Caling, translation) are also classified as pre-processing methods here since similar techniques are used. Image pre-processing methods are c1assifk"'
5.1 deals with pixel brightness transformations, Section 5.2 describes geometric 5.3 considers pre-processing methods that usc a local neighbor and Section 5.4 briefly characterizes image restoration that requires knowledge
Section
transformations, Section hood,
about the entire image. Some authors classify image pre-processing methods differently into
ment, covering pixel image restoration.
image enhance
brightness transformations (local pre-processing ill our sense), and
A considerable redundancy of information in
1ll0000t images allows image pre-processing
methods to explore image data itself to learn image characteristics in a statistical sense. These characteristics arc used either to suppress unintended degradatioIL.<; such as noise or to enhance the image. Neighboring pixels corresponding to given object in real images ha.ve essentially the same or similar brightness value, so if a distorted pixel can be picked out from the image, it ca.n usually be restored as an average value of neighboring pixels.
114
Chapter 5: I mage pre-processing
If pre-processing aims to correct some degradation in the image, the nature of a priori information is important: •
•
•
A first group of methods uses little or no knowledge about the nature of the degrada tion; only very general properties of the degradation arc assumed. A second group assumes knowledge about the properties of the image acquisition device, and the conditions under which the image was obtained. The nature of noise (usually its spectral characteristics) is sometimes known. A third approach uses knowledge about object.s that are sought in the image, which may simplify the pre-processing considerably. If knowledge about ohjects is not available in advance, it can be estimated during the processing. The following strategy is possible: first the image is coarsely processed to reduce data quantity and to find image objects. The image information derived is used to create a hypothesis about image object properties, and this hypothesis is then verified in the image at finer resolution. Such an iterative process can be repeated until the presence of knowledge is verified or rejected. This feedback may span more than pre-processing, since segmentation a.lso yields semantic knowledge about objects-thus feedback ca.n be initiated after the object segmentation.
5.1
P ixel brightness transformations
A brightness transformation modifies pixel brightness--the transformation depcnds on the properties of a pixel itself. There are two classes of pixel brightness transformations: brightness corrections and gray-scale transformations. Brightness correction mod ifies the pixel brightness taking into account its original brightness and its position in the image. Gray-scale transformations change brightness without regard to position in the image.
5.1.1
Position-dependent brightness correction
Ideally, the sensitivity of image acquisition and digitization devices should not depend on position in the image, but this assumption is not valid in many practical cases. The lens attenuates light more if it passes farther from the optical axis, and the photosensitive part of the sensor (vacuum-tube camera, CCD camera elements) is not of identical sensitivity. Uneven object illumination is also a source of degradation. If degradation is of a systematic nature, it can be suppressed by brightness correction. A multiplicative error coefficient e ( i, j) describes the change from the ideal identity transfer function. Assume that g(i , j) is the original undegraded image (or desired or true image) and f (i, j) is the image containing degradation. Then
f (i, j) = e (i, j) g(i , j) .
(5.1 )
The error coefficient e(i, j) can be obtained if a reference image g(i, j) with known brightnesses is captured, the simplest being an image of constant brightness c. The degraded result is the image fc(i , j). Then systematic brightness errors can be suppressed by . f (i, j) - c f (i, j) (5,2) 9 ( 1" .7 ) j'c ( � , J ) e (� , J ) '
_
_
'
'
'
'
5 . 1 Pixel brightness transformations
115
This method can be used only if the image degradation process is stable. If we wish to suppress this kind of error in the image capturing process, we should perhaps re-calibrate the device (find error coefficients eU, j)) from time to time. This method implicitly assumes linearity of the transformation, which is not true in reality because the brightness scale is limited to some interval. The calculation according to equation ( 5 . 1 ) can overflow, and the limits of the brightness scale are used instead, implying that the best reference image has brightness that is far enough from both limits. If the gray-scale has 256 brightness levels, the ideal image l has constant brightncss values of 128.
5. 1. 2
Gray-scale transformation
Gray-scale transformations do not depend on the position of the pixel in the image. A transformation T of the original brightness P from scale [PO , Pk] into brightness q from a new scale [qO , qk ] is given by (5.3) q = T(p) . The most common gray-scale transformations are shown in Figure 5 .1 ; the piecewise linear fUIlction Q, enhances the image contrast between brightness values PI and P2 . The function b is called brightness thresholding and results in a black-and-white image; the straight line c denotes the negative transformation. f 255 -
/� (a) contrast enhancement ,.
'.,
.
'.,
.
o
," , " -- (b) threshold
""
. , , , , , , , . . -'
.
255
g
Figure 5.1: Perspective projection geome try examples.
Digital images have a very limited number of gray-levels, so gray-scale transformations are easy to realize both in hardware and software. Often only 256 bytes of memory ( called a look-up table) are needed. The original brightness is the index to the look-up, and the table content gives the new brightness. The image signal usually passes through a look-up table in image displays, enabling simple gray-scale transformation in real time. The same principle can be used for color displays. A color signal consists of three components --red, green, and blue; three look-up tables provide all possible color seale transformations. These tables are called the palette in personal computer terminology ( see Section 2. 4 for more detail on color representation ) . Gray-scale transformations are used mainly when an image is viewed by a human observer, and a transformed image might be more easily interpreted if the contrast is enhanced. For instance, an X-ray image can often be much clearer after transformation. J Most TV cameras have automat.ic control of gain, which allows them to operate under changing illumination conditions. If systematic errors are suppressed using error coefficients, this automatic gain control should be switched off first.
116
Chapter 5: Image pre-processing
A gray-scale transformation for contrast enhancement is usually found automatically using the histogram equalization technique. The aim is to create an image with equally distributed brightness levels over the whole brightness scale (see Figure 5.2) . Histogram equalization enhances contrast for brightness values close to histogram maxima, and decreases contra..'lt near minima.
G(q)
H(p)
Figure 5.2: Histogram equalization.
q
p
Denote the input histogram by H(p) and recall that the input gray-scale is [pO , Pkj . The intention is to find a monotonic pixel brightness transformation q = T(p) such that the desired output histogram G( q ) is uniform over the whole output brightness scale
[qo , qkj .
The histogram can be treated as a discrete probability density function. The monotonic property of the transform T implies
k = G( ) qi L L H(Pi ) . k
(5.4)
i= O
i=O
The sums in equation (5.4) can be interpreted as discrete distribution functions. Assume that the image has N rows and columns; then the equalized histogram G( q ) corresponds to the uniform probability density function f whose function value is a constant: N2
f = -- . qk - (jo
(5.5)
The value from equation ( 5.5) replaces the left side of equation (5.4) . The equalized histogram can be obtained precisely only for the 'idealized' continuous probability density, in which case equation (5.4) becomes N2
1
q
'10
_1_ d s = N2 ( q - qo ) =
qk - qo
qk - qo
r H( s ) d s .
.Jp o
lP H( s) ds + qo .
(5.6)
The desired pixel brightness transformation T can then be derived as
qk - qo q = T(p ) = --;j2
(5.7)
Po
The integral in equation ( 5.7) is called the cumulative histogram, which is approximated by a sum in digital images, so the resulting histogram is not equalized ideally. The discrete approximation of the continuous pixel brightness transformation from equation (5.7) is P
qk - qo " . q = T(p) = --;j2 � H(z) + qo . i= po
(5.8)
5.1 Pixel brightness transformations
117
Formally, the algorithm to perform equalization is as follows. Algorithm 5.1: Histogram equalization
1. For an N x M image of G gray-levels (often 256), create an array H of length G iuitialized with 0 values. 2. Form the image histogram: Scan every pixel and increment the relevant member
of H-if pixel p has intensity 9p, perform Hlg,]
�
H lg,1 + I .
3. Form the cumulative image histogram He: Hotol H,IPI 4.
� �
HIO] , H,IP - II + HIPI ,
. ,G - I .
p � 1,2, . .
Set
(This step obviously lends itself to more efficient implementation by constructing a look-up table of the multiples of (G - l)/NM, and making comparisons with the values in He, which are monotonically increasing.) 5. Rescan the image and write an output image with gray-levels 9q , setting g. � T[g,i ·
(This presentation assumes that the intensity range of source and destination images is [0, G - II-the adjustment if this is not the case is trivial.) These results can be demonstrated on an image of a lung. An input iml\ge and its equalization are shown in Figure 5.3; t heir respective histogI'ams are shown in Figure 5.4.
(al
(bl
Figure 5.3: Histogram eqwl.lizatioll. (a) Original ima.ge. (b) Equalized image.
118
Chapter 5: Image pre-processing
-.
-
�
i
,
.�.
-.
.
I
=
=. ,�
,�
� .
,. ,
Figure ure
•
�
�
,
.
I_oi\v
(0)
,�
m
5.4: Histogram equalization: Original
,I
= ,�
,�
� .
,' ,
.,
5.3a,b.
-
,� .
(b)
and equalized histograms corresponding to fig
The logarithmic gra.y-scale transformation function is Rnother frequently u8Cd. tech nique. It simulates the logarithmic sensitivity of the human eye to thc light interu;ity which enables us to pcrceive intensities to an amazing nine orders of magnitude. The logarithmic gmy-scale transformation is also used to compensate for exponential -y-correction used in cameras (explained alrea.dy in Section 2.5.2). Pseudo-color is yet another kind of gray-scale transform. The individual brightnesses in the input monoduomatic image are coded to some color. Since the human eye is much more sensitive to change in color than to change in brightness, much more detail can be perceived in pseudo-colored images.
5.2
Geometric transformations
Geometric transforms arc COlllmon in (;omputer graphics, and are often used in image analysis as well. They permit elimination of the geometric distortion that occurs when an image is captured. If ont.' attempts to match two different images of the same object, a geometric transformation lUay be llt.'t.,ded. We consider geometric transformations only in 2D, as this is sufficient for most digital images. One example is an attempt to match remotely sensed images of the same area taken after onc year, when the more recent image was probably not taken from prccisely the same position. To iru;pcct changes over t.he year, it [s necessary first to execute a. geometric transformation, and then snbtract one image from the other. Another cxample, commonly encountered in document image processing applications, s i correcting for document skew, which occurs when an image w ith an obvious oricntation (for example, a printed page) is scanned, or othcrwise captured, at a differcnt orientation. This differcnce may be very small, but ca.n be critical if the orientation is exploited in subsequcnt proc�ing-this is usually the case in optical character recognition (OCR). A geometric transform is a vector function T that maps the pixel (x,y) to a new position (x', y')-·an illustration of the whole region tmllsformed on a point-t.o-point basis is in Figure 5.5. T is defined by its two component equations
x' = T�(x,y) ,
y' = TlI(x, y) .
(5.9)
5.2 Geometric tra nsformations y
T
...
L------� x
119
y
L-----� x
Figure 5 . 5 :
Geometric transform on a plane.
The transformation equations Tx and Ty are either known in advance-for example, in the case of rotation, translation, scaling-or can be determined from known original and transformed images. Several pixels in both images with known correspondences are used to derive the unknown transformation. A geometric transform consists of two basic steps. First is the pixel co-ordinate transformation, which maps the co-ordinates of the input image pixel to the point in the output image. The output point co-ordinates should be computed as continuous values ( real numbers ) , as the position does not necessarily match the digital grid after the transform. The second step is to find the point in the digital raster which matches the transformed point and determine its brightness value. The brightness is usually computed as an interpolation of the brightnesses of several points in the neighborhood. This idea enables the classification of geometric transforms among other pre-processing techniques, the criterion being that only the neighborhood of a processed pixel is needed for the calculation. Geometric transforms are on the boundary between point and local operations.
5.2.1
Pixel co-ordinate transformations
Equation (5.9) shows the general case of finding the co-ordinates of a point in the output image after a geometric transform. It is usually approximated by a polynomial equation Tn
m-r
r X' = L L ark X y k , r =O k =O
m
m-T
""' ""' brk Xr Y k . yI = 6 6 r=O k =O
(5. 10)
This transform is linear with respect to the coefficients ark, brh, and so if pairs of corresponding points (x, y), (x ' , y') in both images are known, it is possible to determine ark, br k by solving a set of linear equations. More points than coefficients are usually used to provide robustness; the mean square method is often used. In the case where the geometric transform does not change rapidly depending on position in the image, low-order approximating polynomials, m = 2 or m = 3, are used, needing at least 6 or 10 pairs of corresponding points. The corresponding points should be distributed in the image in a way that can expre;;s the geometric transformation- usually they are spread uniformly. In general, the higher the degree of the approximating polynomial, the more sensitive to the distribution of the pairs of corresponding points the geometric transform is. Equation (5.9) is in practice approximated by a bilinear transform for which four pairs of corresponding points are sufficient to find the transformation coefficients
x' = ao + al x + a2 Y + a3 x Y , y' = bo + bt x + b2 y + b3 :1: y .
(5.11)
120
Chapter 5: I mage pre-processing
Even simpler is the affine transformation, for which three pairs of corresponding points are sufficient to find the coefficients x'
= 0,0 + a ] x + 0,2 Y ,
(5.12)
y' = bo + b1 X + b2 y .
The affine transformation includes typical geometric transformations such as rotation, translation, scaling, and skewing. A geometric transform applied to the whole image may change the co-ordinate system, and a Jacobian J provides information about how the co-ordinate system changes
[
\ \
_ a(X' , y') _ J , - a(x, y) -
ax'iax ay'la:r
ax'iay ay'lay
[
.
(5.13)
If the transformation is singular ( has no inverse) , then J = O. If the area of the image is invariant under the transformation, then J = 1. The Jacobian for the bilinear transform (5. 1 1 ) is (5. 14) and for the affine transformation (5.12) it is (5. 15) Some important geometric transformations are: •
Rotation by the angle cP about the origin x' -
X cos cP + y sin cP ,
y' = -x sin cP + Y cos cP ,
J •
=
(5.16)
1.
Change of scale a in the x axis and b in the
y
axis
x' = a x , y' = b x )
(5.17)
J = abo •
Skewing by the angle cP, given by x' =
:1;
+ y tan cP )
,
y =y,
(5.18)
J= 1. It is possible to approximate complex geometric transformations ( distortion ) by partitioning an image into smaller rectangular subimages; for each subimage, a simple geometric transformation, such as the affine, is estimated using pairs of corresponding pixels. The geometric transformation ( distortion ) is then repaired separately in each subimage.
5.2 Geometric transformations
S I�
b
I
--.;... ' ..a
_
-
- - - - - -
e -
- -
-
121
\
- ,
- - - - - -
Figure
5.6: Geometric distortion types.
There are some typical geometric distortions which have to be overcome in remote sensing. Errors may be caused by distortion of the optical systems, by the non-linearities in row-by-row scanning and a non-constant sampling period. Wrong position or orientation of the sensor ( or the satellite ) with respect to the object is the main cause of rotation, skew, and line non-linearity distortions. Panoramic distortion (Figure 5.6b ) appears in line scanners with the mirror rotating at constant speed. Line non-linearity distortion ( Figure 5.6a) is caused by variable distance of the object from the scanner mirror. The rotation of the Earth during image capture in a mechanical scanner generates skew distortion ( Figure 5. 6c ) . Change of distance fro m the sensor induces change-of·scale distortion ( Figure 5.6e ) . Perspective projection canses perspective distortion ( Figure 5.6f) .
5.2.2
Brightness interpolation
Assume that the planar transformation given by equation (5.9) has been accomplished, and new point co-ordinates (x', V' ) obtained. The position of the point does not in general fit the discrete raster of the output image, and the collection of transformed points gives the samples of the output image with non-integer co-ordinates. Values on the integer grid are needed, and each pixel value in the output image raster can be obtained by brightness interpolation of some neighboring non-integer samples [Moik, 1980J . Brightness interpolation influences image quality. The simpler the interpolation, the greater is the loss in geometric and photometric accuracy, but the interpolation neighborhood is often reasonably small due to computational load. The three most common interpolation methods are nearest neighbor, linear, and bi-cubic. The brightness interpolation problem is usually expressed in a dual way by determining the brightness of the original point in the input image that corresponds to the point in the output image lying on the discrete raster. Assume that we wish to compute the brightness value of the pixel ( x' , y ' ) in the ontput image where x' and y' lie on the discrete raster ( integer numbers, illustrated by solid lines in figures ) . The co-ordinates of the point (x , y) in the original image can be obtained by inverting the planar transformation in equation (5.9): (5. 19) In general, the real co-ordinates after inverse transformation ( da.'ihed lines in figures ) do not fit the input image discrete raster ( solid lines ) , and so the brightness is not known. The only information available about the originally continuous image function f (x, y) is its sampled version .Ys (l 6. :1: , k 6. y) . To get the brightness value of the point ( x , y) , the input image is resampled. Denote the result of the brightness interpolation by fn (x, y), where n distinguishes different interpolation methods. The brightness can be expressed by the convolution
Cha pter 5: I mage pre-processing
122
equation
fn ( x , y) =
00
00
L L
1=-00 k = - oo
g8 ( l �X, k �y) hn (x - l �x, y - k �y) .
(5.20)
The function hn is called the interpolation kernel. Usually, only a small neighborhood is used, outside which hn is zero. (The same idea was used in continuous image sampling recall that in equation (3.44) the function hs represented the limited impulse. ) Three examples of interpolation will illustrate this: for clarity, the common simplification � x = � y 1 is adopted. =
" ------
I
I
I
I
1
\11 - �------.I
I
1 1 1
_
:-
\. : ..� � - - ... - - - -e-: I I
-
/
-- --- -
I I I
I
•...� - _
\
I 1
I 1 1
I
I
\
\
o
-0.5
0.5
x
Figure 5.7: Nearest-neighborhood in terpolation. The discrete raster of the original image is depicted by the solid line.
Nearest-neighborhood interpolation assigns to the point ( x, y) the brightness value of the nearest point g in the discrete raster; this is demonstrated in Figure 5.7. On the right side is the interpolation kernel h I in the 1D case. The left side of Figure 5.7 shows how the new brightness is assigned. Dashed lines show how the inverse planar transformation maps the raster of the output image into the input image; full lines show the ra..'-iter of the input image. Nearest-neighborhood interpolation is given by h (x, y)
= gs ( round(x), round(y) ) .
(5.21)
The position error of the nearest-neighborhood interpolation is at most half a pixel. This error is perceptible on objects with straight-line boundaries that may appear step-like after the transformation. /
-
- - - - _JL I
I
I
- .. \
-
- - _ _ ,'_ I
I
1
1
Figure 5.8: Linear interpolation. The discrete raster of the original image is depicted by the solid line.
1
1 - - - - -_ 1 1 ,
Linear interpolation explores four points neighboring the point (:c, V), and assumes that the brightness function is linear in this neighborhood. Linear interpolation is delIlonstrated in Figure 5.8, the left-hand side of which shows which points are used for interpolation. Linear interpolation is given by the equation h (x, y)
=
(1 - a) ( 1 - b ) gs (l, k) + a (1 b) gs (l + 1, k) -
+ b ( 1 - a ) gs ( l , k + 1) + a b gs (l + 1 , k + 1 ) ,
(5.22)
5.3 Local pre-processing
l = floor(x) ,
123
a = x - l , k = floor(y) , b = y - k .
Linear interpolation can cause a small decrease in resolution, and blurring due to its averaging nature. The problem of step-like straight boundaries with the nearest neighborhood interpolation is reduced. Bi-cubic interpolation improves the model of the brightness function by approx imating it locally by a bi-cubic polynomial surface; 1 6 neighboring points arc used for interpolation. The one-dimensional interpolation kernel ('Mexican hat ' ) is shown in Figure 5.9 and is given by for 0 :::; I xl < 1 , for 1 :::; I xl < 2 , otherwise.
(5.23)
Bi-cubic interpolation does not suffer from the step-like boundary problem of nearest neighborhood interpolation, and copes with linear interpolation blurring as well. Bi-cubic interpolation is often used in raster displays that enable zooming with respect to an arbitrary point. If the nearest-neighborhood method were used, areas of the same brightness would increase. Bi-cubic interpolation preserves fine details in the image very well.
- 0.1
5.3
Figure
5_9: Bi-cubic interpolation kernel.
Local pre-processing
We shall consider methods that usc a small neighborhood of a pixel in an input image to produce a new brightness value in the output image. Such pre-processing operations are called also filtration (or filtering) if signal processing terminology is used. Local pre-processing methods can be divided into two groups according to the goal of the processing. First, smoothing aims to suppress noise or other small fluctuations in the image; it is equivalent to the suppression of high frequencies in the Fourier transform domain. Unfortunately, smoothing also blurs all sharp edges that bear important information about the image. Second, gradient operators are based on local derivatives of the image function. Derivatives are bigger at locations of the image where the image function undergoes rapid changes, and the aim of gradient operators is to indicate such locations in the image. Gradient operators have a similar effect to suppressing low frequencies in the Fourier transform domain. Noise is often high frequency in nature; unfortunately, if a gradient operator is applied to an image, the noise level increases simultaneously.
1 24
Cha pter 5: Image pre-processing
Clearly, smoothing and gradient operators have conflicting aims. Some pre-processing algorithms solve this problem and permit smoothing and edge enhancement simultaneously. Another classification of local pre-processing methods is according to the transforma tion properties; linear and non-linear transformations can be distinguished. Linear operations calculate the resulting value ill the output image pixel g ( i, j) as a linear combination of brightnesses in a local neighborhood 0 of the pixel f(i , j ) in the input image. The contribution of the pixels in the neighborhood 0 is weighted by coefficients 11,: (5.24) h (i - m , j - n) g( m , n) . f(i , j ) =
LL
(m, n ) E O
Equation (5.24) i.s equivalent to discrete convolution with the kernel h, which is called a convolution mask. Rectangular neighborhoods 0 are often used with an odd number of pixels in rows and columlls, enabling specification of the central pixel of the neighborhood. Local pre-processing methods typically use very little a priori knowledge about the image contents. It is very difficult to infer this knowledge while an image is being processed, as the known neighborhood 0 of the processed pixel is small. Smoothing operationH will benefit if some general knowledge about image degradation is available; thiH might, for instance, be Htatistica.l parameters of the noiHe. The choice of the local transformation, size, and shape of the neighborhood 0 depends strongly on the size of objects in the procesHed image. If objects are rather large, an image can be enhanced by smoothing of Hma11 degradationH.
5.3.1
I mage smoothing
Image smoothing is the set of local pre-processing methods whose predominant UHe is the suppression of image noise-it uses redundancy in the image data. Calculation of the new value is based on the averaging of brightness values in some neighborhood O. Smoothing pOHes the problem of blurring sharp edgeH in the image, and so we Hha11 concentrate on smoothing methods which are edge preserving. They are based on the general idea that the average is computed only from those pointH in the neighborhood which have similar properties to the point being processed. Local image smoothing can effectively eliminate impulHe noise or degradations ap pearing &<; thin HtripeH, but does not work if degradations are large blobs or thick stripes. The solution for complicated degradations may be to use image restoration techniques, described in Section 5.4.
Averaging. statistical principles of noise suppression Assume that the noise value v at each pixel is an independent random variable with zero mean and standard deviation a. We might capture the same static scene under the same conditions n times. From each captured image a particular pixel value gi , i = 1 , . . . , n is selected; the index i indicates to which image the pixel value gi belongs. An estimate of the correct value can be obtained as an average of these values, with corresponding noise values VI , . . . , Vn g1 + . . . + gn VI + . . . + Vn . (5.25) + n n The second term here describes the effect of the noise, which is again a random value with zero mean and standard deviation a /.;n. Thus, if n images of the same scene arc
5.3 Local pre-processing
125
available, smoothing can be accomplished without blurring the image by
n
f (i , j) n1 Ll 9k (i , j) . k= = -
(5.26)
This reasoning has roots in statistics which aims at estimating the most probable value from some population: a random sample is taken from the population and the corresponding sample mean value is calculated. If random samples were repeatedly selected and their sample mean values were calculated, we would obtain a distribution of sample mean values. This distribution of sample means has some useful properties: •
•
•
•
The mean value of the distribution of sample mean values is equal to the mean value of the population.
The distribution of sample mean values has smaller variance than the original popu lation. Suppose samples are selected, and the standard deviation of the population is 0". Then the standard deviation of the distribution of sample mean values is 0"/ Vii .
n
If the original distribution is normal (Gaussian) then the distribution of sample mean values is also normal. In fact, no matter what the shape 0 the original distribution, the distribution of sample means converges to a normal distribution. This is the central limit theorem, which is one reason why the normal distribution plays such a critical role in statistics.
From the practical point of view, it is important that not too many random selections have to be made. The central limit theorem tell us the distribution of sample mean values without the need to create them. In statistics, usually about 30 samples are considered the lowest limit of the necessary number of observations. The degree of belief in the parameter describing the population (we have only considered the mean so far) is expressed by a confidence interval.
In many cases only one image corrupted by noise is available, and averaging is then realized in a local neighborhood. Results are acceptable if the noise is smaller in size than the smallest objects of interest in the image, but blurring of edges is a serious disadvantage. In the case of smoothing within a single image, one has to assume that there are no changes in the gray-levels of the underlying image data. This assumption is clearly violated at locations of image edges, and edge blurring is a direct consequence of violating the assumptions. Averaging is a special case of discrete convolution [equation (5.24) ] . For a 3 x 3 neighborhood, the convolution mask h is
h=� 9
[i i i] 1
1
(5.27)
1
The significance of the pixel in the center of the convolution mask h or its 4-neighbors is sometimes increased, as it better approximates the properties of noise with a Gaussian probability distribution (Gaussian noise, see Section 2.3.6)
h=
1 16
[ ] � 1
! 2
� 1
(5.28)
126
Chapter 5: Image pre-processing
(a)
( b)
(0)
(d)
Figure 5.10: Noise with Gaussian distribution
and averaging filters.
(a) Original image. (b) Su
perimposed lIoise (ralldom Gaussian noise characterized by :.:ero nlean
and standard deviation x 3 averaging.
equal to one-half of the gray-level standard deviation of the original image). (c) 3 (d)
7 x 7 averaging.
There are two commonly used smoothing filters whose coefficients gradually decrease to have the values close to zero at the limit of the window. This is the best way to minimize spurious oscillations in the frequency spectrum (see the discussion of the uncertainty principle (3.24)). These arc the Gaussian and the Butterworth filters. Larger convolution masks for averaging by Gaussian filter are created according to the Gaussiau distribution formula (5.47) and the mask coefficients are normalized to have a unit suw. The Buttcrworth filter will be explained in Section 5.3.8 dealing with the local pre-processing in the frequency domain. An example will illustrate the effect of this noise suppression. Imagl..'S with low resolution (256 x 256) were chosen deliberately to show the discrete nature of the process. Figure 5.lOa shows an original image of Prague castle with 256 brightnm>es; Figure 5.lOb shows the same image with superimposed additive noise with Ga.ussian distribution; Figure 5.10c shows the result of averagillg with a 3 x 3 convolution mask (5.28)--noise is significantly reduced and the image is slightly blurred. Averaging with a larger mask (7 x 7) is demonstrated in Figure 5.1Od, where the blurring is much more serious.
5.3 Local pre-processing
127
Consider now the issue of computational cost. There is an important special case of convolution filters called separable filters. Separability in 2D means that the convolution kernel can be factorized as a product of two one-dimensional vectors, and theory provides a clue as to which convolution masks are separable. Every convolution mask with rank one is separable. As an example, consider a binomic filter. Its elements are binomic numbers which are created as a sum of the corresponding two numbers in Pascal's triangle. Consider a 2D binomic filter of size 5 x 5. Such a filter can be decomposed into a product of two ID vectors. 11, 1 , h2 .
1 4 6 4 1 4 16 24 16 4 6 24 36 24 6 4 16 24 16 4 1 4 6 4 1
h1
h2
I�
[�l
[1 4 6 4 1] .
Suppose a convolution kernel is of size 2N + 1 . Equation (5.24) allows the convolution to be rewritten taking account of special properties of a separable filter
g(x, y) =
N
N
L L
m= - N n= - N
h(m, n) f(:r +m, y + n) =
N
L
m=-N
h1 (m)
N
L
n=-N
h2 (n) f(x+ m, y+n) .
The direct calculation of the convolution according to Equation (5.24) would need, in our case of 5 x 5 convolution kernel, 25 multiplications and 24 additions for each pixel. If the separable filter is used then only 10 multiplications and 8 additions suffice. The computational saving would be more pronounced in the case of convolution of a 3D image (e.g., from a computed tomography data). Consider the 9 x 9 x 9 convolution kernel. There would be a need to use 729 multiplications and 728 additions per voxel if the convolution definition were followed. In the case of the separable filter, only 27 multiplications and 24 additions per voxel will do. The smoothing discussed thus far was linear, which has the disadvantage that edges in the image are inevitably blurred. Alternative non-linear methods exist which reduce this. The neighborhood of the current pixel is inspected and divided into two subsets by a homogeneity criterion of the user's choice. One set consists of all pixels neighboring the current pixel or any pixel already included in this set, which satisfy the homogeneity criterion. The second set is the rest of the image. This selection operation is non-linear and causes the whole filter to be non-linear. Having selected the homogeneous subset containing the current pixel, the most probable value is sought in it by a linear or non-linear technique.
Averaging using a rotating mask Averaging using a rotating mask is a non-linear smoothing method that avoids edge blurring by searching for the homogeneous part of the current pixel neighborhood and the resulting image is in fact sharpened [Nagao and Matsuyama, 1980] . The brightness average is calculated only within this region; a brightness dispersion (}2 is used as the region homogeneity measure. Let n be the number of pixels in a region R and g be the
128
Chapter 5: Image pre-processing
input image. Dispersion a 2 is calculated
as
a = � L (g ( i , j ) 2 n (i,j ) E R
-
�n
L
(i,j) E R
9 (i , j ) ) 2
(5.29)
The computational complexity ( number of multiplications ) of the dispersion calculation can be reduced if equation ( 5.29) is expressed another way:
a2
=
� n
2 ( ) ( (9 ( i, j ) ) 2 - g i , j
L j
n
(i, ) E R
(g ( i , j ) ) 2 � � ( ( iL ,j) E R -
=
(
L j
( i, ) E R
L i
( ,.i ) E R
g (i, j ) +
2 9 ( i,j ) ) +
2 � ( (i,L (g ( i , j ) ) 2 - � ( L 9 ( i ,.n) ) j) E R (i,j) E R
(
�n
L
2 9 (i , j ) ) )
eU ) E R
� ((i,jL) E R g ('1, j ) )2 )
(5.30 )
Having computed region homogeneity, we consider its shape and size. The eight possible 3 x 3 masks that cover a 5 x 5 neighborhood of a current pixel ( marked by the small cross ) are shown in Figure 5 .1 1 . The ninth mask is the 3 x 3 neighborhood of the current
;;� . . . . -:-00 '" '
:tl:l..!._l_.!. -f-+, , , ,
-f--:--f--l--t-i-
.
.;. , -+. , --.
-
, - f,
=1:":".i_-!-_l:±: -+-
-+-+-+-+-+--!-. 2
H++ tt� :
, , . . . . -+.+-+-+-+--+-.
:
.
- +-+-
, , -f-+-
.
7
Em
:t:t: +-+++ :1:±: t � t � t -!,
,
-+-..... -
- -- - -- - -
8
Figure 5 . 1 1 :
3
x
Eight possible rotated
3 masks.
pixel itself. Other mask shapes can also be used. Figure 5.12 shows another set of eight masks covering a 5 x 5 neighborhood of the current pixel. Again the ninth mask is the 3 x 3 neighborhood of the current pixel.
:i:!:i-+-t:±: :! : t : ittt:
. , . . , . .• ---+---+-.... .
2
++-
� 7
8
Figure 5 . 12: Alternative shape of eight possible rotated masks.
Another possibility is to rotate a small 2 x 1 mask to cover the 3 x 3 neighborhood of the current pixel. Image smoothing using the rotating mask technique uses the following algorithm.
Algorithm 5.2: Smoothing using a rotating mask 1. Consider each image pixel ( i , j ) .
5.3 Local pre-processing
129
2. Calculate dispersion in the mask for all possible mask rotations about pixel (i, j) according to equation (5.29). 3. Choose the mask with minimum dispersion. 4. Assign to the pixel f(i, j) in the output image f the average brightness in the chosen mask. Algorithm 5.2 can be used iteratively; the iterative process converges quite quickly to the stable state (that is, the image does not change any more) . The size and shape of masks influence the convergence-the smaller the mask, the smaller are the changes and more iterations are needed. A larger mask suppresses noise faster and the sharpening effect is stronger. On the other hand, information about details smaller than the mask may be lost. The number of iterations is also influenced by the shape of regions in the image and noise properties.
Median filtering In probability theory, the median divides the higher half of a probability distribution from the lower half. For a random variable x, the median M is the value for which the probability of the outcome x < M is 0.5. The median of a finite list of real numbers can be found by ordering the values and selecting the middle one. Lists are often constructed to be odd in length to secure uniqueness. Median filtering is a non-linear smoothing method that reduces the blurring of edges [Tyan, 1981], in which the idea is to replace the current point in the image by the median of the brightnesses in its neighborhood. The median of the brightnesses in the neighborhood is not affected by individual noise spikes and so median smoothing eliminates impulse noise quite well. Further, as median filtering does not blur edges much, it can be applied iteratively. Clearly, performing a sort on pixels within a (possibly large) rectangular window at every pixel position may become very expensive. A more efficient approach [Huang et al., 1979; Pitas and Venetsanopoulos, 1990] is to notice that as the window moves across a row by one column, the only change to its contents is to lose the leftmost column and replace it with a new right column -for a median window of m rows and n columns, mn - 2m pixels are unchanged and do not need re-sorting. The algorithm is as follows,
Algorithm 5.3: Efficient median filtering
1. Set
mn t = -2- ·
(We would always avoid unnecessary floating point operations: if m and n are both odd, round t.)
2. Position the window at the beginning of a new row, and sort its contents. Construct a histogram H of the window pixels, determine the median m, and record nm , the number of pixels with intensity less than or equal to m.
130
Chapter 5: I mage pre-processing
3. For each pixel p in the leftmost column of intensity Pg , perform Further, if Pg
::;:
m, set
4. Move the window one column right. For each pixel P in the rightmost column of intensity Pg , perform If Pg
::;:
m, set
5. If nm = t then go to (8) . 6. If nm > t then go to (7) . Repeat m=m+1, nm = nm + H[m] , until nm :::: t. Go to (8) . 7. (We have nm > t, if here) . Repeat H[m] , m=m-1,
nm = nm
-
until nm ::;: t. 8. If the right-hand column of the window is not at the right-hand edge of the image, go to (3). 9. If the bottom row of the window is not at the bottom of the image, go to (2).
The effect of median filtering is shown in Figure 5.13. The main disadvantage of median filtering in a rectangular neighborhood is its damaging of thin lines and sharp corners in the image-this can be avoided if another shape of neighborhood is used. For instance, if horizontal/vertical lines need preserving, a neighborhood s11ch as that in Figure 5.14 can be used. Median smoothing is a special instance of more general rank filtering techniques [Rosenfeld and Kak, 1982; Yaroslavskii, 1987] , the idea of which is to order pixels in some neighborhood into a sequence. The results of pre-processing are some statistics over this sequence, of which the median is one possibility. Another variant is the maximum or the minimum values of the sequence. This defines generalizations of dilation and erosion operators (Chapter 13) in images with more brightness values. A similar generalization of median techniques is given in [Borik et al., 1983]. Their method is called order statistics (OS) filtering. Values in the neighborhood are again ordered into sequence, and a new value is given as a linear combination of the values of
5.3 Local pre-processi ng
(3)
131
(b)
Figure 5.13: Median filtering. (a) Image corruptoo with impulse n oise (14% of image
covered with
bright aud dark dots). (b) Result of 3 x 3 median filtering.
area
this sequence. Median smoothing, and minimum or maximum filters, arc a special case of OS filtering.
Figure 5.14; Horizontaljvertical lill(l pl'C!>erving neighbor hood for median filtering.
Non-linear mean filter
(L:(;';)EO
)
The non-linear mean filter is another generalization of averaging techniques [Pitru; and Venetsunopulos, 1986J; it is defined by
I(m , n)
_ _
u
-,
'\" 6 ( i,j) €O a(i,j )
a(i, j) U(9 (i,i) )
,
(5.31)
where I(m, n ) is the result of the filtering, g(i, j) is the pixel in the input image, and 0 is a local neighborhood of the current pixel (m, n). The function 1l of one variable has rul inverse function u-1; the a(i,j) are weight coefficients. IT the weights a(i,j) art) constant, the filter is called homomorphic. Some homo morphic filters used in image processing are •
Arithmetic mean, u(g)
•
Harmonic mean, u(g)
•
Geometric mean, u(g)
=
== ::=
g,
l/g, logy.
Chapter 5: Image pre-processing
132
Another llon·Jinear homomorphic approach to image prt.'-processing will be discuS8ed in Section
5.3.8
dealing with methods operating ill frequency domain. The spectrum will
be non-linearly transformed there using the logarithm function.
5.3.2
Edge detectors
Edge detectors are 8 collection of very important
local image pre-processing methods
used to loca.te changes in the intensity function; edges are pixels where this function (brightness) changes abruptly. Neurological and psychophysical research suggests that locations in the image in which tlte function vallie change; abruptly are important for image perception. Edges are to a certain degTee invariant to changes of illumination and viewpoint. If only edge elements with strong magnitude (edgels) are considered, such information often suffices for image
understanding. The positive effect of such a process is that it leads to significant reduction of image data. Nevertheles." such a data reduction does not undermine understanding the content of the image (interpretation) in many cases. Edge detection provides appropriate generaliJliltion of the image data. For instance, painters of line drawings perform such a generalization, Sl.'€ Figure 5.15.
)
)
Figure 5.15: Siesta by Pablo Picasso, 1919.
We shall consider which physical phenomena in the image formation process lead to abrupt changes in image vaJues-sec Figure
5.16.
Calculus describes changes of continuous
functions using derivatives; an image function depends on two variables--co-ordinates in the image plane-and so operators describing edges are expressed using partial derivatives. A change of the image fUllctioll can be da;cribed by
1\
gradient that points in the direction
of the largest growth of the image function. An edge is a property attached to an individual pixel and is calculated from the
vector variable with magnitude and direction. The edge magnitude is the magnitude of the gradient, and the edge direction ¢ is rotated with respect to the gradient direction t/J by _900• The gradient direction gives the direction of maximum growth of the functioIl, e.g., frolll black I(i,j) = 0 to white f(i,j) 255. This is illustrated in Figure 5.18, in which closed lines are lines of equal brightness. The orientation 00 points east. image fUllction behavior in a lIeighborhood of that pixel. It is a two components,
=
Edges arc oftell lIscd in image analysis for finding region boundaries. Provided that the region has homogeneous brightnes..., its boundary is at the pixels where the image fUllction varies and so in the ideal case without noise consists of pixels with high edge
5.3 Local pre-processing
133
surface normal discontinuity
_
depth discontinuity
highlights
surface color/texture shadow/illumination discontinuity
Figure 5.16: Origin of edges, i.e., physical phenomena in the image formation process which lead to edges in images.
white
edge direCtion ((>
Figure 5.17: Detected edge
clements.
Figure 5.18: Gradient direction and edge direction.
magnitude. It can be seen that the boundary and its parts (edges) are perpendicular to the direction of the gradient. The edge profile in the gradient direction (perpendicular to the edge direction) is typical for ed.ges, and Figure 5.19 shows examples of several standard edge profiles. Roof edges are typical for objects corresponding to thin lines in the image. Edge detectors arc usually tuned for some type of edge profile. The gradient magnitude Igrad y{x,y)1 and gradient direction 1/J are continuous image functiolls calculated as
' Ig,ad 9(X,Y) I � ( �Xu9 ) + (�u9y ) ' 1/J = arg 09 09 ( ox' By )
(5.32) (5.33)
where arg{x,y) is the angle (in radians) from the x axis to the point (x,y). Sometimes we are interested only in edge magnitudes without regard to their orientations-a linear differential operator called. the Laplacian may then be used. The Laplacian has the same properties in all directions and is therefore invariant to rotation iIi the image. It is defined as �, v
' X,9) ' (X,9) 9(X,Y) 0 9(ox'l + 0 9oy2 ' .
_
-
(5.34)
Chapter
134
g
5:
Image pre-processing
x
x
Figure Image
5.19: Typical edge profiles.
x
sharpening [Rosenfeld and Ka.k, 19821 ha::; the objective of making edges stecper-
the sharpened image is intended to be observed by a human. Tbe sharpened output image f is obtained from the input image 9 as
f(i, j ) � g(i,j) - C S(i,j) ,
where
(5.35)
C is a positive coefficiellt which gives the strength of si arpeuing a.nd S(i.j) is J
a measure of the image function sheerness, calculated Ilsing a gradient operator. The
Laplacian is very often used for this purpose. Figure
5.20 gives
i-\n example of image
Image sharpening can be interpreted in the frequency domain as well. We alreAdy
sharpening using a Laplaciall.
derivative of the harmonic function sin(nx) is n cos(n:r) ; thus the higher the frequency, know that the result of the Fourier transform is a combination of harmonic functions. The
the higher the magnitude of its derivative. This is another explanation of why gradient operators enhance edges.
A similar image sharpening technique to that given in equation (5.35), called unsharp masking, is often us{.'d in printing industry applications [Jain, W89}. A signal proportional to an unsharp image (e.g., heavily blurred by a smoothing operator) is subtracted from the original image. A digital image is discrete in natttJ'e and so equations (5.32) and (5.33), containillg derivatives, must be approximated by differences. The first differences of the image 9 in the vertical direction (for fixed i) alld in the horizontal direction (for
0.7). Compare the sharpenillg
Figure 5.20: Laplace gradient operator. (a) Laplace edge image u�ing the 8-COlllLectivity mask.
(b) Sharpening lIsing the Laplace operator (equation (5.35), effect with the original image in Figure 5.lOa.
C
=
5.3 Local pre-processing
1 35
fixed j) are given by ll i g('i, .j ) = gCi, j) llj g(i,j) = g(i, j)
- g C i - n, j) , - g(i, j - ) 17,
,
(5.36)
where n is a small integer, usually 1 . The value n should be chosen small enough to provide good approximation to the derivative, but large enough to neglect unimportant changes in the image function. Symmetric expressions for the difference a
lli g (i, j) = g(i + n, j) llj g('i , j) = g('i , j + n)
- g(i - n, j) , - g (i, j - n) ,
(5.37)
are not usually used because they neglect the impact of the pixel ('i, j) itself. Gradient operators as a measure of edge sheerness can be divided into three categories: 1. Operators approximating derivatives of the image function using differences. Some of them are rotationally invariant ( e.g., Laplacian) and thus are computed from one convolution mask only. Others, which approximate first derivatives, use several masks. The orientation is estimated on the basis of the best matehing of several simple patterns. 2. Operators based on the zero-crossings of the image function second derivative ( e.g., Marr-Hildreth or Canny edge detectors) . 3 . Operators which attempt to match an image function to a parametric model of edges. The remainder of this section will consider some of the many operators which fall into the first category, and the next section will consider the second. The last category is briefly outlined in Section 5.3.6. Edge detection represents an extremely important step facilitating higher-level image analysis and therefore remains an area of active research, with new approaches continually being developed. Recent examples include edge detectors using fuzzy logic, neural networks, or wavelets [Law et al. , 1996; Wang et al., 1995; Sun and Sclabassi, 1995; Ho and Ohnishi, 1995; Aydin et al., 1996; Vrabel, 1 996; Hebert and Kim, 1996; Bezdek et al., 1996]. It may be difficult to select the most appropriate edge detection strategy; a comparison of edge detection approaches and an assessment of their performance may be found in [Ramesh and Haralick, 1994; Demigny et al., 1995] . Individual gradient operators that examine small local neighborhoods are in fact convolutions [ef. equation (5.24)] ' and can be expressed by convolution masks. Operators which are able to detect edge direction are represented by a collection of masks, each corresponding to a certain direction. Roberts operator
The Roberts operator is one of the oldest operators [Roberts, 1965] . It is very easy to compute as it uses only a 2 x 2 neighborhood of the current pixel. Its convolution masks are (5.38)
136
Cha pter 5: I mage pre-processing
so the magnitude of the edge is computed as
I g(i, j) - g(i + 1 , j + 1 ) 1 + I g( i , j + 1) - g(i + 1 , j ) l ·
(5.39)
The primary disadvantage of the Roberts operator is its high sensitivity to noise, because very few pixels are used to approximate the gradient. Laplace operator
The Laplace operator \72 is a very popular operator approximating the second derivative which gives the gradient magnitude only. The Laplacian, equation (5.34), is approximated in digital images by a convolution sum. A 3 x 3 mask h is often used; for 4-neighborhoods and 8-neighborhoods it is defined as
1
-4
(5.40)
1
A Laplacian operator with stressed significance of the central pixel or its neighborhood is
sometimes used. In this approximation it loses invariance to rotation h=
[-� -� -�] -1
2 -1
(5.41)
The Laplacian operator has a disadvantage-it responds doubly to some edges in the image. Prewitt operator
The Prewitt operator, similarly to the Sobel, Kirsch, Robinson ( as discussed later ) , and some other operators, approximates the first derivative. The gradient is estimated in eight (for a 3 x 3 convolution mask ) possible directions, and the convolution result of greatest magnitude indicates the gradient direction. Larger masks are possible. Operators approximating the first derivative of an image function are sometimes called compass operators because of their ability to determine gradient direction. We present only the first three 3 x 3 masks for each operator; the others can be created by simple rotation. hi =
U J] 1 0 -1
h2 =
[-� �] 1 0 -1 -1
-[ 1 t ] 0
h3 = - 1 0
-1 0
(5. 42)
The direction of the gradient is given by the mask giving maximal response. This is also the case for all the following operators approximating the first derivative. Sobel operator
hi =
U J] 2 0 -2
h2 =
[-� �] 1 0 -2 - 1
[ �] -1 0
h3 = -2 0
-1 0
(5.43)
5.3 Local pre-processing
hi response is y
137
The Sobel operator is often used as a simple dett.-'Ctor of horizontality and verticality of edgcs, in which case only masks responsc
x, we
and direction as
rctan(yjx)
a
Robinson operator
hi =
U
hi
and
h3
are used. If the
and
the h3
might thell derive edge strength (magnitude) as
1
-2 -1
-
ll
";X2 + y2
DC
I xl + IYI
.
[-: II 1
h2 =
-2 -1 -1
h3 =
(5.44)
-[ 1 1 -1 1 II -1
-2
(5.45)
(b1
(d) Figure 5.21:
First-derivative edge detection using Prewitt compass operators. (a) North direction
(the brighter the pixel value, the stronger the edge). (b) East direction. (e) Strong edges from (a).
(d) Strong edges from (b).
Chapter 5: Image pre-processing
138
Kirsch operator h2 =
[-� � �l -5 -5 3
[
5 h3 = -5 -5
(5.46)
To illustrate the application of gradient operators on real images, consider again the image given in Figure 5.1Oa. The Laplace edge image calculated is shown in Figure 5.20a; the value of the operator has been histogram equalized to enhance its visibility. The properties of an operator approximating the first derivative are demonstrated using the Prewitt operator- -results of others are similar. The original image is again given in Figure 5. 1Oa; Prewitt approximations to the directional gradients are in Figures 5.21a,b, in which north and east directions are shown. Significant edges (those with above-threshold magnitude) in the two directions are given in Figures 5.21c,d. 5. 3. 3
Zero-crossings of the second derivative
In the 1970s, Marr's theory (see Section 1 1 . 1 . 1) concluded from neurophysiological experiments that object boundaries are the most important cues that link an intensity image with its interpretation. Edge detection techniques existing at that time (e.g., the Kirsch, Sobel, and Pratt operators) were based on convolntion in very small neighborhoods and worked well only for specific images. The main disadvantage of these edge detectors is their dependence on the size of the object and sensitivity to noise. An edge detection technique based on the zero-crossings of the second derivative (ill its original form, the Marr-Hildreth edge detector [Marr and Hildreth, 1980] or the same paper in a more recent collection, [IVlarr and Hildreth, 1991]) explores the fact that a step edge corresponds to an abrupt change in the image function. The first derivative of the image function should have an extremum at the position corresponding to the edge in the image, and so the second derivative should be zero at the same position; however, it is much easier and more precise to fiud a zero-crossing position than an extremum. In Figure 5.22 this principle is illustrated in ID for the sake of simplicity. Figure 5.22a shows step edge profiles of the original image function with two different slopes, Figure 5.22b depicts the first derivative of the image function, and Figure 5.22c illustrates the second derivative; notice that this crosses the zero level at the same position as the edge. Considering a step-like edge in 2D, the ID profile of Figure 5.22a corresponds to a cross section through the 2D step. The steepness of the profile will change if the
jM [
I.
x
j6)'
L�x (a)
I'(x) .I
.!"(t) :
-1
�
-.LL�x
�x
I'M ]
(b)
x
I''(x);
(el
Figure 5.22: l D
zero-crossing.
edge profile of the
5.3 Local pre-processing
139
orientation of the cutting plane changes- the maximum steepness is observed when the plane is perpendicular to the edge direction. The crucial question is how to compute the second derivative robustly. One possibility is to smooth an image first (to reduce noise) and then compute second derivatives. �When choosing a smoothing filter, there are two criteria that should be fulfilled [Marr and Hildreth, 1 98 0] . First, the filter should be smooth and roughly band limited in the frequency domain to reduce the possible number of frequencies at which function changes can take place. Second, the constraint of spatial 10cali2ation requires the response of a filter to be from nearby points in the image. These two criteria are conflicting, but they can be optimized simultaneously using a Gaussian distribution. In practice, one has to be more precise about what is meant by the localization performance of an operator, and the Gaussian may turn out to be sub-optimal. We shall consider this in the next section. The 2D Gaussian smoothing operator G(x, y) (also called a Gaussian filter, or simply a Gaussian) is given by (5.47) where x, y are the image co-ordinates and (J" is a standard deviation of the associated probability distribution. Sometimes this is presented with a normalizing factor or
G(x, y)
1 "ffrr (J"
= -- e- (
x
2 + y2 )/2 u2
.
The standard deviation (J" is the only parameter of the Gaussian filter- it is proportional to the size of the neighborhood on which the filter operates. Pixels more distant from the center of the operator have smaller influence, and pixels farther than 3(J" from the center have negligible influence. Our goal is to obtain a second derivative of a smoothed 2D function f(x, V). We have already seen that the Laplace operator \7 2 gives the second derivative, and is non directional (isotropic) . Consider then the Laplacian of an image f(x, y) smoothed by a Gaussian (expressed using a convolution * ) . The operation is abbreviated by some authors as LoG, from Laplacian of Gaussian (5.4 8)
The order of performing differentiation and convolution can be interchanged because of the linearity of the operators involved (5.49)
The derivative of the Gaussian filter \7 2 G can be pre-computed analytically, since it is independent of the image under consideration. Thus, the complexity of the composite operation is reduced. For simplicity, we use the substitution r2 = x2 + y2 , where r measures distance from the origin; this is reasonable, as the Gaussian is circularly symmetric. This substitution converts the 2D Gaussian, equation (5.47) , into a 1D function that is easier to differentiate (5.50) The first derivative G' ( r ) is then 1 G' ( r ) = - 2 (J"
r e
_1'2 / 2 u2
(5 . 5 1 )
Chapter 5: Image pre-processing
140
and the second derivative G" (r), the Laplacian of a Gaussian, is Gil ( r)
=
2 r ( a2 a 2
�
_
)
2 1 e-r2 / ,,2
•
(5.52)
After returning to the original co-ordinates x , y and introducing a normalizing multiplica tive coefficient we get a convolution mask of a LoG operator: c,
(5.53) where normalizes the sum of mask elements to zero. Because of its shape, the inverted LoG operator is commonly called a Mexican hat. An example of a 5 x 5 discrete approximation [Jain et aI., 1995] ( wherein a 17 x 17 mask is also given) is c
H
0 -1 0 -1 - 2 - 1 - 2 16 -2 -1 -2 - 1 0 -1 0
Of course, these masks represent truncated and discrete representations of infinite continu ous functions, and care should be taken in avoiding errors in moving to this representation [Gunn, 1999]. Finding second derivatives in this way is very robust. Gaussian smoothing effectively suppresses the influence of the pixels that are more than a distance 3a from the current pixel; then the Laplace operator is an efficient and stable measure of changes in the image. After image convolution with \l 2G , the locations in the convolved image where the zero level is crossed correspond to the positions of edges. The advantage of this approach compared to classical edge operators of small size is that a larger area surrounding the current pixel is taken into account; the influence of more distant points decreases according to the a of the Gaussian. In the ideal case of an isolated step edge, the a variation does not affect the location of the zero-crossing. Convolution masks become large for larger a; for example, a = 4 needs a mask about 40 pixels wide. Fortunately, there is a separable decomposition of the \l 2 G operator [Huertas and Medioni, 1986] that can speed up computation considerably. The practical implication of Gaussian smoothing is that edges are found reliably. If only globally significant edges are required, the standard deviation a of the Gaussian smoothing filter may be increased, having the effect of suppressing less significant evidence. The \l2G operator can be very effectively approximated by convolution with a mask that is the difference of two Gaussian averaging masks with substantially different a- - this method is called the difference of Gaussians, abbreviated as DoG. The correct ratio of the standard deviations a of the Gaussian filters is discussed in [Marr, 1982] . Even coarser approximations to \l2 G are sometimes used-the image is filtered twice by an averaging operator with smoothing masks of different sizes. When implementing a zero-crossing edge detector, trying to detect zeros in the LoG or DoG image will inevitably fail, while naive approaches of thresholding the LoG/DoG image and defining the zero-crossings in some interval of values close to zero give piecewise disconnected edges at best. To end up with a well-functioning second-derivative edge
5.3 detector, it is Ilecc.'isary to implement
I:l.
Local pre-processing
141
true zero-crossing detector. A simple detector
may identify a zero crossing in a moving
2 x 2 window,
assigning an edge
label
to any
one corner pixel, say the upper left, if LoG/DoG image values of both polarities occur in the 2 x 2 window; 110 edge label would be given if values within the window arc either all
positive or all negative. Another post-processing step to avoid detection of zero-crossings corresponding to nonsignificant edges in regions of almost constant gray-level would admit only those zero-crossings for which there is sufficient edge evidence from a first-derivative edge detector. Figure 5.23 provides several examples of edge detection using zero crossings of the second derivative.
1-)
Ibl
(c)
Idl
Figure 5.23: Zero-crossings of the second derivative, see Figure 5. lOa for the original image. (a) DoG image (171 :::: 0.10, 172 := 0.09), dark pixels correspond to negative DoG values, bright
pixels represent positive DoG valul;$. (b) Zero-crossin&, of the DoG image. (c) DoG zero-crossing edges after removing edges lacking 6.rst-del·ivative support. (d) LoG zero-crossing edges (0" :: 0.20) after removing edge::; lacking first-derivative support-note different scale of edges due to different Gaussian smoothing parameters.
142
Chapter 5: I mage pre-processing
Many other approaches improving zero-crossing performance can be found in the literature [Qian and Huang, 1994; Mehrotra and Shirning, 1996]; some of them are llsed in pre-processing [Hardie and Boncelet, 1995] or post-processing steps [Alparone et al., 1996]. The traditional second-derivative zero-crossing technique has disadvantages as well. First, it smoothes the shape too much; for example, sharp corners are lost. Second, it tends to create closed loops of edges (nicknamed the 'plate of spaghetti' effect) . Although this property was highlighted as an advantage in early papers, it has been seen as a drawback in many applications. Neurophysiological experiments [:Marr, 1982; Ullman, 1981] provide evidence that the human eye retina in the form of the ganglion cells performs operations very similar to the '\l 2 G operations. Each such cell responds to light stimuli in a local neighborhood called the receptive field, which has a center-surround organi�ation of two complementary types, off-center and on-center. When a light stimulus occurs, activity of on-center cells increases and that of off-center cells is inhibited. The retinal operation on the image can be described analytically as the convolution of the image with the '\l 2 G operator. 5.3.4
Scale in image processing
Many image processing techniques work locally, theoretically at the level of individual pixels--edge detection methods are an example. The essential problem in snch computa tion is scale. Edges correspond to the gradient of the image function, which is computed as a difference between pixels in some neighborhood. There is seldom a sound reason for choosing a particular size of neighborhood, since the 'right' size depends on the size of the objects under investigation. To know what the objects are assumes that it is clear how to interpret an image, and this is not in general known at the pre-processing stage. The solution to the problem formulated above is a special case of a general paradigm called the system approach. This methodology is common in cybernetics or general system theory to study complex phenomena. The phenomenon under investigation is expressed at different resolutions of the description, and a formal model is created at each resolution. Then the qualitative behavior of the model is studied under changing resolution of the description. Such a methodology enables the deduction of meta-knowledge about the phenomenon that is not seen at the individual description levels. Different description levels are easily interpreted as different scales in the domain of digital images. The idea of scale is fundamental to Marr's edge detection technique, introduced in Section 5.3.3, where different scales are provided by different sizes of Gaussian filter masks. The aim was not only to eliminate fine scale noise but also to separate events at different scales arising from distinct physical processes [Marr, 1982]. Assume that a signal has been smoothed with several masks of variable sizes. Every setting of the scale parameters implies a different description, but it is not known which one is correct; for many tasks, no one scale is categorically correct. If the ambiguity introduced by the scale is inescapable, the goal of scale-independent description is to reduce this ambiguity as much as possible. Many publications tackle scale-space problems, e.g., [Hummel and Moniot, 1989; Perona and Malik, 1990; Williams and Shah, 1990; Mokhtarian and Mackworth, 1992; Mokhtarian, 1995; Morrone et al., 1995; Elder and Zucker, 1996; Aydin et al. , 1996; Lindeberg, 1996]. A symbolic approach to constructing a multi-scale primitive shape description to 2D binary (contour) shape images is presented in [Saund, 1990] , and the
5.3 Local pre-processing
143
use of a scale-space approach for object recognition is in [Topkar et 11.1 , 1990]. Here we shall consider just three examples of the applicatioll of multiple scale description to image analysis. The first approach [Lowe, 1989] aims to process planar noisy curves at a range of scales-the segment of curve that represents the underlying structure of the scene needs to be found. The problem is illustrated by an example of two noisy curves; see Figure 5.24. One of these may be interpreted as a closed (perhaps circular) curve, while the other could be described as two intersecting straight lilles.
Figure
5.24: Curves that may be analY
Local tangent direction a.nd curvature of the curve are significant only with some idea of scale after the curve is smoothed by a Gaussian filter with varying standard deviations. A second approach [Witkin, 1983] , called scale-space filtering, tries to describe signals qualitatively with respect to scale. The problem was formulated for 1D signals f(x), but it can easily be generalized for 2D functions as images. The original 1D signal f(x) is smoothed by convolution with a 1D Gaussian
(5.54 ) If the standard deviation a is slowly changed, the function
F(.T , a) = f(x) * G(x, a)
(5.55)
represents a surface on the ( a) plane that is called the scale-space image. Inflection points of the curve F(x, ao) for a distinct value ao ;r,
[)2 F(x, ao) [).T2
=0
and
(5.56)
describe the curve f (x) qualitatively. The pm;itions of inflection points can be drawn as a set of curves in (x, a) co-ordinates (see Figure 8 . 15). Coarse to fine analysis of the curves corresponding to inflection points, i.e., in the direction of decreasing value of the a, localizes large-scale events. The qualitative information contained in the scale-space image can be transformed into a simple interval tree that expresses the structure of the signal f(x) over all observed scales. The interval tree is built from the root that corresponds to the largest scale (aml1x), and tlwn the scale-space image is searched in the direction of decreasing a. The interval tree branches at those points where new curves corresponding to inflection points appcar (see Chapter 8 and Section 8.2.4) . The third example of the application of scale is that used by the popular Canny edge detector. Since the Canny detector is a significant and widely used contribution to edge detection techniques, its principles will be explained in detail.
144
Chapter 5: Image pre-processing
5.3.5
Canny edge detection
Canny proposed an approach to edge detection [Canny, 1983; Brady, 1984; Canny, 1986] that is optimal for step edges corrupted by white noise. The optimality of the detector is related to three criteria. •
•
•
The detection criterion expresses the fact that important edges should not be missed and that there should be no spurious responses. The localization criterion says that the distance between the actual and located position of the edge should be minimal. The one response criterion minimizes multiple responses to a single edge. This is partly covered by the first criterion, since when there arc two responses to a single edge, one of them should be considered as false. This third criterion solves the problem of an edge corrupted by noise and works against non-smooth edge operators [Rosenfeld and Thurston, 1971].
Canny's derivation of a new edge detector is based on several ideas.
1 . The edge detector was expressed for a 1D signal and the first two optimality criteria.
A closed-form solution was found using the calculus of variations. 2. If the third criterion ( multiple responses ) is added, the best solution may be found by numerical optimization. The resulting filter can be approximated effectively with error less than 20% by the first derivative of a Gaussian smoothing filter with standard deviation [Canny, 1986] ; the reason for doing this is the existence of an effective implementation. There is a strong similarity here to the Marr-Hildreth edge detector [Marr and Hildreth, 1980] , which is based on the Laplacian of a Gaussian-see Section 5.3.3. 3. The detector is then generalized to two dimensions. A step edge is given by its position, orientation, and possibly magnitude ( strength ) . It call be shown that convolving an image with a symmetric 2D Gaussian and then differentiating in the direction of the gradient ( perpendicular to the edge direction ) forms a simple and effective directional operator ( recall that the Marr-Hildreth zero-crossing operator does not give information about edge direction, as it uses a Laplacian filter ) . Suppose G is a 2D Gaussian [equation (5.47)] and assume we wish to convolve the image with an operator Gn which is a first derivative of G in the direction n oG (5.57) Gn = = n \l G . o (j
n
The direction n should be oriented perpendicular to the edge. Although this direction is not known in advance, a robust estimate of it based on the smoothed gradient direction is available. If f is the image, the normal to the edge n is estimated as
(5.58) The edge location is then at the local maximum of the image f convolved with the operator Grt in the direction n
(5.59)
5.3 Local pre-processing
145
Substituting in equation (5.59) for Gn from equation (5.57), we get
(5.60) This equation (5.60) illustrates how to find local maxima in the direction perpendicular to the edge; this operation is often referred to as non-maximal suppression (see also Algorithm 6.4). As the convolution and derivative are associative operations in equation (5.60), we can first convolve an image 1 with a symmetric Gaussian G and then compute the directional second-derivative using an estimate of the direction n computed according to equation (5.58). The strength of the edge (magnitude of the gradient of the image intensity function n is measured as
I Gn 1 1 = 1 \7( G n l ·
*
*
(5.61)
A different generalization of this optimal detector into two dimensions was proposed by Spacek [Spacek, 1986], and the problem of edge localization is revisited in [Tagare and deFigueiredo, 1990] .
4. Spurious responses to the single edge caused by noise usually create a 'streaking'
problem that is very common in edge detection in general. The output of an edge detector is usually thresholded to decide which edges are significant, and streaking means the breaking up of the edge contour caused by the operator fiuctuating above and below the threshold. Streaking can be eliminated by thresholding with hysteresis. If any edge response is above a high thTeshold, those pixels constitute definite edge output of the detector for a particular scale. Individual weak responses usually correspond to noise, but if these points are connected to any of the pixels with strong responses, they are more likely to be actual edges in the image. Such connected pixels are treated as edge pixels if their response is above a low thTeshold. The low and high thresholds are set according to an estimated signal-to-noise ratio [Canny, 1986] (see also Algorithm 6.5).
5. The correct sca1c for the operator depends on the objects contained in the image.
The solution to this unknown is to use multiple scales and aggregate information from them. Different scales for the Canny detector are represented by different standard deviations of the Gaussians. There may be several scales of operators that give significant responses to edges (i.e., signal-to-noise ratio above the threshold); in this case the operator with the smallest scale is chosen, as it gives the best localization of the edge. Canny proposed a feature synthesis approach. All significant edges from the operator with the smallest scale are marked first, and the edges of a hypothetical operator with larger are synthesized from them (i.e., a prediction is made of how the large should perform on the evidence gleaned from the smaller (j--see also Section 5.3.4 and Figure 8.15) . Then the synthesized edge response is compared with the actual edge response for larger Additional edges are marked only if they have a significantly stronger response than that predicted from synthetic output. This procedure may be repeated for a sequence of scales, a cumulative edge map being built by adding those edges that were not identified at smaller scales. 17
17
17
17.
146
Cha pter 5: I mage pre-processing
Algorithm 5.4: Canny edge detector
1. Convolve an image f with a Gaussian of scale (1 . 2. Estimate local edge normal directions using equation (5.58) for each pixel in the n
3. 4.
5. 6. 7.
image. Find the location of the edges using equation (5.60) (non-maximal suppression). Compute the magnitude of the edge using equation (5.61). Threshold edges in the image with hysteresis (Algorithm 6.5) to eliminate spurious responses. Repeat steps (1) through (5) for ascending values of the standard deviation (1 . Aggregate the final information about edges at multiple scale using the 'feature synthesis' approach.
( a) Figure 5.25:
(b)
Canny edge detection at two different scales.
Figure 5.25a shows the edges of Figure 5.10a detected by a Canny operator with 1.0. Figure 5.25b shows the edge detector response for (1 = 2.8 (feature synthesis has not been applied here) . Canny's detector represents a complicated but major contribution to edge detection. Its full implementation is unusual, it being common to find implementations that omit feature synthesis-that is, just steps 1 -5 of Algorithm 5.4. Recent developments of the optimal border detection concept have focused on optimal detection of more general edges than the step and ramp edges considered in Canny's original, and other early, approaches. Examples of Canny edge detector extensions can be fonnd in [Laligant et al., 1994; Jalali and Boyce, 1995; Sorrenti, 1995; Demigny et al., 1995; Mehrotra and Shiming, 1996]. (1 =
5.3 Local pre-processing
147
5.3.6 Parametric edge models Parametric models are based on the idea that the discrete image intensity function can be considered a sampled and noisy approximation of the underlying continuous or piecewise continuous image intensity function [Nevatia, 1977] . 'iVhile the continuous image intensity function is not known, it can be estimated from the available discrete image intensity function and image properties can be determined from this continuous estimate, possibly with sub-pixel precision. Since modeling the image as a single continuous function leads to high-order intensity functions in x and y, it is practically impossible to represent image intensities using a single continuous function. Instead, piecewise continuous function estimates called facets are used to represent (a neighborhood of) each image pixel . Such image representation is called the facet model [Haralick and Watson, 1981; Haralick, 1984; Haralick and Shapiro, 1992]. The intensity function in a pixel neighborhood can be estimated using models of different complexity. The simplest one is the flat facet model that uses piecewise constants and each pixel neighborhood is represented by a flat function of constant intensity. The sloped model uses piecewise linear functions forming a sloped plane fitted to the image intensities in the pixel neighborhood. Quadratic and bi-cubic facet models employ correspondingly more complex functions. A thorough treatment of facet models and their modifications for peak noise removal, segmentation into constant-gray-level regions, determination of statistically significant edges, gradient edge detection, directional second-derivative i:ero-crossing edge detection, and line and corner detection is given in [Haralick and Shapiro, 1992] . Importantly, techniques for facet model parameter estimation are given there. To provide an edge detection example, consider a bi-cubic facet model
the parameters of which are estimated from a pixel neighborhood [the co-ordinates of the central pixel arc (0 , 0)] . To determine the model parameters, a least-squares method with singular-value decomposition (see Section 3.2.9) may be used. Alternatively, when using a 5 x 5 pixel neighborhood, coefficients Ci can be computed directly using a set of ten 5 x 5 kernels that are provided in [Haralick and Shapiro, 1992] . Once the facet model parameters are available for each image pixel, edges can be detected as extrema of the first directional derivative and/or zero-crossings of the second directional derivative of the local continuous facet model functions. Edge detectors based on parametric models describe edges more precisely than convolution-based edge detectors. Additionally, they carry the potential for sub-pixel edge localization. However, their computational requirements are much higher. Promising extensions combine facet model with Canny's edge detection criteria (Section 5.3.5) and relaxation labeling (Section 6.2.2) [Matalas et al., 1997] . 5 .3.7
Edges in multi-spectral images
One pixel in a multi-spectral image is described by an n-dimensional vector, and brightness values in n spectral bands are the vector components. There are several possibilities for the detection of edges in multi-spectral images [Faugeras, 1993] . The first is to detect edges separately in individual image spectral components llsing the ordinary local gradient operators mentioned in Section 5.3.2.
Cha pter 5: Image pre-processing
148
Individual images of edges can be combined to get the resulting image, with the value corresponding to edge magnitude and direction being the maximal edge value from all spectral components. A linear combination of edge spectral components can also be used, and other combination techniques are possible [Nagao and Matsuyama, 1980J. A second possibility is to use the brightness difference of the same pixel in two different spectral components. This is a very informative feature for classification based on properties of the individual pixel. The ratio instead of the difference can be used as well [Pratt, 1978], although it is necessary to assume that pixel values are not zero in this case. A third possibility is to create a multi-spectral edge detector which uses brightness information from all n spectral bands; this approach is also applicable to multi-dimensional images forming three- or higher-dimensional data volumes. An edge detector of this kind was proposed in [Cervenka and Charvat, 1987J . The neighborhood used has size 2 x 2 x n pixels, where the 2 x 2 neighborhood is similar to that of the Roberts gradient, equation (5.38) . The coefficients weighting the influence of the component pixels are similar to the correlation coefficients. Let f(i,j) denote the arithmetic mean of the brightnesses corresponding to the pixels with the same co-ordinates (i, j) in all n spectral component images, and fr be the brightness of the rth spectral component. The edge detector result in pixel (i,j) is given as the minimum of the following expressions:
L:�= l [d(i,j)] [d(i + 1, j + 1 )] L:�= l [d (i + 1 ,j)] [d(i,j + 1 )] JL:�=l [d(i,j)] 2 L:�=l [d(i + 1 ,j + 1 ) ] 2 JL:�= l [d(i + 1 ,j) ] 2 L:�=l [d(i , j + 1 )] 2
where d(k, I)
=
fr(k, I ) - f (k, l) .
'
(5.63)
This multi-spectral edge detector gives very good results on remotely sensed images. 5.3.8
Local pre-processing in the frequency domain
Section 3.2.4 noted that the Fourier transform makes convolution of two images in the frequency domain very easy. In Sections 5.3 , many filters used in image pre-processing were presented-the convolution masks in most cases were used for image filtering or image gradient computation. It is natural to think about processing these (and many other) convolutions in the frequency domain. Such operations are usually called spatial frequency filtering.
Assume that f is an input image and F is its Fourier transform. A convolution filter h can be represented by its Fourier transform H; h may be called the unit pulse response of the filter and H the frequency transfer function, and either of the representations h or H can be used to describe the filter. The Fourier transform of the filter output after an image f has been convolved with the filter h can be computed in the frequency domain
G(n, v ) = F(n , v ) H( n, v ) , .*
(5.64)
where operation represents a element-by-clemcnt multiplication of matrices F and H, not a matrix multiplication. Matrices F and H must be of the same size. The filtered image g can be obtained by applying the inverse Fourier transform to G- --equation (3.28). Some basic examples of spatial filtering are linear low-pass, high-pass, and band pass frequency filters. -*
5.3 •
Local pre-processing
149
low-pass filter is dcfirl(.-'(! by a frequeucy transfer function H(lL,V) with small values at pointt:i located far from the co ordinate origin in the fn.'qucncy domain (that it:i, small transfer values for high spatial frequencies) and large values at points close to the origin (large transfer values for low spatial frequ ncies) -see Figure 5.26a. It preserve!; low spatial frequenciet;; and suppresses high !;patial frequencies, and has behavior similar to smoothing by standard averaging-it blurs t:iharp edges. A
-
c
Figure 5.26: Frequency filters db;pla.yed in (c) Band-pass filter. •
•
(b) 3�.
-
(0)
(fl.) Low-pass filter. (b) High-pass filter.
high-pass filter s i defined by small transfer function values located around the frequency co-ordinate system origin, and larger values outside this area-larger transfer coefficients for higher frequencies (Figure 5.26b). A
Band-pass filters, which select frequencies in a certain rang-c for enhancement, are constructed in a similar way, and also filters with directional response, etc. (Fig ure 5.26c).
The most common image enhancement problems include noise suppression, edge en hancement, and removal of noise which is structured in the frequency spectrum. Noise represents a high-frequency image component, lind to suppress it, the magnitudes of image frequencies of the noise must be decreased. This can be acJlieved by applying a. low-pass filter as shown in Figure 5.27, which demonstrates the principles of frequency filtering on Fourier image spectra; the original image spectrum is Illultiplierl by the filter spectrum and a low-frequency image spectrum results. Unfortunately, as a result of noise suppression, all high-£requeney phenomena are suppressed, including high fn:qucncie; that are not related t.o noise (sharp edges, lines, etc.). Low-pass filtering results in a blurred image. Again, edges represent a high-frequency image phenomenon. Therefore, to enhance the edges, low-frequency components of the image spectrum must be suppressed, and to achieve this, a high-frequency filt.er must be applied. To remove noise which is structured in the frequency domain, the filter design must include a priori knowk-clge about the lIoise properties. This knowledge may be acquired either from the image data or f om the corrupted image Fourier spectrum, where the structured noise usua!!y causes notable peaks. Some examples of frequency domain image filt.ering are shown in Figures 5.27-5.30. The original image was shown in Figure 3.8 and its frequency spectrum in Figure 3.7. Figure 5.28 shows results after application of a high-pass fitter foHowed by an inverse Fourier transform. It can be seen that edges represent high-frequency phenomena in the image. Results of band-pass filtering can be seen in Figure 5.29. Figure 5.30 gives an even r
150
Chapter 5: Image pre-processing
(0)
(b)
(0)
(d)
Figure 5.27: Low-pass frequency-domain filtcring--·for the original m i age and its spectrum see Figure 3.7. (a) Spectrum of a low-pasll filter<-'<1 image, all higher frequencies filtered out. (b) Image resulting £rOlI1 the inverse Fourier transform a.pplied to �pectrum (a). (c) Spectrum of a low-pass filtered image, only very high frequencies filten.'d out. (d) Inverse fourier transform applied to spectrum (cl.
more powerful example of frequeocy filtering-removal of periodic lIoise that was present in the image. Thc vertical periodic noise lines in the original image are transformed into frequency spectrum peaks after the transform. To remove these frequencies from an image, a filter was designed which suppresses the periodic noise in the image, which is visible as white circular areas. Discrete image transforms are computationally expensive (although wit.h t.he continuous increase in routinely available computing power, this is not
more) , but note that the Fourier transform can be obtained in real time using optical processing methods (for example, a convex lens may produce the Fourier transform) [Goodman, 1996J. There arc several filters which prove useful for filtering in the frequency domain : two important representativC8 of them are the Gaussian and Butterworth filters. Choose all isotropic filter for Simplicity, D(u, ti) = D{r) Ju2 + v2. Let Do be a parameter of the as important an issue any
:::::
5.3 local pre-processing
(al
151
(bl
•
(dl
« I
Figure 5.28: High-pass frequency domain filtering. (a) Spectrum of a high-pass filtered image, only very low frequencies filtered out. (b) Image resulting from the inverse Fourier transform applied La !lpectrum (a). (e) Spectrum of a high-pass filtered image, all lower frequencies filtered out. (d) Inverse Fourier transform applied to s)X.'Ctrum (e).
(D(U,"))')
filter called the cut-off frequency. For the Gaussian Do coincides with the dbpersion 0-2.
(
The Fourier spectrum of a low-pass Gaussian filter
G1ow{u,1I) = exp - '2 The Duttenvorth filter [Butterwort.h,
1930]
1
Glow
is
(5.65)
Do
has its root in the era of circuit theory in
electrical engineering. It is specified to bave maximaHy Rat frequency response over a spectrum band, and is also called a 'maximally flat magnitude filter'. The frequency response of the
20
low-pass Butterworth filter
Blow of degree
n
is
(5.66)
152
Chapter 5: Image pre-processing
(bl
Figure 5.29: Band-pass frequency domain filtering. (a) Spe<:trum of a band-pass-filtered image, low and high frequencies filtered out. (b) Image resulting from the inverse Fourier transform applied to spectrum (a). The usual Butterworth filter degree is n = 2, which will be used here.
illustrates the shape of the Gaussian and Butterworth filters
for Do = 3 in
Figure 5.31 10 plots.
The high-pass filter is created easily from the low-pass filter. If the Fourier frequency spectrum of a low-pas.o:; filter is vertically,
Hhigh
=
1
-
Hluw , the high-pass filter can be created by just flipping it
Hlow.
The most substantial progress in discrete image transforms was probably motivated by image transmissiO!l and image data storage requirements. The maiu goal is to decrease the amount of data necessary for image representation and to decrease the amount of the \Vorld \Vide Web; many multimedia presentations rely on image compression to store
transferred or stored data. Compressed images are freQucntly used for transmission using
large !lumbers of images and movies on CD-ROMs, and standards cxist for such image compression. For cxample, the commonly used .1PEG and MPEG image compression standards are based on the discrete cosine transform presented here (Section 3.2.6). Another large application area can be found in image description, especially in texture description and recognition (sec Section 15.1.1). Another useful pre-proc(.'SSing technique operating in the frequency domain is an instance of homomorphic
filtering, discussed at t.he end of ScctiOll 5.3.1.
Homomorphic
filtering is used to remove multiplicative noise. The aim of the particular homomorphic filtering to be discus. o:;ed here is to Simultaneously increase contrast and normalize image intensity across the image.
The assumption is that the image function
f(x, y)
can be factorized as a product of
i(x,y) and the i(x,y)r(x,y). These two
two independellt multiplicative components in eadl pixel: illumination reflectance
r(x,y)
at the point in the observed scene,
f(x,y)
=
components can be separated ilt some images because the illumination component tends to vary slowly and the reflectance component varies more Quickly as the scene looks differently because it contains dissimilar objects.
5.3 local pre-processing
153
(b)
(a)
« )
5.30: Periodic noise removal. (a) Noisy image. (b) hnAge spectrum u.o;I..'({ for image reconstruction·-note that the areas of frequencies corresponding with periodic vertical Jines are filtered out. (c) Filtered image.
Figure
/ Butterworth
.A
-
IO
-e
'
"
�
-
-
2
0
,
•
&
8
�
,.
10
Figure 5.31: Gaussian alld Butter worth low-pass filters.
154
Chapter 5: I mage pre-processing
The idea of the separation is to apply a logarithmic transform to the input image. The logarithm of the product is to the sum of the factors
( 5.67 ) z (x, y) = log f (x , y) = log i (x , y) + log r (x, y ) . If the image z(x, y) is converted to Fourier space ( denoted by capital letters ) then its additive components remain additive due to the linearity of the Fourier transform
Z(u, v)
=
1(u, v) + R (u, v) .
( 5.68 )
Assume that the Fourier spectrum Z ( 71" v ) is filtered by the filter H (u, v) and the spectrum 5 (u , v) is the result
5 (u, v)
=
H(u, v)
.*
Z(u, v)
=
H(u, v)
.*
1(u, v) + H(u, v)
.*
R (u, v) ,
( 5.69 )
where operation . * means element-by-clement multiplication of matrices. Usually the high-pass filter is used for this purpose. Assume a high-pass Butterworth filter; it has to be damped in order not to suppress low frequencies entirely as they bear needed information too. The Butterworth filter modified by damping coefficient 0.5 is shown in Figure 5.32.
for homomorphic filtration -10
-6
-4
Butterworth
-2
.�ojoL-- ---- .-.--.- .2 4 6 8 10 -+
r
Figure 5.32: High-pass filter used in homomorphic filtering. It is the But terworth filter damped by a 0.5 co efficients to keep also some low fre quencies.
Having the filtered spectrum 5( 1L, v) , we can return to spatial coordinates using the inverse Fourier transform, s(x, y) = F- 15 (u, v) . Recall that the logarithm was first applied to the input image f(x, y) in Equation ( 5.67) . Now the image has to be transformed by the logarithm inverse function; this inverse function is the exponential. The result-the image g(x, y) filtered by the homomorphic filter-is given by g(x, y) = exp (s(x, y)) . An illustration of the effect of homomorphic filtration is in Figure 5.33, an image of a person in a dark tunnel with strong illumination at the entrance. Detail of the tunnel surface on the top and right side are not visible because the surface is too dark. The result of homomorphic filtration is in Figure 5.33 ( b ) . More details can be seen in this image.
5.3.9
Line detection by local pre-processing operators
Several other local operations exist which do not belong to the taxonomy given in Section 5.3, as they are used for different purposes as, e.g., line finding, line thinning,
5.3
C.I
Loca l pre-processing
155
Cbl
Figure 5.33: Illustration of homomorphic filtra.tion. (3) Original image. (b) Result of homomor phic filtration. Courtesy 0/ Tomas Svoboda, Czech Technica.l Un;ver�itll, Prague.
'interest points'
and line filling operators. The second group of operators finds
'locations of
interest' in the image.
or
There is yet another class of local nonlinear
operators, mathematical morphology techniques, which is mentioned in Chapter
13.
Recall that one of the reasons why edges are being detected. is that they bear a lot of information about underlying objects in the scene. Taking just edge elements n i stead of all pixels reduces the amount of data which has to be processed. The edge detector
s i
a general tool which does not depend. on the content of the particular image. Thc
detected edges are to some degree robust as they do not depend much on small changes in illumination, viewpoint change, etc. It is interesting to seek yet richer features which can be reliably detected in the image and which can outperform simple edge detectors in some classes of applications. Line detectors and corner detectors arc some such. Line dctecton> are used to detcct linear objects such as dimension lines in engineering drawings or railways or roads in satellite images. Corner detectors and other interest point.like detectors are used mainly to register two or more images one to the other (e.g, in stereo vision, motion analysis, panorama stitching, object recObrnition from images) or to index the image or dominant objects in it to an image database.
Line finding operators
aim to find very thin curves in the image; it s i assumed
that curves do not bend sharply. Such curves and straight lines are called lines for the
purpose of describing this technique. If a cross section perpendicular in direction to the tangent of a line is examined, we get a roof profile (see Figure
5.19)
when eX!lJ.11ining
edges. We ru;sume that the width of the lines is approximately one or two pixels. The presence of
a.
line may be detected by local convolution of the image with
1991; Petrou, 19!J3]. The 3 x 3 is able to detect lines rotated modulo
convolution kernels which serve as line pa.tterns [Vernon,
[-; ; ;]
simplest colltdion of four such patterns of size the angle
45".
Three of four such convolution kernels are
-
h, �
-
-1
-1
(5.70)
-1
A similar principle can be applied to bigger masks. The case of 5
x 5 masks is common.
Such line detecton; sometimes produce more lines than needed, a.nd other non·linear constraints may be added to reduce this number. More sophisticated approaches determine
156
Chapter 5: I mage pre-processing
lines in images as ridges and ravines using the facet model [Haralick and Shapiro, 1992] . Line detection is frequently used in remote sensing and in document processing; examples include [Venkateswar and Chellappa, 1992; Tang et al., 1997] . Local information about edges is the basis of a class of image segmentation techniques that are discussed in Chapter 6. Edges which are likely to belong to object boundaries are usually found by simple thresholding of the edge magnitude--such edge thresholding does not provide ideal contiguous boundaries that are one pixel wide. Sophisticated segmentation techniques that are dealt with in the next chapter serve this purpose. Here, much simpler edge thinning and filling methods are described. These techniques are based on knowledge of small local neighborhoods and are very similar to other local pre-processing techniques. Thresholded edges are usually wider than one pixel, and line thinning techniques may give a better result. One line thinning method uses knowledge about edge orientation and in this case edges are thinned before thresholding. Edge magnitudes and directions provided by some gradient operator are used as input, and the edge magnitudes of two neighboring pixels perpendicular to the edge direction are examined for each pixel in the image. If at least one of these pixels has edge magnitude higher than the edge magnitude of the examined pixel, then the edge magnitude of the examined pixel is assigned a zero value. This technique is called non-maximal suppression and is similar to the idea mentioned in conjunction with the Canny edge detector. There are many line thinning methods which we do not present here. In most cases the best line thinning is achieved using mathematical morphology methods which are explained in Chapter 13.
5.3.10
Detection of corners (interest points)
In many cases it is advantageous to find pairs of corresponding points in two similar images; we came across this fact in Section 5.2 when considering geometric transforms. Knowing the position of corresponding points enables the estimation of parameters describing geometric transforms from live data. The same transformation usually holds for almost all pixels of the image. The necessary number of corresponding pairs of points is usually rather small and is equal to the number of parameters of the transform. We shall see later on that finding corresponding points is also a core problem in the analysis of moving images ( Chapter 1 6 ) , and for recovering depth information from pairs of stereo images ( Section 1 1.5). In general, all possible pairs of pixels should be examined to solve this correspon dence problem, and this is very computationally expensive. If two images have n pixels each, the complexity is O(n2 ) . This process might be simplified if the correspondence is examined among a much smaller number of points, called interest points. An interest point should have some typical local property [Ballard and Brown, 1982] . For example, if square objects are present in the image, then corners are very good interest points. In this section, two representatives from the wide class of interest points detectors will be explained. The first are corner detectors and the second one are the more rich structures called l'vISERs ( Maximally Stable Extremal Regions ) . Corners in images can be located using local detectors; input to the corner detector is the gray-level image, and output is the image in which values are proportional to the likelihood that the pixel is a corner. Interest points are obtained by thresholding the result of the corner detector.
5.3
157
local pre-processing
Corners serve better than lines when the correspoudence problem is to be solved. This is due to the
aperture problem.
Assume a moving line is seen through a small
aperture. In such a case, only the motion vector perpendicular to the line can be observed. The component collinear with the line remains invisible. The situation is better with corners. They provide ground for unique matching, sec Figure
5.34 for illustration.
Figure 5.34: Arnbigui�y of lines for matching and unambiguity of cor ners. as
Edge detectors themselves are not stable at corners. This is naturaJ at the tip of the corner is ambiguous. This is illustrated in Figure
5.35
the gradient
in which a triangle
with sharp corner is shown. However, near the corner there is a discontinuity in the gradient direction. This observation is used in corner detect.ors.
? •
The
corner
Figure 5.35: Ambiguity of edge de tector
at the corner tip.
in the image can abo be defined 8.-; a pixel in its small neighborhood
where are two dominant and different edge directions. This definition is 1I0t precise as an isolated point of local intensity maximum or minimum, line endings, or an abrupt change in the curvature of a curve givCl:i a response similar to a corner. Nevertheless, sllch detectors are named comer detectors in the literature and are widely used. If corners have to be detected then some additionaJ constraints have to be applied. Corner detectors are not usually very robust.
This deficiency is overcome either
by manual expert supervision or large redundancies iut.roduced to prevent the effect of individual errors from dominating the task. The latter mealls that many more corners are detected in two or more images than arc needed for estimating a transformation sought between these images. The simplest corner detector is the
Moravec detector
[Moravec,
1977}
which is
maxima! in pixels with high contrast. These points arc on corners and sharp edges. The Moravec operator MO is given by
MO(i,j) �
L L
j+ l
H1
1 8 k:.oi- l
1;::; - 1
)f(k,l) - f(i ,j» )
(5,71 )
,
Better results are produced by computationally more expensive corner operators such as those proposed by Zuniga-Haralick [Zuniga and Haralick, or Kitchen-·Rosenfeld [Huang, The image function
1983} which
1983; Haralick and Shapiro, 1992} 5.3.(3).
are based on the facet model (Section
J is approximated in the neighborhood of the pixel
polynomiaJ with coefficients Ck:
(i,j) by a cubic
158
Chapter 5: I mage pre-processing
The Zuniga-Haralick operator ZH is given by (5.73) The Kitchen-Rosenfeld KR operator has the same numerator as equation (5.73), but the denominator is ( c� + c§ ) . The ZH operator has been shown to outperform the KR corner detector in test images [Haralick and Shapiro, 1992]. The Harris corner detector [Harris and Stephen, 1988] improved upon Moravec ' s by considering the differential of the corner score (sum of square differences) . Consider a 2D gray-scale image f. An image patch W E f is taken and is shifted by .6.x, .6.y . The sum of square differences S between values of the image f given by the patch W and its shifted variant by .6.x, .6.y is given by:
SW (.6.x , .6.y) =
L L xi E W Yi E W
(J ( :Ci , Yi ) - f (Xi - .6.X, Yi - .6.y)) 2
•
(5.74)
A corner point not suffering from the aperture problem must have a high response of SW (.6.x, .6.y) for all .6.x , .6.y . If the shifted image patch is approximated by the first-order Taylor expansion (5.75) then the minimum of Sw ( .6.x, .6. y) can be obtained analytically. Substitute this approxi mation given by equation (5.75) into equation (5.74)
([�;l [g� ��]) [��] ( L L [�l [� U]) [��l [��] ,
L L [.6.x, .6.y]
Xj E W y, E W
= [ .6.x , .6. y]
x i E W Yi E W
=
[ .6.x, .6. y] A w (x, y)
ay
ay
5.3 Local pre-processing
159
where the Harris matrix Aw(x,y) is the tiecond derivative of S around the point (x,y) = (0,0). A is
(5.76) Usually an isotropic window is used, such as a Gaussian. The response will bc isotropic too. The local structure matrix A represents the neighborhood--the Harris matrix A is symmetric and pOl:>itive scmi�definite. Its main modes of variation correspond to partial derivatives in orthogonal directions and are reflected in eigenvalues >." >'2 of matrix A. These modes of variationti can be found using principal component analysis (peA), see Section 3.2.10. Three distinct cases can appear: 1. 2.
Both eigenvalues are smalL This means that image f is flat in the examiued pixel. There are no edges or corners in this location.
One eigenvalue is small and the second one large . The local neighborhood is ridgL' shaped. Significant change of image f occurs if a small movement is made perpendic ularly to the ridge.
3. Both eigenvalues are rather large. A small shift in any direction causes significant change of image f. A cornel' is found. Cases 2 and 3 are illustrated in Figure 5.36.
(a)
(b)
(e)
Figure 5.36: Illustration of the decision within Harris corner detector according to eigenvalues of the local structure matrix. (a), (b) Ridge detected, no comer at this position. (c) Corner detected.
Harris suggested that exact eigenvalue computation can be avoided by calculating the response function R.(A) 0::: dct(A) - K trace2 (A), where det(A) is the determinant of the iocal structure matrix A, trace(A) is the trace of matrix A (sum of elements on the main diagonal), and K is a tunable parameter where values from 0.04 to 0.15 were reported in literature as appropriate. An example of Harris corners applied to a real scelle is in Figure 5.37. Corners are marked by red crosses. Algorithm 5.5: Harris corner detector
1. Filter the image with a Gaussian. 2.
�.
af�:'1I),
Estimate intensity gradient in two perpendicular directions for each pixel, This is performed by twice using a ID convolution with the kernel approximating the derivative.
3. For each pixel and a given neighborhood window:
Chapter 5: Image pre-processing
160
Uflitlersity in Prague, who u.ied such images fm· :/D reconstntction. A colQr version of thi..� fi.qV.re may
Figure 5.37: Example of Harris corners in the imllge. Courte:.-y of Ma.rtin Urban, Czech Technical be seen in the colo,· inset--Plate 7. •
•
Calculate the local structure matrix A. Evaluate the re>ponsc function R(A).
4. Choose the best candidates for corners by selecting a threshold on the response function R(A) and perform non-maximal suppression.
The Harris comer detector has been very popular. It:s advantages are insensitivity to 20 shift and rotation, to :small illumination variat.ions, to small viewpoint change, and its low computational requiremellts. On the other hand, it is not invariant to larger scale change, viewpoint changes and significant changes in contrast. Many more comer-like detectors exi:st, and the reader is refern..u to the overview papers [Mikolaj<.-zyk and Schmid, 20041, [Mikolajczyk et al., 2005] . 5.3.11
Detection of maximally stable extremal regions
The Harris iuterest point detector is an example of an algorithm producing output that is invariant with rotation and translation in this casco When effects of noise and discreti'lation are n.egligible, the output of a Harris detector on a rotated and/or translated image is a rotated and/or tran:slated set of points. However, if the image is rescaJed or transformed projectively, t.he output of Harris detector changes rapidly. Maximally Stable Extremal Regions (MSERs) lMatas et aI., 2002] are an exam ple of all image structure that can he repeatahly detected not only after translations and rotations, but also after similarity and affine transforms of an image. The MSER detection process can be explained informally as follows. Imagine all possible thresholdings of an input gray-level image I, say with a common range S ]0,1, . . . , 255]. We will refer to the pixels below it threshold as 'black' and to those above =
5.3 Local pre-processing
161
Figure 5.38: Example of MSERs detected in the image. Regions with the red border are results of the algorithm on the increasingly ordered list of intensities. Regions with the green borders come from the list with decreasing ordering. CQurtcsy of .liri Matlls, Czech Technical University in Prague, whQ 11Sed sw;h images for 3D recoTloSt"'ction. A color version of thi.� fi.Qurc may be seen in the wlor inset-Plate 8.
or equal as 'white'. If we were shown a movie of thresholded images It, with frame corresponding to threshold t, we would see first a white image.
t
Subsequently black spots
corresponding to local intcIll:;ity minima will appear and grow. At some point regions corresponding to two local minima will merge. Finally, the last image will be black. The union of all connected components of all frames of the movie is identical to the set of all maximal regioIls; minimal regions could be obtained by inverting the intensity of
J and
over a large range of thresholds in certain regions. Such regions arc of interest since they
running the same process. On many images one observes that local binarization s i stable
have the following properties: •
lnvariance to monotonic transformation.
=
M : S --> S of image intensities. M, I(P) < J(q)
M(!(p))
=
I'(p) < F(q)
M (J(q))
since
-->
!vi dOel:; not affect adjacency (and thus
The set of extrcmal regions is unchanged after transformation contiguity). The intensity ordering is preserved.
•
•
Invariance to adjacency preserving (continuous) transformation. T : V --> V on the image domain.
Stability, since only extremal regions whose support is virtually ullchang(:.'(1 over a range of thresholds are selected.
•
•
Multi-scale detection. Since I10 smoothing is involved, both very fine and very large
structure is detected.
The set of all extremal regions can be enumerated in linear time for
In outline,
the
8 bit images.
MSER detection algorithm is:
O(ll log logn),
i.e., almost in
162
Chapter 5 : Image pre-processing
Algorithm 5.6: Enumeration of Extremal Regions. Input: Image I. Output: List of nested extremal regions. 1 . For all pixels sorted by intensity: • Place pixel in the image. • Update the connected component structure. • Update the area for the effected connected component. 2. For all connected components: • Local minima of the rate of change of the connected component area define stable thresholds. The computational complexity of step 1 is O(n) if the image range S is small, e.g. the typical [0, 1, . . . , 255] and sorting can be implemented as 'binsort' [Sedgewick, 1998] . ' As pixels ordered by intensity are placed in the image (either in decreasing or increasing order) , the list of connected components and their areas is maintained using the efficient union-find algorithm [Sedgewick, 1998] . The complexity of the algorithm is O(n log log n) . The process produces a data structure holding the area of each connected component as a function of a threshold. A merge of two components is viewed as the end of existence of the smaller component and the insertion of all pixels of the smaller component into the larger one. Finally, intensity levels that are local minima of the rate of change of the area function are selected as thresholds. In the output, each MSER is represented by a local intensity minimum (or maximum) and a threshold. The structure of Algorithm 5.6 and an efficient watershed algorithm [Vincent and Soille, 1991] (Sections 6.3.4 and 13.7.3) is essentially identical. However, the structure of output of the two algorithms is different. In watershed computation, the focus is on thresholds where regions merge and watershed basins touch. Such thresholds are highly unstable - after a merge, the region area changes abruptly. In MSER detection, a range of thresholds is sought that leaves the watershed basin effectively unchanged. Detection of MSER is also related to thresholding. Every extremal region is a connected component of a thresholded image. However, no global or 'optimal' threshold is needed, all thresholds are tested and the stability of the connected components evaluated. Finally, the watershed is a partitioning of the input image, where MSER can be nested, if in some parts of the image multiple stable thresholds exist. In empirical studies [Mikolajczyk et a1. , 2005; Frauendorfer and Bischof, 2005] , the MSER has shown the highest repeatability of affine-invariant detectors in a number of experiments. MSER has been used successfully for challenging wide baseline matching problems [Matas et al., 2004] and in state-of-the-art object recognition systems [Obdrzalek and Matas, 2002; Sivic and Zisserman, 2004] .
5.4
I mage restoration
Pre-processing methods that aim to suppress degradation using knowledge about its nature arc called image restoration. Most image restoration methods are based on convolution applied globally to the whole image.
5.4 I mage restoration
163
Degradation of images can have many causes: defects of optical lenses, non-linearity the electro-optical sensor, graininess of the film material, relative motion between an of object and camera, wrong focus, atmospheric turbulence in remote sensing or astronomy, scanning of photographs, etc. [Jain, 1989; Pratt, 1991; Gonzalez and Woods, 1992; Tekalp and Pavlovic, 1993; Sid-Ahmed, 1995] . The objective of image restoration is to reconstruct the original image from its degraded version. Image restoration techniques can be classified into two groups: deterministic and stochastic. Deterministic methods are applicable to images with little noise and a known degradation function. The original image is obtained from the degraded one by a transfor mation inverse to the degradation. Stochastic techniques try to find the best restoration according to a particular stochastic criterion, e.g. , a least-squares method. In some cases the degradation transformation must be estimated first. It is advantageous to know the degradation function explicitly. The better this knowledge is, the better are the results of the restoration. There are three typical degradations with a simple function: relative constant speed movement of the object with respect to the camera, wrong lens focus, and atmospheric turbulence. In most practical cases, there is insufficient knowledge about the degradation, and it must be estimated and modeled. The estimation can be classified into two groups according to the information available: a priori and a posteriori. If degradation type and/or parameters need to be estimated, this step is the most crucial one, being responsible for image restoration success or failure. It is also the most difficult part of image restoration. A priori knowledge about degradation is either known in advance or can be obtained before restoration. For example, if it is known in advance that the image was degraded by relative motion of an object with respect to the sensor, then the modeling determines only the speed and direction of the motion. An example of the second case is an attempt to estimate parameters of a capturing device such as a TV camera or digitizer, whose degradation remains unchanged over a period of time and can be modeled by studying a known sample image and its degraded version. A posteriori knowledge is that obtained by analyzing the degraded image. A typical example is to find some interest points in the image (e.g., corners, straight lines) and guess how they looked before degradation. Another possibility is to use spectral characteristics of the regions in the image that are relatively homogeneous. Image restoration is considered in more detail in [Pratt, 1 978; Rosenfeld and Kak, 1982; Bates and McDonnell, 1986; Pratt, 1991; Gonzalez and Woods, 1992; Castleman, 1996] and only the basic principles of the restoration and three typical degradations are considered here. A degraded image 9 can arise from the original image f by a process which can be expressed as
g ( i, j)
= s
(1 I
. (a,bl EO
)
f (a, b) h(a, b, i , j) da db + v(i , j) ,
(5.77)
where s is some non-linear function and v describes the noise. The degradation is very often simplified by neglecting the non-linearity and by assuming that the function h is invariant with respect to position in the image. Degradation can be then expressed as convolution: (5.78) g (i, j) = ( f * h ) ( i j ) + v(i , j) .
,
164
Chapter 5: Image pre-processing
If the degradation is given by equation (5.78) and the noise is not significant, then image restoration equates to inverse convolution (also called deconvolution). If noise is not negligible, then the inverse convolution is solved as an overdetermined system of linear equations. Methods based on minimization of the least square error such as Wiener filtering (off-line) or Kalman filtering (recursive, on-line; see Section 16.6.1) are examples [Bates and McDonnell, 1986J .
5.4.1
Degradations that are easy to restore
We mentioned that there are three types of degradations that can be easily expressed mathematically and also restored simply in images. These degradations can be expressed by convolution, equation (5.78); the Fourier transform H of the convolution function is used. In the absence of noise, the relationship between the Fourier representations F, G, H of the undegraded image j, the degraded image g, and the degradation convolution kernel h, respectively, is (5.79) G = HF. Therefore, not considering image noise v , knowledge of the degradation function fully facilitates image restoration by inverse convolution (Section 5.4.2). We first discuss several degradation functions.
Relative motion of the camera and object Assume an image is acquired with a camera with a mechanical shutter. Relative motion of the camera and the photographed object during the shutter open time T causes smoothing of the object in the image. Suppose V is the constant speed in the direction of the x axis; the Fourier transform H (u, 'u ) of the degradation caused in time T iH given by [Rosenfeld and Kak, 1982] sin(7T V T u ) . H( 1l, V ) (5.80) 7T V U _
Wrong lens focus Image smoothing caused by imperfect focus of a thin lens can be described by the following function [Born and Wolf, 1969] : J1 (a r) (5.81) aT , where J1 is the Bessel function of the first order, = + v 2 , and a is the displacement-- the model is not space invariant. H(u, v) =
",2 u2
Atmospheric turbulence Atmospheric turbulence is degradation that needs to be restored in remote sensing and astronomy. It is caused by temperature non-homogeneity in the atmosphere that deviates passing light rays. The mathematical model is derived in [Hufnagel and Stanley, 1964] and is expressed as _ c(,,2 +,?)5/U (5.82) H ( U, 'U ) = e , where c is a conHtant that depends on the type of turbulence which iH usually found experimentally. The power 5/6 is sometimes replaced by 1 .
5.4 I m age restoration
5.4. 2
165
I nverse filtration
An obvious approach to image restoration is inverse filtration based on properties of the Fourier transforms [Sondhi, 1972; Andrews and Hunt, 1977; Rosenfeld and Kak, 1982J. Inverse filtering uses the assumption that degradation was caused by a linear function h( i, j) (cf. equation (5.78)) and considers the additive noise // as another source of degradation. It is further assumed that v is independent of the signal. After applying the Fourier transform to equation (5.78), we get
G(u , v)
=
F(u, v ) H(u , v) + N(u , v) .
(5.83)
The degradation can be eliminated using the restoration filter with a transfer function that is inverse to the degradation h. The Fourier transform of the inverse filter is then expressed as H- 1 (u, v). We derive the original undegraded image F (its Fourier transform to b e exact) from its degraded version G [equation (5.83)], as follows
F(u , v ) = G( U, V ) H - l ( U, V ) - N(u, v) H - 1 (u, v ) .
(5.84)
This equation shows that inverse filtration works well for images that are not corrupted by noise [not considering possible computational problems if H Cu , v ) gets close to zero at some location of the u, v space- -fortunately, such locations can be neglected without perceivable effect on the restoration resultJ . However, if noise is present, several problems arise. First, the noise influence may become significant for frequencies where H(u , v ) has small magnitude. This situation usually corresponds to high frequencies u , v. In reality, H( u, v) usually decreases in magnitude much more rapidly than N( u, v ) and thus the noise effect may dominate the entire restoration result. Limiting the restoration to a small neighborhood of the u, v origin in which H( u, v ) is sufficiently large overcomes this problem, and the results are usually quite acceptable. The second problem deals with the spectrum of the noise itself- -we usually do not have enough information about the noise to determine N (u, v ) sufficiently well.
5.4.3
Wiener filtration
Based on the preceding discussion, it is no surprise that inverse filtration gives poor results in pixels suffering from noise, since the information about noise properties is not taken into account. Wiener (least mean square) filtration [Wiener, 1942; Helstrom, 1967; Slepian, 1967; Pratt, 1972; Rosenfeld and Kak, 1982; Gonzalez and Woods, 1992; Castleman, 1996J incorporates a priori knowledge about the noise properties in the image restoration formula. Restoration by the Wiener filter gives an estimate j of the original uncorrupted image f with minimal mean square error
(5.85) where E denotes the mean operator. If no constraints are applied to the solution of equation (5.85) , then an optimal estimate j is the conditional mean value of the ideal image f under the condition g. This approach is complicated from the computational point of view. Moreover, the conditional probability density between the optimal image f
166
Chapter 5: I mage pre-processing
and the corrupted image 9 is not usually known. The optimal estimate is in general a non-linear function of the image g . Minimi:wtion of equation (5.85) is easy if the estimate j is a linear combination of the values in the image g ; the estimate j is then close (but not necessarily equal) to the theoretical optimum. The estimate is equal to the theoretical optimum only if the stochastic processes describing images .t, g , and the noise v are homogeneous, and their probability density is Gaussian [Andrews and Hunt, 1977] . These conditions are not usually fulfilled for typical images. Denote the Fourier transform of the Wiener filter by Hw . Then, the estimate F of the Fourier transform F of the original image .t can be obtained as
FCu, v) = Hw (u, v) G(u, v) .
(5.86)
The function Hw is not derived here, but Illay be found elsewhere [Papoulis, 1965; Rosenfeld and Kak, 1982; Bates and McDonnell, 1986; Gonzalez and Woods, 1992] . The result is
H (u, ) w
u
,
_ -
H* (u, v) I H(u, v) 1 + [Svv(U, V)/ Sff ( U, v) ] 2
'
(5.87)
where H is the transform function of the degradation, * denotes complex conjugate, Svv is the spectral density of the noise, and Sf! is the spectral density of the undegraded image. If Wiener filtration is used, the nature of degradation H and statistical parameters of the noise need to be known. Wiener filtration theory solves the problem of optimal a posteriori linear mean square estimates- all statistics (for example, power spectrum) should be available in advance. Note the term SJ f (u, v) in equation (5.87) , which represents the spectrum of the undegraded image. This information may be difficult to obtain considering the goal of image restoration, to determine the undegraded image. Note that the ideal inverse filter is a special case of the Wiener filter in which noise is absent, i.e., Svv = O. Restoration is illustrated in Figures 5.39 and 5.40. Figure 5.39a shows an image that was degraded by 5 pixels motion in the direction of the .7: axis, and Figure 5.39b shows the result of restoration where Wiener filtration was used. Figure 5.40a shows an image degraded by wrong focus and Figure 5.40b is the result of restoration using \i\1iener filtration. Despite its unquestionable power, vViener filtration suffers several substantial limitations. First, the criterion of optimality is based on minimum mean square error and weights all errors equally, a mathematically fully acceptable criterion that unfortunately does not perform well if an image is restored for human viewing. The reason is that humans perceive the restoration errors Illore seriously in constant-gray-level areas and in bright regions, while they are much less sensitive to errors located in dark regions and in high-gradient areas. Second, spatially variant degradations cannot be restored using the standard vViener filtration approach, and these degradations are common. Third, most images are highly nOll-stationary, containing large homogeneous areas separated by high-contrast edges. Wiener filtration cannot handle non-stationary signals and noise. To deal with real-life image degradations, more sophisticated approaches may be needed. Examples include power spectrum equalization and geometric mean filtration. These and other specialized restoration techniques can be found in higher-level texts devoted to this topic; [Castleman, 1996] is well suited for such a purpose.
5.5 Summary
• • •
•
;
• • III . . .��
(a)
Figure
167
•• •• ••
(b)
5.39: Restoration of motion blur using Wiener filtration. C01Htesy of P. Kohout, Criminal·
istic Institute, Prague.
WI . no
••• • •
(a)
Figure
5.40:
.
••
. • •
-
• •
(b)
Restoration of wrong focus hlur using Wiener filtration.
Courtesy of P. Kohout,
Criminalistic Instittlte, Prngue.
5.5 •
Summary
Image pre-processing - Operations with images at the lowest level of abstraction-both input and output arc intensity images-arc called pre-processing.
- The aim of pre-processing is an improvement of the image data that su ppr esses unwilling distortions or enhances some image features important for further
processing.
Four basic types of pre-processing methods exist: *
II<
Geometric transformations
*
Image restoration
*
•
Brightness transformations Local neighborhood pre-processing
Pixel brightness transformations
168
Chapter 5: I m age pre-processing
There are two classes of pixel brightness transformations:
* Brightness corrections * Gray-scale transformations
•
Brightness corrections modify pixel brightness taking into account its original brightness and its position in the image. Gray-scale transformations change brightness without regard to position in the image. Frequently used brightness transformations include: * Brightness thresholding * Histogram equalization * Logarithmic gray-scale transforms * Look-up table transforms * Pseudo-color transforms The goal of histogram equalization is to create an image with equally distributed brightness levels over the whole brightness scale. Geometric transformations Geometric transforms permit the elimination of the geometric distortions that occur when an image i::; captured. A geometric transform typically consists of two basic steps: * *
•
Pixel co-ordinate transformation Brightness interpolation
Pixel co-ordinate transformations map the co-ordinates of the input image pixel to a point in the output image; affine and bilinear· transforms are frequently used. The output point co-ordinates do not usually match the digital grid after the transform and interpolation is employed to determine brightnesses of output pixels; neaTest-neighboT, lin eaT, and bi-cubic interpolations are frequently used. Local pre-processing Local pre-processing method::; use a small neighborhood of a pixel in an input image to produce a new brightness value in the output image. For the pre-processing goal, two groups are common: smoothing and edge detection. Smoothing aims to suppres::; noise or other small fiuctuations in the image; it is equivalent to suppressing high frequencies in the Fourier transform domain. Smoothing approaches ba.'ied on direct averaging blur image edges. More sophis ticated approache::; reduce blurring by averaging in homogeneous local neighbor hoods. Median smoothing is a non-linear operation; it reduces the blurring of edges by replacing the current point in the image by the median of the brightnesses in its neighborhood. Gradient operators determine edges--·locations in which the image function un dergoes rapid changes; they have a similar effect to suppressing low frequencies in the Fourier transform domain. Edge is a property attached to an individual pixel and has two components, magnitude and diTection.
5.6 References
169
Most gradient operators can be expressed using convolution masks; examples include Roberts, Laplace, Prewitt, Sobel, Robinson, and Kirsch operators. The main disadvantage of convolution edge detectors is their scale dependence and noise sensitivity. There is seldom a sound reason for choosing a particular size of a local neighborhood operator. Zero-crossings of the second derivative are more robust than small-size gradient detectors and can be calculated as a Laplacian of Gaussians ( LoG ) or as a difference of Gaussians ( DoG ) . The Canny edge detector is optimal for step edges corrupted by white noise. The optimality criterion is based on requirements of detecting important edges, small localization error, and single-edge response. Canny edge detection starts with convolving an image with a symmetric 2D Gaussian and then differentiating in the direction of the gradient; further steps include non-maximal edge suppression, hysteresis thresholding, and feature synthesis. Edges can also be detected in multi-spectral images. Other local pre-processing operations include line finding, line thinning, line filling, and inter-c8t point detection. There are structures in an image as corners and maximally stable extremal regions which are more information rich and more stable to detect than edges. These structures are often used in image matching. •
Image restoration Image restoration methods aim to suppress degradation using knowledge about its nature. Most image restoration methods are based on deconvolution applied globally to the entire image. Relative-constant-speed movement of the object with respect to the camera, wrong lens focus, and atmospheric turbulence are three typical image degradations with simple degradation functions. Inverse filtration assumes that degradation was caused by a linear function. Wiencr filtration gives an estimate of the original uncorrupted image with minimal mean square error; the optimal estimate is in general a non-linear function of the corrupted image.
5.6
References
Alparone L., Baronti S . , and Casini A. A novel approach to the suppression of false contours. In International Conference on Image Processing, pages 825-828, Los Alamitos, CA, 1996. IEEE. Andrews H. C. and Hunt B. R. Digital Image Restomtion. Prentice-Hall, Englewood Cliffs, NJ, 1977.
Aydin T., Yemez Y . , Anarim E., and Sankur B. Multidirectional and IIlultiscale edge detection
via M-band wavelet transform. IEEE Transactions on Image Processing, 5:1370-1377, 1996.
Ballard D. H. and Brown C. M. Computer Vision. Prentice-Hall, Englewood Cliffs, NJ, 1982. Bates R. H. T. and McDonnell M. J. Image Restomtion and Reconstruction. Clarendon Press, Oxford, 1986.
170
Chapter 5: I mage pre-processing
Bezdek J. C., Chandrasekhar R., and Attikiollzel Y. A new fuzzy model for edge detection. In Applications of Fuzzy Logic Technology 111, Proc. SPIE Vol. 276'1, pages 1 1-28, Bellingham, WA, 1996. SPIE. Borik A. C., Huang T. S., and Munson D. C. A generalization of median filtering using combination of order statistics. IEEE Pr-oceedings, 71(31):1 342-1350, 1 983. Born M . and Wolf E. Principles of Optics. Pergamon Press, New York, 1 969. Brady M. Representing shape. In Brady M . , Gerhardt L. A., and Davidson H. F., editors, Robotics and Artifidai intel ligence, pages 279-300. Springer + NATO, Berlin, 1 984.
Butterworth S. On the theory of filter amplifiers. Experimental Wireless and the Radio Engineer, 7:536-541 , 1 930.
Canny J. F. Finding edges and lines in images. Technical Report AI-TR-720, MIT, Artificial Intelligence Laboratory, Cambridge, MA, 1983. Canny J. F. A computational approach to edge detection. IEEE Transactions on Pattem Analysis and Machine Intel ligence, 8(6):679-698, 1986. Castleman K. R. Digital Image Processing. Prentice-Hall, Englewood Cliffs, NJ, 1 996. Cervenka V. and Charvat K. Survey of the image processing research applicable to the thematic mapping based on aerocosmic data ( in Czech ) . Technical Report A 12-346-8 1 1 , Geodetic and Carthographic Institute, Prague, Czechoslovakia, 1987. Demigny D . , Lorca F. G . , and Kessal L . Evaluation of edge detectors performances with a discrete expression of Canny's criteria. In Intemational Conference on Image Process'ing, pages 1 69-172, Los Alamitos, CA, 1 995, IEEE. Elder J, H. and Zucker S, W. Local scale control for edge detection and blur estimation. In Buxton B. and Cipolla R. , editors, 4th European Conference on Computer Vision, Cambridge, England, pages 57- 69, Berlin, 1996. Springer Verlag, Faugeras O. D, Three-Dimensional Cornp'u ter Vision: A Geometr"ic Viewpoint, MIT Press, Cambridge, MA, 1 993. Frallendorfer F, and Bischof H. A novel performance evaluation method of local detectors on non-planar scenes, In Pmceedings of the Workshop Empirical Evaluation Methods ?:n Computer Vision adjoint to the confer'ence Computer Vision and Pattern Recognition, San Diego, USA, 2005, IEEE Computer Society, Gonzalez R. C, and Woods R. E. Digital Image Processing. Addison-Wesley, Reading, IVIA, 1992, Goodman J. W, Introduct'ion To Four"ie'(' Optics, McGraw-Hill Science, 2 edition, 1996, Gllnn S. R. On the discrete representation of the Laplacian of Gaussian. Pattern Recognition, 32 (8) : 1463 1472, 1999. Haralick R. M. Digital step edges from zero crossing of second directional derivatives, IEEE Transactions on Pattern Analysis and Machine Intelligence, 6:58-68, 1984, Haralick R. M. and Shapiro L. G. Computer and Robot V?:sion, Volume Reading, MA, 1992.
1.
Addison-Wesley,
HaraJick R. M. and Watson L. A facet model for image data. Comp'u ter Graphics and Image Processing, 15: 1 13-1 29, 1 981 . Hardie R. C. and Boncelet C, G. Gradient-based edge detection using nonlinear edge enhancing prefilters, IEEE Transactions on Image Processing, 4:1572-1577, 1995,
Harris C . and Stephen M. A combined corner and edge detection. In Matthews M. M " editor, Proceedings of the 4 th ALVE Y vision conference, pages 147-151, University of Manchaster, England, 1988.
5.6 References
171
Hebert D. J. and Kim H. A fast-wavelet compa..<;s edge detector. In Wavelet Applications in Signal and Image Proce8sing IV, Proc. SPIE Vol. 2825, pages 432-442, Bellingham, WA, 1996. SPIE. Helstrom C. W. Image restoration by the method of least squares. Journal of the Optical Society of America, 57: 297-303, 1967. Ho K. H. L. and Ohnishi N. FEDGE--fuzzy edge detection by fuzzy categorization and classification of edges. In Fuzzy Logic in Artificial Intelligence. Towards Intelligent SY8tems. I.lCA I '95 Worbhop. Selected Papers, pages 182 -196, 1995. Huang T. S., editor. Image Sequence Proce8sing and Dynamic Scene Analysis. Springer Verlag, Berlin, 1983.
Huang T. S., Yang G. J . , and Tang G. Y. A fast two-dimensional median filtering algorithm. IEEE Tran8actions on Aco'u8tics, Speech and Signal Process-ing, ASSP-27 ( 1 ) : 13-18, 1979. Huertas A, and Medioni G. Detection of intensity changes with subpixel accuracy using Laplacian Gaussian masks, IEEE Tmnsactions on Pattern AnalY8i8 and Machine Intelligence, 8 : 651 -664, 1986. Hufnagel R. E. and Stanley N. R Modulation transfer function associated with image transmission through turbulent media, Journal of the Optical Society of America, 54:52 ..6 1 , 1964.
Hummel R and Moniot R Reconstructions from zero crossings in scale space, IEEE Transactions on Acou8tics, Speech and Signal Pmcessing, 37(12) : 2 1 1 1-·2130, 1989, Jain A. K. Fundamentals of Digital Image Processing. Prentice-Hall, Englewood Cliffs, NJ, 1989,
Jain
R,
Kasturi
R,
and Schunck B. G, Machine Vision, McGraw-Hill, New York, 1995.
Jalali S, and Boyce .J. F. Determination of optimal general edge detectors by global minimization of a cost function. Image and Vision Computing, 13:683-693, 1995.
Laligant 0 " Truchete F" and Miteran J, Edge detection by multiscale merging. In Proceeding8 of the IEEE-SP International Symp08ium on Time-Frequency and Time-Scale AnalY8is, pages 237-240, Los Alamitos, CA, 1994, IEEE. Law T., Itoh H" and Seki H. Image filtering, edge detection, and edge tracing using fuzzy reasoning. IEEE Transactions on Pattern AnalY8is and Machine Intelligence, 1 8:48 1-49 1 , 1996. Lindeberg T, Edge detection and ridge detection with automatic scale selection. In Computer Vision and Pattern Recognition, pages 465-470, Los Alamitos, CA, 1996. IEEE. Lowe D. G. Organization of smooth image curves at multiple scales. International Journal of Computer Vision, 1 : 1 19·· 1 30, 1989. Marr D. Vision- A Computational Investigation into the H-uman RepT'esentation and Processing of Visual Information. Freeman, San Francisco, 1 982, Marr D. and Hildreth E. Theory of edge detection. Proceedings of the Royal Society, B 207: 1 87-2 17, 1980. Marr D. and Hildreth E. Theory of edge detection. In Kasturi R. and Jain R. C., editors, Computer Vision, pages 77- 1 07. IEEE, Los Alamitos, CA, 199 1 . Matalas L . , Benjamin R , and Kitney R A n edge detection technique using the facet model and parameterized relaxation labeling, IEEE Transactions on Pattern Analysis and Machine Intelligence, 19:328 -341 , 1 997.
Matas J . , Chum 0" Urban M" and Pajdla T. Robust wide baseline stereo from maximally stable extremal regions, In Rosin P. L. and Marshall D" editors, Proceedings of the British Machine V'ision Conference, volume 1 , pages 384-393, London, UK, 2002. BMVA.
172
Chapter 5: I m age pre-processing
Matas .1 . , Chum 0., Urban M., and Pajdla T. Robust wide-baseline stereo from maximally stable extremal regions. Image and Vision Computing, 22(10) :76 1-767, 2004. Mehrotra R. and Shiming Z. A computational approach to bero-crossing-based two-dimensional edge detection. Graphical Models and Image Processing, 58: 1-17, 1 996. Mikolajcbyk K. and Schmid C. Scale and affine invariant interest point detectors. International Journal of Computer V?:sion, 60( 1 ) :63 - 86, 2004. Mikolajczyk K . , Tuytelaars T., Schmid C . , Zisserman A., Matas J . , Schaffalit:
Papoulis A. Probability, Random Variables, and Stochast-ic Processes. McGraw-Hill, New York, 1965. Perona P. and Malik J. Scale-space and edge detection using anisotropic diffusion. IEEE lransactions on Pattcrn Analysis and Machine Intelligence, 12(7) :629 639, 1990.
Petrou 1VI. Optimal convolution filters and an algorithm for the detection of wide linear features. lEE Proceedings, I: 140(5):331-339, 1993. Pitas I. and Venetsanopoulos A. N. Nonlinear Digital FilteTs: Principles and Applications. Kluwer, Boston, 1990. Pitas I. and Venetsanopulos A. N. Nonlinear order statistic filters for image filtering and edge detection. Signal Processing, 10(10):573-584, 1986. Pratt W. K. Generalized Wiener filter computation techniques. IEEE Tmnsactions on Computers, 21 :636-641 , 1 972. Pratt W. K. Digital Image Processing. Wiley, New York, 1978. Pratt \'1. K. Digital Image Processing. Wiley, New York, 2nd edition, 199 1 .
Qian R . J . and Huang T. S. Optimal edge detection i n two-dimensional images. I n A RPA Image Understanding WOTkshop, Monterey, CA, pages 158 1-1 588, Los Altos, CA, 1 994. ARPA.
5.6 References
173
Ramesh V. and Haralick R. 1"1. An integrated gradient edge detector. Theory and performance evaluation. In A RPA Image Understanding Workshop, Monterey, CA, pages 689-702, Los Altos, CA, 1994. ARPA. Roberts L. G. Machine perception of three-dimensional solids. In Tippett J. T., editor, Optical and Electro - Optical Inform.ation PTOcessing, pages 1 59·- 197. MIT Press, Cambridge, MA, 1965. Rosenfeld A. and Kak A. C. Digital Picture Processing. Academic Press, New York, 2nd edition, 1982. Rosenfeld A. and Thurston M. Edge and curve detection for visual scene analysis. IEEE Transactions on Computers, 20(5):562-569, 1971. Saund E. Symbolic construction of a 2D scale-space image. IEEE Transactions on Pattern Analysis and Machine Intelligence, 12:817· 830, 1990. Sedgewick R. Algorithms in C : Parts 1-4 : F7m,damentals ; Data Structures ; Sorting ; Searching, Addison-Wesley, Reading, Ma..'lsachusetts, 3rd edition, 1998. Sid-Ahmed M. A. Im.age Processing. McGraw-Hill, New York, 1995. Sivic J. and Zisserman A, Video data mining using configurations of viewpoint invariant regions. In Proceedings of the IEEE Conference on Computer- Vision and Pattern Recognition, Washington, DC, volume 1, pages 488-495, 2004. Slepian D. Linear least-squares filtering of distorted images. Journal of the Optical Society of America, 57:918-922, 1967. Sondhi M. M, Image restoration: The removal of spatially invariant degradations. Proceedings IEEE, 60:842-853, 1972. Sorrenti D. G. A proposal on local and adaptive determination of filter scale for edge detection. In Image Analysis and Processing. ICIAP '95, pages 405-410, Berlin, 1 995, Springer Verlag. Spacek L. Edge detection and motion detection. Image and Vis'ion Computing, 4:43- 52, 1986.
Sun M . and Sclabassi R. J . Symmetric wavelet edge detector of the minimum length. In International Conference on Image Processing, pages 1 77-180, Los Alamitos, CA, 1995. IEEE. Tagare H. D. and deFigueiredo R. J. P. On the localization performance measure and optimal edge detection. IEEE Transactions on Pattern Analysis and Machine Intelligence, 12(12): 1 186 1 190, 1990. Tang Y. Y., Li B . F., and Xi D, Multiresolution analysis in extraction of reference lines from documents with gray level background. IEEE Transactions on Pattern Analysis and Machine Intelligence, 19:92 1 -926, 1997. Tekalp A. M . and Pavlovic G. Digital restoration of images scanned from photographic paper. Journal of Electronic Imaging, 2(1 ) : 19 27, 1993. Topkar V., Kjell B . , and Sood A. Object detection using scale-space. In Proceedings of the Applications of Artificial Intelligence VIII Conference, The International Society for Optical Engineering, pages 2-13, Orlando, FL, 1990. SPIE. Tyan S. G. Median filtering, deterministic properties. In Huang T. S., editor, Two-Dimensional Digital Signal Processing, volume II. Springer Verlag, Berlin, 198 1 . Ullman S . Analysis o f visual motion by biological and computer systems. IEEE Computer, 1 4 (8):57-69, 1981. Venkateswar V. and Chellappa R. Extraction of straight lines in aerial images. IEEE Transactions on Patter'n Analysis and Machine Intelligence, 14:11 1 1 - 1 1 14, 1 992.
174
Chapter 5: I m age pre-processing
Vernon D. Machine v·ision. Prentice-Hall, Englewood Cliffs, New Jersey, USA, 1 991.
Vincent L. and Soille P . Wa.t ersheds in digital spaces: An efficient algorithm based on immersion simulations. IEEE Transactions on Pattern. Analysis and Machine Intelligence, 13(6): 583-598, 1 99 1 . Vrabel M . J. Edge detection with a recurrent neural network. In Applications and Science of Art'ificial Neural Networks II, Proc. SPIE Vol. 2760, pages 365-371, Bellingham, WA, 1996. SPIE.
Wang D . , Haese-Coat V., and Ronsin ,J . Shape decomposition and representation using a recursive morphological operation. Pattern Recogn'ition, 28: 1783-1792, 1995.
Wiener N . Extrapolation, Interpolation and Smoothing of Stationar-y Time Series. MIT Press, Cambridge, MA, 1942. Williams D. J. and Shah M . Edge contours using multiple scales. Computer Vision, Graphics, and Image Processing, 5 1 :256-274, 1990. Witkin A. P. Scale-space filtering. In Proceedings of the 8th Joint Conference on Artificial Intelligence, pages 1019-1022, Karlsruhe, Germany, 1 983. W Kaufmann.
Yaroslavskii L. P. Digital Signal Processing in Optics and Holography ( in Russian) . Radio i svja�, Moscow, 1987. Zuniga O. and Haralick R. M. Corner detection using the facet model. Pattern Recognition, pages 30-37, Los Alamitos, CA, 1983. IEEE.
In
Computer Vision and
Chapter
6
Segmentation I Image segmentation is one of the most important steps leading to the analysis of processed image data-its main goa] is to divide an image into parts that have a strong correlation with objects 01' areas of the real world contained in the image. We may aim for complete segmentation, which result.s in a set of disjoint regions corresponding uniquely with objects in the input. image, or for partial segmentation, in which regions do not correspond directly with image objects. To achieve a compict,c segmentation, cooperation with higher proces..<;iug levels which use specific knowledge of the problem domain is necessary. However, there is a whole class of segmentation problems that can be solved successfully using lower-lcvd processing only. In this case, the image commonly consists of contrasted objects located on a uniform background-simple Itssembly tasks, blood cells, printed characters, etc. Here simple global approach can be u!:iCd and the complete segmentation of an image into objects and background can be obtained. Such processing is context independent; 110 obj t rcluted model is used and no knowledge about expected segmentation results contributC8 to thc fina.l segmentation. If partial segmentation is the goal, an image is divided into separate regions that are homogeneous with respect to a chosen property such brightness, color, reffectivity, texture, etc. If an image of a complex scene is processed, for example, an aerial photograph of an urban scene, a set of possibly overlapping homogeneous regions may result. The partially segmented image must then be subjected to further processing, and the final image segmenta.tion may be found with the help of higher·level information. Totally correct and complete segmcntation of complex scenes usually canllot be achieved in this processing phase, although substantial reduction in data volume offers an immediate gain. A reasonable aim is to Ilse partial segmentation as all input to higher·levcl processing. Image data ambiguity is onc of the main segment ation problems often accompanied by information noise. Segmentation methods can be divided into three groups according to the dominant features they employ: Fin;!. is global knowledge about. an image or its part; the knowledge is usually represented by a histogram of image features. Edge-based segmentations form the second group, and region-based segmentations the third many different characteristics ma.y be used in edge detection or region growing, for example, , Ii
e c .
,
a. <;
,
-
176
Cha pter 6: Segmentation I
brightness, texture, velocity field, etc. The second and the third groups solve a dual problem. Each region can be represented by its closed boundary, and each closed boundary describes a region. Because of the different natures of the various edge- and region-based algorithms, they may be expected to give somewhat different results and consequently different information. The segmentation results of these two approaches can therefore be combined in a single description structure. A common example of this is a region adjacency graph, in which regions are represented by nodes and graph arcs represent adjacency relations based on detected region borders (Section 4.2.3) .
6.1
Thresholding
Gray-level thresholding is the simplest segmentation process. Many objects or image regions are characterized by constant reflectivity or light absorption of their surfaces; a brightness constant or threshold can be determined to segment objects and background. Thresholding is computationally inexpensive and fast-- it is the oldest segmentation method and is still widely used in simple applications; thresholding can easily be done in real time using specialized hardware. A complete segmentation of an image R is a finite set of regions RJ , , R s , • • •
s
R
=
U Ri ,
i= l
Ri n Rj = 0 ,
i -I- j .
(6.1)
Complete segmentation can result from thresholding in simple scenes. Thresholding is the transformation of an input image .f to an output (segmented) binary image 9 as follows:
g(i, j) = 1 for f(i, j) 2: T , = 0 for f(i, .1) < T ,
(6.2)
where T is the threshold, g(i, j) = 1 for image elements of objects, and g(i, .1) = 0 for image elements of the background (or vice versa) .
Algorithm 6.1: Basic thresholding 1. Search all the pixels f (i, j) of the image f. An image element g( i, .1 ) of the segmented image is an object pixel if f(i, .1 ) 2: T, and is a background pixel otherwise. If objects do not touch each other, and if their gray-levels are clearly distinct from background gray-levels, thresholding is a suitable segmentation method. Such an example is found in Figure 6. 1a, the threshold segmentation result for which is shown in Figure 6. 1b. Figures 6.1c and 6.1d show segmentation results for different threshold values. Correct threshold scIection is crucial for successful threshold segmentation; this selection can be determined interactively or it can be the result of some threshold detection method that will be discussed in the next section. Only under very unusual circumstances can thresholding be successful using a single threshold for the whole image (global thresholding) since even in very simple images there are likely to be gray-IevcI
6,1
Thresholding
177
(b)
(a)
(d)
«) Figure 6.1: Image thresholding, (a) too low. Cd) Threshold too high.
Original image.
(b) Threshold segmentation. (e) Threshold
variations in objects and background; this variation may be due to non-uniform lighting, non-uniform input device parameters or a number of other factors. Segmentation using
variable thresholds (also called adaptive thresholding), in which the threshold value varies over the image as a fuuction of local image characteristics, can produce the solution
A global threshold i;; determined from the whole image J:
in these cases.
(6.3)
T � TIf) · On the other hand, local thresholds arc position dependent
(6.4)
where
Ie is that image part ill which the thre:;hold is determined. One option is to divide Ie and determine a threshold independently in each subimage;
the image f into subimage..<;
then if a threshold cannot be determined in some :mbimage, it ca.n be interpolated from thresholds determined in neighboring subimagC!:i. Each subimage is thcn processed with respect to its local thrC!:ihold. Basic thresholding as dcfined by equation
(6.2) has many modifications.
One possibility
is to segment an image into regions of pixels with gray-levels from a set
D
and into
background otherwise (band thresholding):
..(i,j)
�
I fm f(i,j) E D ,
=
0
otherwise.
(6.5)
178
Chapter
6:
Segmentation '
o
(a)
(b)
Figure 6.2: Image thresholding modification. (a) Original image. (b) Border detection using band�thrcsholding. This thresholding can be useful, for instance, in microscopic blood cell segmentations, where a particular gray�level interval represents cytoplasma, the background is lighter, and the cell kernel darker. This thresholding definition can serve as a border detector as well; assuming dark objects on a light background, somc gray�levels between t.hose of objects and background can be found only in the object borders. If the gray�levcl set
D
equatioll (6.5) is used, object borders result as shown ill Figure 6.2. Isolines of gray can
is chosen to contain just these object�border gray�levels, and if thresholding according to be found using this appropriate gray�levcl set
D.
There are many modifications t.hat use mUltiple thresholds, after which the resulting image is no longer binary, but rather an image consisting of a very limited set of gray-levels:
9(;,j)
f(i, j) � 2 for f(i,j) � 3 for f(i,j) �
1
�n
�O
for
for
E
E E
f(i,j)
otherwise,
E
Dl ,
D2 , D3 , D....
Another special choice of gray�level subsets Di defines
where each
Di
(6.6)
:
is a specified subset of gray-levels.
semi�thresholding,
which is
sometimes used to make human�assisted analysis easier:
9(i , j) � f(i,j) =0
fo' for
f(i,j) � T , f(i , j) < T .
(6.7)
This process aims to mask out the image background, leaving gray�level information present in the object.s. that this is just one of many possibilities; thresholding can be applied if the values
Thresholding has been presented relying only on gray-level image properties. Note
f(i,j)
do not represent. gray�levels, but instead represent gradient, a local texture property
(Chapter 15), or the value of any other image decomposition criterion.
6.1 Thresholding 6.1.1
179
Threshold detection methods
If some property of an image after segmentatioll is known a priori, the task of threshold selection is simplified, since the threshold is chosen to ensure that this property is satisfied. A printed text sheet may be an example if we know that characters of the text cover lip of the sheet. area. Using this prior information about the ratio between the sheet area and character area, it is very easy to choose a threshold T (based on the image histogram) such that lip of the image area has gray values lao.; than T and the rest has gray values larger than T. This method is called p-tile thresholding. Unfortunately, we do not usually have such definite prior information about area ratios. This information can sometimes be substituted by knowledge of another property, for example, the average width of lines in drawings, etc. The threshold can be determiued to provide the required line width in t.he segmented image. 9000
•
MOO •
'''''' .
! t
•
""'" .
5000 .
<"'" .
""'" .
2000 .
'''''' . o • 0
"
"
"
."
'" "" Intensity
'"
'"
Figure 6.3: A bi-modal histogram.
More complex methods of threshold detection are based on histogram shape analysis. If an image consists of objects of approximately the same gray-level that differs from the gray-level of the background, the resulting histogram is bi-modal. Pixels of objects form one of its peaks, while pixels of the background form the second peak-Figure 6.3 shows a typical example. The histogram shape illustrates the fact that the gray valuCti between the two peaks arc not common in the image, and probably result from border pixels between objects aud background. The chosen threshold must meet minimum segmematioll error requirements; it makes intuitive sense to determine the threshold as the gray-level that has a minimum hist.ogram value between the two mentioned maxima; see Figure 6.3. If the histogram is multi-modal, more thresholds may be determined at minima between any two maxima. Each threshold gives different segmentation results, of course. Multi-thresholding as given in equation (6.6) is another option. To decide if a histogram is bi-modal or multi-modal may not bc so simple in reality, it often being impossible to interpret the significance of local histogram maxima. Bi-modal histogram threshold detection algorithms usually find the highest local maxima first and detect the threshold as a. minimum betwl:.'{:n them; t.his technique is called the mode method. To avoid detection of two local maxima belonging to the same global maximum, a minimum distance in gray-levels bctwl:.'Cll these maxima is usually required, or techniques to smooth histograms (see Section 2.3.2) arc applied. Note that histogram bi-modality itself does not guarantee correct threshold segmentation·-even if the histogram is bi modal, correct segmentation may not occur with objects located on a background of
180
Chapter 6: Segmentation I
different gray-levels. A two-part image with one half white and the second half black actually has the same histogram as an image with randomly spread white and black pixels (i.e., a salt-and-pepper noise image, see Section 2.3.6). This is one example showing the need to check threshold segmentation results whenever the threshold has been determined from a histogram only, using no other image characteristics. A more general approach takes gray-level occurrences inside a local neighborhood into consideration when constructing a gray-level histogram, the goal being to build a histogram with a better peak-to-valley ratio. One option is to weight histogram contributions to suppress the influence of pixels with a high image gradient. This means that a histogram will consist mostly of the gray values of objects and background, and that border gray-levels (with higher gradient) will not contribute. This will produce a deeper histogram valley and allow an easier determination of the threshold. Another method based on the same idea uses only high-gradient pixels to form the gray-level histogram, meaning that the histogram will consist mostly of border gray-levels and should be unimodal in which the peak corresponds to the gray-level of borders between objects and background. The segmentation threshold can be determined as the gray value of this peak, or as a mean of a substantial part of the peak. Many modifications of histogram transformation methods can be found in literature. Thresholding is a very popular tool in image segmentation, and a large variety of threshold detection techniques exist in addition to the maiu techniques which have been discussed. The survey [Sahoo et aI. , 1988] gives a good overview of existing meth ods: histogram concavity analysis, entropic methods, relaxation methods, multi thresholding methods, and others can be found there, together with an extensive list of references. High processing speed has always been typical for threshold segmentations, and images can easily be thresholded in real time.
6.1.2
Optimal thresholding
Methods bascd on approximation of the histogram of an image using a weighted sum of two or more probability densities with normal distribution represent a different approach called optimal thresholding. The threshold is set as the closest gray-level corresponding to the minimum probability between the maxima of two or more normal distributions, which results in minimum error segmentation (the smallest number of pixels is mis-segmented) [Rosenfeld and Kak, 1982; Gonzalez and Wintz, 1987] ; see Figure 6.4 (and also compare maximum-likelihood classification methods, Section 9.2.2 and expectation-maximization, Section 10.10). The difficulty with these methods is in estimating normal distribution parameters together with the uncertainty that the distribution may be considered normal. These difficulties may be overcome if an optimal threshold is sought that maximizes gray-level variance between objects and background. Note that this approach can be applied even if more than one threshold is needed [Otsu, 1979; Kittler and Illingworth, 1986; Cho et aI. , 1989] . Alternatively, minimization of variance of the histogram, sum of square errors, spatial entropy, average clustering, or other optimization approaches may be used. For an overview of alternative approaches, 1 1 common algorithms for global threshold detection and relationships between them can be found in [Glasbey, 1993] ; Section 10.10 is also relevant. The following algorithm represents a simpler version that shows a rationale for this approach [Ridler and Calvard, 1978] and works well even if the image histogram is not bi-modal. This method assumes that regions of two main gray-levels are present in the
6 . 1 Th resholding
(a)
181
Optimal threshold
Distribution of objects Distribution of background
I Optimal �I �onventional
(b)
Figure 6.4: Gray-level histograms approximated by two normal distributions- -the threshold is set to give minimum probability of segmentation error. (a) Probability distributions of background and objects. (b) Corresponding histograms and optimal threshold.
image, thresholding of printed text being an example. The algorithm is iterative, four to ten iterations usually being sufficient. Algorithm 6.2: Iterative (optimal) threshold selection 1. Assuming no knowledge about the exact location of objects, consider
a first approximation that the four corners of the image contain background pixels only and the remainder contains object pixels. 2. At step t, compute fJ'B and fJb the mean background and object gray-level, respectively, where segmentation into background and objects at step t is defined by the threshold value Tt determined in the previous step [equation 6.9] as
as
L(i ,j)Ebackgrou nd f (i, j) t fJ B = #background_pixels '
L(i,j) EObjects f (i, j) t fJo = #object_pixels .
(6.8)
3. Set
t + t T( t + l ) = fJ B fJo 2 l t T( + ) now provides an updated background-object distinction. 4. If T( t + l ) = T( t ) , halt; otherwise return to step 2.
(6.9)
The method performs well under a large variety of image contrast conditions. A combination of optimal and adaptive thresholding (equation (6.4)) was used for brain image segmentation from MR image data. The method determines optimal gray-level segmentation parameters in local sub-regions for which local histograms are constructed. The gray-level distributions corresponding to n individual (possibly non-contiguous)
Chapter 6: Segmentation I
182
regions are fitted to each local histogram hregion which is modeled as a sum hmodcl of Gaussian distributions so that the difference between the modeled and the actual hiHtograms is minimized. n
hmod cl ( g) =
2:= n
.;=)
ai
e - (g -IL; )2 /( 2<>7) .
(6. 10)
Variable 9 representH gray-level values from the set G of image gray-levels, ai ; {L i and (ji denote parameters of the Gaus::;iall distribution for the region i. The optimal parameterH of the GausHian distributions are determined by minimizing the fit function F: F=
2:= ( hmodcl (g) - hrcgion (g) ) 2 .
(6. 1 1 )
g EG
In this method, Levenberg-Marquardt [Marquardt, 1963; Press et al., 1992] minimiza tion waH successfully used for segmentation of three-dimensional Tl-weighted images from a magnetic resonance scanner into regions of white matter ( WM ) , gray matter ( GM ) , and cerebro-spinal fluid ( CSF ) ( see Seetion 1 0 . 5 . 1 for a description of a different approach to the same problem using multi-band image data ) . A nine-parameter model (n = 3) was first fitted to the entire volume histogram and the parameters (ji and {LesE' were determined from the global histogram. ( The {LesF parameter was determined globally, since CSF regions are relatively small and localized. ) An example of a global histogram, fitted GauHsian distributions, and the three distributionH corresponding to WM, GM, and CSF is given in Figure 6.5. The remaining five parameters are determined locally by minimizing the function F in each of the overlapping 45 x 45 x 45 pixel (volume picture elements-voxels ) 3D Hub-regions located 10 voxels apart in all three dimensions. Non-collvergent solutions (Flocal > 10 Fglobal ) are neglected and interpolation of neighbor ing parameters is used instead. Then, Gaussian distribution parameters are tri-linearly interpolated for voxcls between the minimized fit locations. Thus, the optimal thresholds can be determined for each voxel and used for segmentation. In [Santago and Gage, 1993] , the partial volume effect was also considered ( in brain MR images, the finite-size voxels can consist of a combination of, e.g., gray and white matter) and a volume percentage Volume %
Volume %
16
16
12 8
16
12
12
4
4
8
4
a
Volume %
0
50
l Oa 1 50 200 2S0 Gray level
( a)
a
Gray matter
8
()
50
100
I SO 200 2S0 (b)
Gray level
a
a
so
100 1 50 200 250 (e)
Gray level
Segmentation of 3D T l-weighted MR brain image data llsing optimal thresholding. (a) Local gray-level histogram. (b) Fitted Gaussian distributions, global 3D image fit. (c) Gaus sian distributions corresponding to WM, GM, and CSF. Courtesy of R. J. Fra.nk, T. J. Grabowski, Figure 6 . 5 :
The University of Iowa.
6.1
Figure 6.6: Optimal MR brain image segmentation. Left
Thresholding
183
column: original T l-weighted MR
images, two of 120 slices of the 3D volume. Middle left: Partial-volume maps of gray matter. The brighter the voxel, the higher is the partial volume percentage of gray matter in the voxel. Middle right: Partial-volume maps of white matter. Right column: Partial-volume maps of
cerebra-spinal fluid. CouI·tuy of R. J. Frank, T. J. Gmbow8ki, The University of Iowa.
corresponding to WM, GM, and CSF was calculated for each voxel. Figure 6.6 gives an example of such brain segmentation. The brighter the voxel location in individual segmented images, the higher the volume percentage of the GM, WM, or CSF in that particular voxel. In each voxc\, the sum of partial volume percentages is
6.1.3
100%.
M ulti-spectral thresholding
Many practical segmentation problems need more information than is contained in one spectral band. Color images are a natural example, ill which information is coded in three spectral bands, for example, red, green, and blue; multi-spectral remote sensing images or meteorological satellite images may have even more spectral bands. One segmentation approach determines thresholds independently in each spectral band and combines them into a single segmented image.
Algorithm 6.3: Recursive multi-spectral thresholding
1. 2.
Initialize the whole image as a single region. Compute a smoothed histogram (see Section
2.3.2)
for each spectral hand. Find
the most significant peak in each histogram and determine two thresholds as local
184
Chapter 6: Segmentation I
minima on either side of this maximum. Segment each region in each spectral band into sub-regions according to these thresholds. Each segmentation in each spectral band is projected into a multi-spectral segmentation-see Figure 6.7. Regions for the next processing steps are those in the multi-spectral image. 3. Repeat step 2 for each region of the image until each region's histogram contains only one significant peak.
o ( a)
(b)
Figure 6.7: Recursive multi-spectral thresholding. thresholding. (c) Multi-spectral segmentation.
(e)
(a) Band 1 thresholding.
(b) Band 2
Region shapes can be adjusted during recursive pre-processing--for instance, boundary stretching, etc. (see Section 6_2.7) . Better segmentation results can be achieved by analyzing multi-dimensional histograms instead of histograms for each spectral band in step 2 of the previous algorithm. fvIulti-spectral segmentations are often based on n-dimensional vectors of gray-levels in n spectral bands for each pixel or small pixel neighborhood. This segmentation approach, widely used in remote sensing, results from a classification process which is applied to these n-dimensional vectors. Generally speaking, regions are formed from pixels with similar properties in all spectral bands, with similar n-dimensional description vectors; see Chapter 9. Segmentation and region labeling based on supervised, unsupervised, and contextual classification is discussed in more detail in Section 10. 5 . 1 .
6.2
Edge-based segmentation
Edge-based segmentation represents a large group of methods based on information about edges in the image; it is one of the earliest segmentation approaches and still remains very important. Edge-based segmentations rely on edges found in an image by edge detecting operators-these edges mark image locations of discontinuities in gray-level, color, texture, etc. A variety of edge detecting operators was described in Section 5.3.2, but the image resulting from edge detection cannot be used as a segmentation result. Supplementary processing steps must follow to combine edges into edge chains that correspond better with borders in the image. The final aim is to reach at least a partial segmentation---that is, to group local edges into an image where only edge chains with a correspondence to existing objects or image parts are present.
6.2 Edge-based segmentation
185
We will discuss several edge-based segmentation methods which differ in strategies leading to fillal border construction, alld also differ in the amount of prior information that can be incorporated into the method. The more prior information that is available to the segmentation process, the better the segmentation results that can be obtained. Prior knowledge can be included in the cOllfidence evaluation of the resulting segmentation as well. Prior information affects segmentation algorithms; if a large amount of prior information about the desired result is available, the boundary shape and relations with other image structures are specified very strictly and the segmentation must satisfy all these specifications. If little information about the boundary is known, the segmentation method must take more local information about the image into consideration and combine it with specific knowledge that is general for an application area. If little prior information is available, it cannot be used to evaluate the confidence of segmentation results, and therefore no basis for feedback corrections of segmentation results is available. The most common problems of edge-based segmentation, caused by image noise or unsuitable information in an image, are an edge presence in locations where there is no border, and no edge presence where a real border exists. Clearly both these cases have a negative influence on segmentation results. First, we will discuss simple edge-based methods requiring minimum prior information, and the necessity for prior knowledge will increase during the section. Construction of regions from edge-based partial segmentations is discussed at the end of the section.
6.2. 1
Edge image thresholding
Almost no zero-value pixels are present in an edge image, but small edge values correspond to non-significant gray-level changes resulting from quantization noise, small lighting irregularities, etc. Simple thresholding of an edge image can be applied to remove these small values. The approach is based on an image of edge magnitudes [Kundu and Mitra, 1987] processed by an appropriate threshold. Figure 6.8a shows an original image, an edge image [as produced by a non-directional Sobel edge detector, see Section 5.3.2, equation (5.44)] is in Figure 6.8b, an 'over-thresholded' image is in Figure 6.8c, and an 'under-thresholded ' image is in Figure 6.8d. Selection of an appropriate global threshold is often difficult and sometimes impossible; p-tile thresholding can be applied to define a threshold, and a more exact approach using orthogonal basis functions is described in [Flynn, 1 972] which, if the original data has good contrast and is not noisy, gives good results. A problem with simple detectors is the thickening that is evident in Figure 6.8b where there should only be a simple boundary. This can be partially rectified if edges carry directional information (as they do with the Sobel) by performing some form of non-maximal suppression (see Section 5 3.5) to suppress multiple responses in the neighborhood of single boundaries. The following algorithm generates Figure 6.9a from Figure 6.8b. .
Algorithm 6.4: Non-maximal suppression of directional edge data 1. Quantize edge directions eight ways according to 8-connectivity (cf. Figures 2.5 and 4.3).
186
Chapter 6: Segmentation I
2. For each pixel with non-zero edge magnitude, inspect the two adjacent pixels indicated by the direction of its edge (S€€ Figure 6.10). 3. If the edge magnitude of either of these two exceeds that of the pixel under inspection, mark it for deletion.
4. When all pixels have been inspected, re-scan the image and erase to zero all edge data marked for deletion. Thil; algorithm is based on 8-connectivity and may be simplified for 4-conneetivitYi it is also opell to more sophisticated measmement of edge direction. It is probable that such data will still be cluttered by noise (as in this case). The hYl-iteresis approach outlined in Section 5.3.5 is also generally applicable if suitable thresholds can be determined. Supposing that edge magnitudes exceeding t, can be taken
(b)
(a)
'.
���: ,
.
« )
.
,C" ,''. '
•• . . .. " .
. .
"
d .
\
,
(d)
Figure 6.8: Edge image thresholding. (a) Original image. (b) Edge image (low contrast edges enhanced for display). (c) Edge image thresholded at 30. (d) Edge image thrcsholded a!. to.
6.2 Edge-based segment3tion
187
I\
�v; ��"��J�1
.
,� w-
I rr;;,�,
,I 0 -
Jt;u " �ct � 0::1 � �,� &:,1' " I!�� .
� =""'"'� "
....
} rl 0
(b)
Figure 6.9: (a) Non-maximal suppression of the data in Figure 6.8a.. (b) hysteresis applied to (a); high threshold 70, low threshold 10. as certain (Le., not due to noise), and that edge magnitudes less t.han to may be assumed to be noise induced, the ronawing algorithm may be defined. Algorithm 6.5: Hysteresis to filter output of an edge detector
1. Mark all edges with magnitude greater than tl as correct.
2. Scan all pixels with edge magnitude in the range [to, tIl. 3. If such a pixel borders another already marked as an edge, then mark it too. 'Bordering' may be defined by 4- or 8-connectivity. 4. Repeat from step 2 until stability.
Boundary in image
�7'------_
Neighboring pixels (defined by edge direction)
Figure 6.10:
Pixel under inspection
Non-maximal suppression; pix
els adjacent with respect to local edge in formation arc inspected.
Canny [Canny, 1986J reports choOSing tdto to be in the range 2 to 3; clearly, if a p-tile approach is ava.ilable, this would guide the choice of t, . Figure 6.9b illustrates the application of this algorithm. Hysteresis is a generally applicable technique that may be deployed whcn evidence is generated with 'strength' that is not susceptible to simple thresholding.
188
Chapter 6: Segmentation I
Other forms of post-processing are also available, for example, to remove all border segments with length less than a specified value, or to consider the average edge strength of a (partial) border.
6.2.2
Edge relaxation
Borders resulting from the previous method are strongly affected by image noise, often with important parts missing. Considering edge properties in the context of their mutual neighbors can increase the quality of the resulting image. All the image properties, including those of further edge existence, are iteratively evaluated with more precision until the edge context is totally clear-based on the strength of edges in a specified local neighborhood, the confidence of each edge is either increased or decreased. A weak edge positioned between two strong edges provides an example of context; it is highly probable that this inter-positioned weak edge should be a part of a resulting boundary. If, on the other hand, an edge (even a strong one) is positioned by itself with no supporting context, it is probably not a part of any border. d
a
b
DDD DDD
g
e
c
Figure 6 . 1 1 :
h
f
Crack edges surrounding central edge
e.
A method we are going to discuss here [Hanson and Riseman, 1978; Prager, 1980] is a classical example of edge context evaluation. This method uses crack edges (edges located between pixels), which produce some favorable properties (see Section 2.3) , although the method can work with other edge representations as well. Edge context is considered at both ends of an edge, giving the minimal edge neighborhood shown in Figure 6 . 1 l . All three possible edge positions at the end o f the edge e must b e included t o cover all the possible ways the border can continue from both ends of e. Furthermore, two edge positions parallel with the edge c can be included in the local neighborhood--these parallel positions compete with the edge e in the placement of the border. Edge relaxation aims for continuous border construction, so we discuss the edge patterns that can be found in the local neighborhood. The central edge e has a vertex at each of its ends, and three possible border continuations can be found from both of these vertices. Let each vertex be evaluated according to the number of edges emanating from the vertex, not counting the edge e; call this number the vertex type. The type of edge e can then be
6.2 Edge-based segmentation e
. . - - .
0-0
I I
e
--
- _ .. .. -
1 -1
( a)
I I
--
2-0
I I
e
- _ .. ... _
_-
3-3
(c)
(b ) Figure 6 . 1 2 :
e
- - - _ ..
I I
189
-
(d)
Edge patterns and corresponding edge types.
represented using a number pair .i describing edge patterns at each vertex, where i and j are the vertex types of the edge e. For example, it assigns type 0 0 for the edges shown in Figure 6.12a, type 3 - 3 in for Figure 6. 12d, etc. Dy symmetry, we need only consider the cases where :::; j. The following context situations are possible:
i
-
-
i
•
0-0 isolated edge-negative influence on the edge confidence,
•
0-1 uncertain-weak positive, or no influence on edge confidence,
•
0-2, 0-3 dead end-negative influence on edge confidence,
• •
•
1-1
continuation-strong positive influence on edge confidence,
1-2, 1-3 continuation to border intersection--medium positive influence on edge confidence, 2-2, 2-3, 3-3 bridge between borders -not necessary for segmentation, no influence on edge confidence.
An edge relaxation can be defined from the given context rules that may be considered a production system, Section 9 . 1 . Edge relaxation is an iterative method, with edge confidences converging either to zero ( edge termination) or one ( the edge forms a border) . The confidence c(l ) (e) of each edge e in the first iteration can be defined as a normalized magnitude of the crack edge, with normalization based on either the global maximum of crack edges in the whole image, or on a local maximum in some large neighborhood of the edge, thereby decreasing the influence of a few very high values of edge magnitude in the image. as
Algorithm 6.6: Edge relaxation 1. Evaluate a confidence
c(1) (e)
for all crack edges e in the image.
2. Find the edge type of each edge based on edge confidences c(k ) (e) in its neighbor hood. 3. Update the confidence C(k+ l ) (e) of each edge e according to its type and its previous confidence c(k) (e). 4. Stop if all edge confidences have converged either to 0 or 1 . Repeat steps 2 and 3 otherwise.
190
Chapter 6: Segmentation I
The main steps of Algorithm 6.6 are evaluation of vertex types followed by evaluation of edge types, and the manner in which the edge confidences are modified. A vertex is considered to be of type i if
type(i) = m:x (type ( k )) , k = 0, 1 , 2 , 3 , a) ( rn - b ) (rn - c) , type(O) = ( type(l) = a ( rn - b) ( rn - c) , type(2) = a b ( rn c) , type(3) = a b c , rn
(6.12)
-
-
where a, b, c are the normalized values of the other incident crack edges, and without loss of generality we can assume a ;::: b ;::: c; q is a constant, for which a value of approximately 0.1 seems to be appropriate, and rn = max ( a, b, c, q) [Ballard and Brown, 1982]. Note that the introduction of the quantity q ensures that type(O) is non-zero for small values of a. For example, choosing q = 0.1, a vertex ( a, b, c) (0.5, 0.05, 0.05) is a type 1 vertex, while a vertex (0.3, 0.2, 0.2) is a type 3 vertex. Similar results can be obtained by simply counting the number of edges emanating from the vertex above a threshold value. Edge type is found as a simple concatenation of vertex types, and edge confidences are modified as follows : =
Confidence increa.<; e: Confidence decrease:
c( k+ 1) ( e) = min ( 1, c( k ) (e) + 8) , C( k+ l ) (e) max (0, c( k ) (e) 8) , =
-
(6.13) (6.14)
where 8 is an appropriate constant, usually in the range 0.1 to 0.3. Edge confidence modification rules can be simplified and just one value of 8 can be used, not including the weak, moderate, or strong confidence increase / decrease options. Further, vertex types 2 and 3 can be considered the same in implementation because they result in the same production rules. Edge relaxation, a8 described above, rapidly improves the initial edge labeling in the first few iterations. Unfortunately, it often slowly drifts, giving worse results than expected after larger numbers of iterations. A theoretical explanation, convergence proof, and practical solutions are given in [Levy, 1988]. The reason for this strange behavior is in searching for the global maximum of the edge consistency criterion over all the image, which may not give locally optimal results. A solution is found in setting edge confidences to zero under a certain threshold, and to one over another threshold which increases the influence of original image data. Therefore, one additional step must be added to the edge confidence computation [equations (6.13) and (6.14)] : If c( k+l) (e) > Tl If c ( k+l) (e) < T2
then assign c( k+ l ) (e) = 1 , then assign C( k+l ) (e) = 0 ,
(6.15) (6.16)
where TJ and T2 are parameters controlling the edge relaxation convergence speed and resulting border accuracy. Moreover, this method makes multiple labelings possible; the existence of two edges at different directions in one pixel may occur in corners, cro8ses, etc. Edge relaxation results are shown in Figure 6.13, where edges parallel with the central edge were not considered in the relaxation process. The relaxation method can
6.2 Edge-based segmentation
(al
« I
191
(bl
(dl
Figure 6.13: Edge relaxation, see Figure 3.11a for original (3) Resulting borders after 10 iterations. (b) Borders after thinning. (c) Borders after 100 iterations, tl.inned. (d) Borders after 100 iterations overlaid over original.
easily be implemented in parallel, with snrprisingly good speedup. Implementation on a
used; in other words, using 16 processors the processing was almost 16 times faster than
16-proces50f hypercube showed almost linear speedup if 2, 4, 8, or 16 processors were
using one proces.'iOf (note that linear speedup is uncommon in parallel implementations). Other approaches to edge relaxation use edge and border information derived from image data.
A
method to determine probabilistic distribution of possible edge neighborhoods is assess
edge patterns; neural networks are employed as a means for fuzzy rule training.
given in [Sher, 1992]. III [Kim and Cho, 1994], fuzzy logic is used to
6.2.3
neighborhood
Border tracing
If a region border is Ilot known but regions have been defined in the image, borders can be uniquely detected. First, let us as..'!ume that the image with regions is either binary or that regions have been labeled (see Section 8.1). The first goal is to determine
inner region
192
Chapter 6: Segmentation I
borders. As defined earlier, an inner region border is a subset of the region-conversely, the outer border is not a subset of the region. The following algorithm covers inner boundary tracing in both 4-connectivity and 8-connectivity.
Algorithm 6.7: Inner boundary tracing 1. Search the image from top left until a pixel of a new region is found; this pixel Po then has the minimum column value of all pixels of that region having the minimum row value. Pixel Po is a starting pixel of the region border. Define a variable dir which stores the direction of the previous move along the border from the previous border element to the current border element. Assign ( a) dir = 3 if the border is detected in 4-connectivity ( Figure 6.14a) , ( b ) dir = 7 if the border is detected in 8-connectivity ( Figure 6. 14b ) . 2. Search the 3 x 3 neighborhood of the current pixel in an anti-clockwise direction, beginning the neighborhood search in the pixel positioned in the direction ( a) ( dir + 3 ) mod 4 ( Figure 6. 14c) , ( b ) ( dir + 7 ) mod 8 if dir is even ( Figure 6. 14d ) , ( dir + 6 ) mod 8 if dir is odd ( Figure 6.14e) . The first pixel found with the same value as the current pixel is a new boundary element Pn. Update the dir value. 3. If the current boundary element Pn is equal to the second border element P1 , and if the previous border element Pn-1 is equal to Po, stop. Otherwise repeat step 2. 4. The detected inner border is represented by pixels Po · . . Pn- 2 • Algorithm 6.7 works for all regions larger than one pixel ( looking for the border of a single-pixel region is a trivial problem ) . This algorithm is able to find region borders but does not find borders of region holes. To search for hole borders as well, the border must be traced starting in each region or hole border element if this element has never been a member of any border previously traced. The search for border elements always starts after a currently traced border is closed, and the search for 'unused' border elements can continue in the same way as the search for the first border element was done. Note that if objects are of unit width, more conditions must be added. If the goal is to detect an outer region border, the given algorithm may still be used based on 4-connectivity.
Algorithm 6.8: Outer boundary tracing 1. Trace the inner region boundary in 4-connectivity until done. 2. The outer boundary consists of all non-region pixels that were tested during the search process; if some pixels were tested more than once, they are listed more than once in the outer boundary list.
6.2 Edge-based segmentation
193
2
2
3
--r--- O
4
-----'*E--. 0
\
7
5 3
A
�
"
(e)
6 (b)
"-
�
-to.
./
. . . . .. .. . . . . . . . .
f:J : 'r . ..,
-to.
./
r=l I con ec
(e) (d) Figure 6.14: Inner boundary tracing. (a) Direction 1I0tation, 4-oonnectivity. (b) s.
n tivity. (d), (e) Search sequence in 8connectivity. (f) Boundary tracing ill S-counectivity (dotted lines show pixels tested during the border tracing).
(el Pixel neighborhood search sequence
in 4-connectivity.
Note that some border elements may be repeated in the outer border up to three
times-see Figure 6.15. The outer reglon border is useful for deriving properties such perimeter, compactness, etc., and is consequently often used-see Chapter
8.
as
The inner border is always part of a region but the outer border nevel" is. Therefore, if two regions ace adjacent, they never have a common border, which causes difficulties in higher processing levels with region description, region merging, etc. The inter-pixel boundary extracted, for instance, from crack edges is common to adjacent regions; nevertheless, its position cannot be specified in single pairs of pixel co-ordinates (compare
•
•
• •
• •
•
•
•
•
•
•
• •
Figure 6.15: Outer bounda.ry tracing; may be listed several times.
•
•
•
•
• •
•
•
•
denotes outcr border elements. Note that somc pixels
194
Chapter 6: Segmentation I
the supergrid data structure in Figure 6.42 ) . Boundary properties better than those of inner and outer borders may be found in extended borders [Pavlidis, 1977] . The main advantage of the extended boundary definition is that it defines a single common border between adjacent regions, and it may be specified using standard pixel co-ordinates (see Figure 6.16). All the useful properties of the outer border still remain; in addition, the boundary shape is exactly equal to the inter-pixel shape but is shifted one half-pixel down and one half-pixel right. The existence of a common border between regions makes it possible to incorporate into the boundary tracing a boundary description process. An evaluated graph consisting of border segments and vertices may result directly from the boundary tracing process; also, the border between adjacent regions may be traced only once and not twice as in conventional approaches.
f]D (a)
(c)
(b)
Boundary locations for inner, outer, and extended boundary definition. (a) Inner. (b) Outer. (c) Extended.
Figure 6.16:
The extended boundary is defined using 8-neighborhoods, and the pixels are coded according to Figure 6.17a, e.g., P4 (P) denotes the pixel immediately to the left of pixel P . Four kinds of inner boundary pixels of a region R are defined; if Q denotes pixels outside the region R, then a pixel P E R is a LEFT pixel of R a RIGHT pixel of R an UPPER pixel of R a LOWER pixel of R
if P4 (P) if Po(P) if P2 (P) if P6 (P)
EQ,
EQ
,
EQ, EQ.
Let LEFT(R) , RIGHT(R), UPPER(R) , LOWER(R) represent the corresponding subsets of R. The extended boundary EB is defined as a set of points P, Po, P6 , P7 satisfying the following conditions [Pavlidis, 1977; Liow, 1991] :
EB = { P : P E LEFT(R) } U {P : P E UPPER(R) }
U { P6 (P) : P E LOWER(R) } U { po(P) : P E RIGHT(R) } U { P7(P) : P E RIGHT(R) } .
(6.17)
Figure 6.17 illustrates the definition. The extended boundary can easily be constructed from the outer boundary. Using an intuitive definition of RIGHT, LEFT, UPPER, and LOWER outer boundary points, the extended boundary may be obtained by shifting all the UPPER outer boundary points
6.2 Edge-based segmentation
3
2
5
P
0
6
7
4
I
195
(d)
(b)
rr==:J ' llJ
(.)
.. . . . . . . . . . . . . .. . . .. . . . . . . . . . . . .
(cJ
(eJ
Extended boundary definition. (a) Pixel coding scheme. (b) Region R. (e) LEFT(R). (d) LOWER(R). (e) Extended boundary. Figure 6.17:
one pixel down and right, shifting all the right, and shifting all the
RlGHT
LEFT ollter boundary points
outer boundary point positions remain nnchanged; sec Figure
II
The LOWER
6.18.
I
(.J
Figure
olle pixel to the
outer boundary points onc pixel down.
(oj
(bJ
6.18: COIU;Lrllcting the extended boundary frolll outer boundary. (a) Outer boundary. (b) Extended boundary constructioll. (e) Extended boundary lias the same shape and size as
the natural object boundary.
A more sophisticated method for extended boundary tracing was introduced together
with
an
efficient algorithm in
[Liow, 1991).
The approach is based on detecting common
boundary segments betwe<m a.djacent regions a.nd vertex points in boundary segment connections. The detection process is based on a look�up table, which defines all 12 possible situations
of t he local configuration
of 2x2 pixel windows, depending on the
previous detected direction of boulldary, and on t he status of window pixels which Catl be inside or outside a region.
Algorithm 6.9: Extended boundary tracing
1.
Define a starting pixel of an extended boundary in a standard way (the first region pixel found in a left-to-right and top-to-bottom line-by�line image search).
2. The first move along the traced boundary from the starting pixel
di1' = 6
3. Trace the extended boundary extended border results.
s i
Figure 6.19. using the look�up table in Figure 6.19
(down), corresponding to the situation (i) in
in direction
until a closed
196
Chapter
6: Segmentation I
(c) Background �(a) � � (e) '------' (g) � b a c k g r o u n d � ( I) (b)
L----'----'
D
'+'-- --->-'----'---
pixel
(fl
(d)
hi �I::-
Region
pixel
(h)
tJJ ,I
L-_-----' (k)
( i)
D
Region or
pi xe l
Figure 6.19: Look-up table defining all 12 possible situations that can appear during extended border tracing. Current pooition is in the central pixel. The direction of the next move depends on the local configuration of background and region points, and on the direction of approach to the current pixel. Adapte
Note that no hole-border tracing is included in �he algorithm. The holes are considered separate regions and therefore the borders between the region and itl; hole are traced as
a
border of the hole. The look-up table approach makes the tracing more efficient than conventional methods and makes parallel implementation pos...:;ible.
A pseudo-code description of
all the borders in an image in an eHicielit way is given. In addition to extended boundary algorithmic detail., is givcn ill {Liow, 1991], where a wlution to the problems of tracing
tracing, it provides a description of each houndary segmeut in chain code form together with inforlllation about vcrticCl;. This method is very suitahle for representing borders in
each border
higher-level $egmentation approaches including methods that int.egrate edge-based and regioll-based segment.ation results. Moreover, in the conventional approaches,
het.ween two regiolls must be traced twice. The algorithm can trace each boundary segment only once, st.oring the informat.ion about what has already been done in double-linked
A more difficult situation is encountered if the borders are traced in gray-level
lists.
is represented by a
images where regions have not yet been defined {Dudani, 19761. Therefore, the border
simple path of high-gradient. pixels in t.he image (see
Section 2.3.1).
Border tracing should be started in a pixel with a high probability of being a border element, and thell border construction is based on the idea of adding the next elements
6.2 Edge-based segmentation
197
which are in the most probable direction. To find the following border elements, edge gradient magnitudes and directions are usually computed in pixels of probable border continuation.
Algorithm 6.10: Border tracing in gray-level images 1 . Suppose the border has been determined up to the border element Xi .
2. Define an element Xj as a pixel adjacent to Xi in the direction ¢(Xi ) . If the gradient magnitude in Xj is larger than the preset threshold, Xj is considered a border element; return to step 1 . Otherwise proceed to step 3. 3. Compute the average gray-level value in the 3x3 neighborhood of the pixel Xj . Compare the result with some preset gray-level value and decide whether Xj is positioned inside or outside the region. Proceed to step 4. 4. Try to continue the border tracing in pixel Xk which is adjacent to Xi in direction [¢(Xi) ± 7r/4] ' the sign being determined according to the result of step 3. If a border continuation is found, Xk is a new border element, and return to step 1 . If Xk is not a border element, start the border tracing at another promising pixel. This algorithm can be applied to multi-spectral or dynamic images (temporal image sequences) as well, ba.'led on multi-dimensional gradients. An algorithm for crack-edge boundary tracing that uses a concept of finite topological spaces and cell complexes is given in [Kovalevsky, 1 994J . Its application to connected component labeling (Section 8 . 1 ) , object interior filling, and shape description (Chapter 8) is also discussed.
6.2.4
Border detection as graph searching
Whenever additional knowledge is available for boundary detection, it should be used. One example of prior knowledge is a known starting point and a known ending point of the border, even if the precise border location is not known. Even some relatively weak additional requirements such as smoothness, low curvature, etc., may be included as prior knowledge. If this kind of supporting information is available in the border detection task, general problem-solving methods widely used in AI can be applied. A graph is a general structure consisting of a set of nodes ni and arcs between the nodes (ni ' n j ) (see Section 4.2.3) . We consider oriented and numerically weighted arcs, these weights being called costs. The border detection process is transformed into a search for the optimal path in the weighted graph, the aim being to find the best path that connects two specified nodes, the starting and ending nodes. While cost minimization is considered throughout this section, the approach works equally well if a maximum cost path is sought. Assume that both edge magnitude s (x) and edge direction ¢(x) information is available in an edge image. Each image pixel corresponds to a graph node weighted by a value s(x). Two nodes ni and nj corresponding to two 8-connected adjacent pixels Xi and Xj are connected by an arc if the edge directions ¢(Xi ) and ¢(Xj ) match the local border direction. We can apply the following rules to construct the graph: To connect a node rLi representing the pixel Xi with a node nj representing the pixel Xj , pixel Xj must
198
Chapter 6: Segmentation I
be one of three exi�ting neighbors of Xi in the direction d E [¢(Xi) - 7r / 4, ¢(Xi) + 7r /4] . Further, s (x;) and s(Xj ) must be greater than T, where T is some preset threshold of edge significance. Another common requirement is to connect two nodes only if the difference of their edge direction� is less than 7r /2. These condition� can be modified in specific edge detection problems. Figure 6.20a �hows an image of edge directions, with only significant edges according to their magnitudes listed. Figure 6.20b �hows an oriented graph constructed in accordance with the presented principles.
Jf ---3>- - --'7 ---3>-
�
--'7
�
/
--'7
�
� �
Jf
--'7
/
--'7
/
-
--'7
(a)
t
/
(b)
Figure 6.20: Graph representation of an edge image. (a) Edge directions of pixels with above threshold edge magnitudes. (b) Corresponding graph.
The application of graph search to edge detection was first published in [Martelli, 1972] , in which Nilsson's A-algorithm [Nilsson, 1 982] applies. Let XA be the starting border element, and XB be the end border dement. To use graph search for region border detection, a method of oriented weighted-graph expansion mmit fir�t be defined (one possible method was described earlier) . A cost function f (xd must also be defilled that is a cost estimate of the path between nodes nA and nJ3 (pixels XA and XB ) which goes through an intermediate node ni (pixel X·i ) . The cost function f(Xi) typically consists of two component�; an e�timate g (Xi ) of the minimum path cost between the starting border dement XA and Xi , and an estimate h,(Xi) of the minimum path cost between Xi and the end border element XB . The cost .q (X'i ) of the path from the starting point to the node ni is usually a sum of cost� associated with the arcs or nodes that are ill the path. The cost function must be separable and llJonotonic with respect to the path length, and therefore the local co�ts associated with arcs are required to be nOll-negative. A simple example of ,q (Xi) satbfying the given conditions is to consider the path length from XA to Xi · An estimate h (xd may be the length of the border from Xi to XB , it making sense to prefer shorter border� between XA and XB as the path with lower cost. This implies that the following graph search algorithm ( Nilsson's A-algorithm) can be applied to the border detection.
Algorithm 6.11: A-algorithm graph search 1. Expand the starting node n.4. and put all its successors into an OPEN list with pointers back to the starting node nA . Evaluate the cost function f for each expanded node.
6.2 Edge-based segmentation
199
2. If the OPEN list is empty, faiL Determine the node ni from the OPEN list with the lowest associated cost f(ni) and remove it. If ni = nB , then trace back through the pointers to find the optimum path and stop. 3. If the option to stop was not taken in step 2 , expand the specified node ni , and put its successors on the OPEN list with pointers back to ni . Compute their costs f. Go to step 2 .
An example of this algorithm is given in Figure 6.21. Here, nodes currently on the OPEN list are shaded and the minimum-cost node on the OPEN list is shaded and outlined. In Figure 6.21c, note that the node with a cumulative cost of 7 is also expanded; however no successors are found. In Figure 6.21e, since an expansion of a node in the final graph layer was attempted, the search is over. If no additional requirements are set on the graph construction and search, this process can easily result in an infinite loop (see Figure 6.22 ) . To prevent this behavior, no node expansion is allowed that puts a node on the OPEN list if this node has already been visited and put on the OPEN list in the past. A simple solution to the loop problem is not to allow searching in a backward direction. This approach can be used if a priori information about the boundary location and its local direction is available. In this case,
4�4 «NOdC
00080
Cumulative o 0 0 07 06 0/ c st
o 2
5
00 2 00 Start node
00080
00080
(b)
(c)
Cost ��de
(a )
0 0 0 00 (d)
(e)
(f)
Figure 6 . 2 1 : Example of a graph searching sequence using the A-algorithm (see text for description of progress of algorithm). (a) Step 1, expansion of the start node. (b) Step 2. (c) Steps 3 and 4. (d) Step 5. (e) Step 6. (f) The optimal path is defined by baek-traeking.
Chapter 6: Segmentation I
200 311
�
7
t
"
311
E
�
j
/
Figure 6.22: Example of following a closed loop in image data.
it may be possible to straighten the processed image (and the corresponding graph) as shown in Figure 6.23. The edge image is geometrically warped by re-sampling the image along profile lines perpendicular to the approximate position of the sought border. The pre-processing step that straightens the image data provides a substantial computational convenience. No backward searches may be allowed to trace boundaries represented this way. This approach can be extremely useful if the borders of thin, elongated objects such as roads, rivers, vessels, etc., are to be detected. On the other hand, prohibiting the backward search may limit the shapes of borders that can be successfully identified. In [van der Zwet and Reiber, 1994] ' a graph-search based method called the gradient field transform is introduced that allows searching to proceed successfully in any direction. The estimate of the cost of the path from the current node ni to the end node nB has a substantial influence on the search behavior. If this estimate h(ni) of the true cost h(ni) is not considered, so (lL(ni ) = 0), no heuristic is included in the algorithm and a breadth-first search is done. Because of this, the detected path will always be optimal according to the criterion used, and thus the minimum-cost path will always be found. Applying heuristics, the detected cost does not always have to be optimal but the search can often be much faster.
/ � Profiles
\
� \
'\
/ /
L
L
/
\ I
/
/
/ /
I
\ \ \
Approximate Original edge image
center line
Warped edge i mage
Geometric warping produces a straightened image: The graph constructed requires (and allows) searches in one main direction only (e.g., top-down) . Adapted from (Fleagle et ai., Figure 6.23:
1989/.
6.2 Edge-based segmentation
201
Given natural conditions for estimates g, the minimum-cost path result can be ranteed if h(ni) :s; h(ni) and if the true cost of any part of the path c(np, nq) is larger gua than the estimated cost of this part c(np, nq). The closer the estimate h(ni) is to h(ni), the lower the numbcr o f nodes expanded i n the search. The problem i s that the exact cost of the path from the node ni to the end node nB is not known beforehand. In some applications, it may be more important to get a quick rather than an optimal solution. Choosing h(ni) > h(ni), optimality is not guaranteed but the number of expanded nodes will typically be smaller because the search can be stopped before the optimum is found. A comparison of optimal and heuristic graph search border detection is given in Figure 6.24 . The raw cost function [called the inverted edge image, inversion defined according to equation (6. 18) ] can be seen in Figure 6.24a; Figure 6.24b shows the optimal borders resulting from the graph search when h(ni) = 0; 38% of nodes were expanded during the search, and expanded nodes are shown as white regions. When a heuristic search was applied [r�(ni) was about 20% overestimated] , only 2% of graph nodes were expanded during the search and the border detection was 15 times faster (Figure 6.24c). Comparing resulting borders in Figures 6.24b and 6.24c, it can be seen that despite a very substantial speedup, the resulting borders do not differ significantly. We can summarize: • •
•
If h(ni) = 0, the algorithm produces a minimum-cost search.
If h(ni) > h(ni), the algorithm may run faster, but the minimum-cost result is not guaranteed. If h(ni) :s;
h(ni) , the search will produce the minimum-cost path if and only if
for any p, q, where c(np , nq) is the true minimum cost of getting from np to nq, which is not easy to fulfill for a specific f ( x ) .
•
•
If h(ni) = h(ni), the search will always produce the minimum-cost path with a minimum number of expanded nodes. The better the estimate of expanded.
h(n) ,
the smaller the number of nodes that must be
In image segmentation applications, the existence of a path between a starting pixel and an ending pixel XB is not guaranteed because of possible discontinuities in the edge image, and so more heuristics must often be applied to overcome these problems. For example, if there is no node in the OPEN list which can be expanded, it may be possible to expand nodes with non-significant edge-valued successors -this can build a bridge to pass these small dil-lcontinuities in border representations. A crucial question is how to choose the evaluation cost functions for graph-search border detection. A good cost function should have elements common to most edge detection problems and also specific terms related to the particular application. Some generally applicable cost functiom; are: XA
•
Strength of edges forming a border: The heuristic 'the stronger the edges that form the border, the higher the probability of the border ' is very natural and almost always
202
Chapter 6: Segmentation I
(a)
(h)
(e)
fUllction (inverted edge image of a vessel). (0) Optilllal graph search, resulting vessel borders Rre shown adjacent to the cost function, expanded nodes shown (38%). (e) Heuristic graph search, re�;lliling borders and expanded nodes (2%).
Figure 6.24: Comparison of optimal and heuristic graph search performance. (a) R..'\w cost
gives good results. Note that if a border consists of strong edges, the cost of that border is smalL The cost of adding another node to the border will be
( max s(xd) - S(Xi) , Imnge
•
•
(6.18)
where the maximum edge strength is obtained from all pixels in the image. Border curvatme: Sometimes, borders with a smH,1I curvatmc arc preferred. If this is the case, the total border CUl"v(lture can be evaluated as a. monotonic function of local curvaturc increments: diff(¢(x;) - ¢(Xj)) , (6.19) whcre diffis some suitable fUllctioll evalnating the di!fercuce in cdge directions ill two consecutive border clements. Proximity to
an approximate border location: If an approximate bouudary location is known, it is natural to support the paths that are closer to the known approximation
6.2 Edge-based segmentation
203
than others. When included into the border, a border element value can be weighted by the distance ' dist' from the approximate boundary, the distance having either additive or multiplicative influence on the cost dist(xi , approximate_boundary) . •
( 6 .20)
Estimates of the distance to the goal (end point) : If a border is reasonably straight, it is natural to support expansion of those nodes that are located closer to the goal node than other nodes (6.21)
Since the range of border detection applications is quite wide, cost functions may need some modification to be relevant to a particular task. For example, if the aim is to determine a region that exhibits a border of a moderate strength, a closely adjacent border of high strength may incorrectly attract the search if the cost given in equation (6.18) is used. Clearly, functions may have to be modified to reflect the appropriateness of individual costs properly. In the given example, a Gaussian cost transform may be used with the mean of the Gaussian distribution representing the desired edge strength and the standard deviation reflecting the interval of acceptable edge strengths. Thus, edge strengths close to the expected value will be preferred in comparison to edges of lower or higher edge strength. A variety of such transforms may be developed; a set of generally useful cost transforms can be found in [Falcao et a1., 1995J . Overall, a good cost function will very often consist of several components combined together. Graph-based border detection methods very often suffer from extremely large numbers of expanded nodes stored in the OPEN list, these nodes with pointers back to their predecessors representing the searched part of the graph. The cost associated with each node in the OPEN list is a result of all the cost increases on the path from the starting node to that node. This implies that even a good path can generate a higher cost in the current node than costs of the nodes on worse paths which did not get so far from the starting node. This results in expansion of these 'bad ' nodes representing shorter paths with lower total costs, even with the general view that their probabilities are low. An excellent way to solve this problem is to incorporate a heuristic estimate h(Xi) into the cost evaluation, but unfortunately, a good estimate of the path cost from the current node to the goal is not usually available. Some modifications which make the method more practically useful, even if some of them no longer guarantee the minimum-cost path, are available: •
•
•
Pruning the solution tree: The set of nodes in the OPEN list can be reduced during the search. Deleting those paths that have high average cost per unit length, or deleting paths that are too short whenever the total number of nodes in the OPEN list exceeds a defined limit, usually gives good results (see also Section 9.4.2) . Least maximum cost: The strength of a chain may be given by the strength of the weakest element--this idea is included in cost function computations. The cost of the current path is then set as the cost of the most expensive arc in the path from the starting node to the current node, whatever the sum of costs along the path. The path cost does not therefore necessarily grow with each step, and this is what favors expansion of good paths for a longer time. Branch and bound: This modification is based on maximum allowed cost of a path, no path being allowed to exceed this cost. This maximum path cost is either known
204
•
Chapter 6: Segmentation I
beforehand or it is computed and updated during the graph search. All the paths that exceed the allowed maximum path cost are deleted from the OPEN list. Lower bound: Another way to increase the search speed is to reduce the number of poor edge candidate expansions. Poor edge candidates are always expanded if the cost of the best current path exceeds that of any worse but shorter path in the graph. If the cost of the best Sllccessor is set to zero, the total cost of the path does not grow after the node expansion and the good path will be expanded again. The method reported in [Sonka et al. , 1993] assumes that the path is searched in a straightened graph resulting from a warped image as discussed earlier. The cost of the minimum-cost node on each profile is subtracted from each node on the profile (lower bound). In effect, this shifts the range of costs from min(profile_node_costs) � node_cost � max(profile node_costs) __
to
o�
new node_cost , � ( max(profile_node_costs) - min(profile _node_cost) ) .
•
•
__
Note that the range of the costs on a given profile remains the same, but the range is translated such that at least one node for each profile is assigned a zero cost. Because the costs of the nodes for each profile are translated by different amounts, the graph is expanded in an order that supports expansion of good paths. For graph searching in the straightened image, the lower bound can be considered heuristic information when expanding nodes and assigning costs to subpaths in the graph. By summing the minimum value for each profile, the total is an estimate of the minimum-cost path through the graph. Obviously, the minimum cost nodes for each profile may not form a valid path, i.e., they may not be neighbors as required. However, the total cost will be the lower limit of the cost of any path through the graph. This result allows the heuristic to be admissible, thus guaranteeing the success of the algorithm in finding the optimal path. The assignment of a heuristic cost for a given node is implemented in a pre-processing step through the use of the lower bound. Multi-resolution processing: The number of expanded nodes can be decreased if a sequence of two graph search processes is applied. The first search is done in lower resolution, therefore a smaller number of graph nodes is involved in the search and a smaller number is expanded, compared to full resolution. The low-resolution search detects an approximate boundary. The second search is done in full resolution using the low-resolution results as a model, and the full-resolution costs are weighted by a factor representing the distance from the approximate boundary acquired in low resolution (equation (6.20) ) . The weighting function should increase with the distance in a nOll-linear way. This approach assumes that the approximate boundary location can be detected from the low-resolution image [Sonka et al. , 1993, 1994] . Incorporation of higher-level knowledge: Including higher-level knowledge into the graph search may significantly decrease the number of expanded nodes. The search may be directly guided by a priori knowledge of approximate boundary position. Another possibility is to incorporate a boundary shape model into the cost function computation. Both these approaches together with additional specific knowledge and the multi-resolution approach applied to coronary border detection are discussed in detail in Chapter 10 (see Figure 6.25 and Section 10.1.5).
6.2
Edge-based segmentation
205
Figure 6.25: Graph search applied to coronary vessel border dete<:tion. (a) Edge image. (b) De- termined vessel borders.
Graph searching techniques ofTer a convenient way to ensure global optimality of the detected contour. This techniquc has often been applied to the detection of approximately
straight contours. The detcction of closed structure contours would involve gcometrically transforming the image u!'ling a polar-to-rectangular co-ordinate transformation in order to 'straighten' the contour, bllt this may prevent the algorithm from detecting the non-convex parts of the contour. To overcome this problem, the image may be divided into two segments (iterat.ively, if necessary) and separate, simultaneous searches can be conducted
in each segment. The searches are independent and proceed in opposite directions from a start point until they meet at the dividing line between the two image segments. The approaches discussed above search for opt.imal borders between two specific image points, but searching for all the borders in the image without knowledge of the start and end points is more complex. In an approach based on magnitudes and dircctiom. of edges ill the image, edges are merged into edge chains (i.e"
partial borders). Edge
chains are constructed by applying a bi-directional heuristic search in which half of each 8-neighborhood expanded node is considered as lying in front of the edge, the second half as lying behind the edge (see Figure 6.26). Partial borders are grouped together using
o
o
f
o
0
Figure 6.26: Bidirectional heuristic search: Edge prede cessors (marked 0) and successors (marked .) .
206
Chapter 6: Segmentation I
other heuristics which are similar to the approach previously described in edge relaxation ( Section 6.2.2) , and final region borders result. The following algorithm describes the ideas above in more detail and is an example of applying a bottom-up control strategy (see Chapter 10). 1
2
3 Figure 6.27: Rules for edge chain mo d ifi cation ; note that edge responHes resulting from continuous changes of illumination are removed (case 2).
Algorithm 6.12: Heuristic search for image borders 1. Search for the strongest edge in the image, not considering edges previously marked or edges that already are part of located borders. Mark the located edge. If the edge magnitude is less than the preset threshold or if no image edge was found, go to step 5. 2. Expand all the image edges positioned in front of the specified starting edge until no new successors can be found. 3. Expand all the image edges positioned behind the specified starting edge until no new predecessors can be found. In steps 2 and 3 do not include edges that are already part of any existing edge chain. 4. If the resulting edge chain consists of at least three edges, it is stored in the chain list, otherwise it is deleted. Proceed to step 1 . 5. Modify edge chains according t o the rules given i n Figure 6.27. 6. Repeat step 5 until the resulting borders do not change substantially from step to step.
6.2 Edge-based segmentation
207
The rules given in Figure 6.27 (used in step 5 of Algorithm 6.12) solve three standard situations. First, thinner edge responses to a single border are obtained. Second, edge responses resulting from changes of lighting, where no real border exists, are removed. Third, small gaps in boundary-element chains arc bridged. Detailed behavior given by these general rules can be modified according to the partielllar problem. A good overview of border detection and edge linking methods can be found in [v. d Heijden, 1 995] . An interesting approach to border detection based on image filtering, detection of edges, sharp eorners and border junctions (corners of at least two adjacent regions) is presented in [Law et al. , 1996] . The steps other than filtering use fuzzy reasoning to ineorporate loeal image eharaeteristics in the edge detection and edge linking processes. An approach to border detection that uses enhancements of corners and junctions can be found in [Demi, 1996] . Yet another approaeh, based on effectively searching for closed contours of edge elements using all optimal graph seareh approach to data clustering, is presented in [Wu and Leahy, 1993] .
6.2.5
Border detection as dynamic programming
Dynamic programming is an optimization method based on the principle of optimality [Bellmann, 1 957; Pontriagin, 1 962] . It searches for optima of functions in which not all variables are simultaneously interrelated. Consider the following simple boundary-tracing problem (Figure 6.28). The aim is to find the best path (minimum cost) between one of the possible start points A, B, C and one of the possible ending points G, H, I . The boundary must be eontiguous in 8-conneetivity. The graph representing the problem, together with assigned partial costs, is shown in Figure 6.28a,b. As can be seen, there are three ways to get to the node E. Connecting A B gives the cost g ( A , E) = 2; connecting B- E, cost g(B, E) = 6; connecting C-E, cost g( C, E ) = 3. The main idea of the principle of optimality is: Whatever the path to the node E was, there e:rists an opt£mal path between E and the end point. In other words, if the
optimal path start point endpoint goes thnmgh E, then both its parts start point-E and E-end point, are also opt£mal. In our ease, the optimal path between the start point and E is the partial path A --E
(see Figure 6.28c). Only the following information need be stored for future use; to get to E, the optimal path is A-E, cost C ( E ) = 2. Using the same approach, to get to D the optimal path is B-D, cost C ( D ) = 2; the best path to F is B-F, eost C(F) = 1 (see Figure 6.28d). The path may get to node G from either D or E. The cost of the path through the node D is a sum of the cumulative cost C ( D ) of the node D and the partial path eost g(D, G). This cost C(GD) = 7 represents the path B-D-G because the best path to D is from B. The cost to get to G from E is C (G E ) = 5, representing the path A-E-G. It is obvious that the path going through node E is better, the optimal path to G is the path A-E-G with cost C(G) = 5 (see Figure 6.28e) . Similarly, cost C(H) = 3 (B-F-H) and cost C(I) = 7 ( A-E-I). Now, the end point with the minimum path cost represents the optimum path; node H is therefore the optimal boundary end point, and the optimal boundary is B-F H (see Figure 6.28f) . Figure 6.29 gives an example in which node costs are used (not arc costs as in Figure 6.28) . Note that the graph, the cost function, and the resulting path are identical to those used in Figure 6.2 l . If the graph has more la.yers (in Figure 6.28 just three layers were present), the process is repeated until one of the end points is reached. Each repetition consists of a simpler
Chapter 6: Segmentation I
208
A
D E
B
C
Start_nodes
G
F
1
End_nodes
(a)
A B
5
2
B
H
D
7
A
G
6
H
3
C
1
(b) A
�---"-----=�-
-
- - - -'7
B
c
-
-
C
/'
-
-
-
- - ,'" /'
- - - -, -
(d )
(c)
D(l)
-
G(5)
" - - - - - 7' - - ......
H(3)
./
"""
- - -...... -
:<
./
B
1(7)
(f) Edge following as dynamic programming. (a) Edge image. (b) Corresponding graph, partial costs assigned. (c) Possible paths from any start point to E, A - E is optimal. (d) Optimal partial paths to nodes D, E, F . (e) Optimal partial paths to nodes G, H, I. (f) Back-tracking from H defines the optimal boundary. (e)
Figure 6.28:
optimization
as
shown in Figure 6.30a (6.22)
where C(X�'+l ) is the new cost assigned to the node x�'+\ and g"' (i, k ) is the partial path cost between nodes xi and x;;n+l . For the complete optimization problem, ( 6 23) .
where x�1 are the end point nodes, lvI is the number of graph layers between start points and end points ( see Figure 6.30b ) , and C (Xl , .,[;2 , . . , xM ) denotes the cost of a path between the first and the last (Mth ) graph layer. Requiring an 8-connected border and assuming n nodes xi in each graph layer m, 3n cost combinations must be computed for each layer, 3n(M 1) + n being the total number of cost combination computations. Compared to the brute-force enumerative search, where n(3M - 1 ) combinations must be .
-
6.2 Edge-based segmentation
�N"'"
(') 0 0 0 0 0
(b)
o 0 0 0 0/ ''''' 7 .') 24 .') 4
��
(e)
0
Cumulalive
:�:
00000
(d) 0 0 0 000
209
o o
000 0 00 2 00
Figure 6.29: Example of a graph searching sequence using dynamic programming: (a) step 1, expansion of the first graph layer; (b) step 2; (c) step 3--the minimum-cost node in the last layer marked; (d) the optimal path is defined by back-tracking.
computed, the improvement is obvious. The final optimal path results from back-tracking through the searched graph. Note that t.he number of neighbors depends on the definition of contiguity and definitiOll of the searched graph, and lli not limited to three. The complete graph must be cOllstructed to apply dynamic programming, and this may follow general rules given in the previous section. Evaluation functions presented in the previous section may also be appropriate for dynamic programming. Figure 6.31 shows the result of dynamic programming applied to detection of pulmonary fissures from X-ray CT images. Since the fissures nre visualized as bright pixels, the cost function simply reflects inverted pixel gray values. Despite the fact that vessels are su�tantially brighter (their pixels correspond to locl-llly lower costs), the path of the lowest overall cost reflects the continuous character of the fissure. C(x}
m
)
C(x
m
)
C(x /I
)
m
I • • •
C(x
m.' k
(a)
)
,
-
f-
--"
2
11/
111+1
AI
(b)
Figure 6.30: Dynamic programming: (a) one step of the cost calculation; (b) graph layers, node
notation.
Chapter 6: Segmentation I
210
o
Figure 6.31: Detecti n of [)Illmonary fissures using dynamic programming. Top: Sub-region of an original
cross-scctiOllfLl X-ray CT image of a human
lung.
Cottom: Detected fissures showlL in
wlJite.
Algorithm 6.13: Boundary tracing as dynamic programming
1. Specify initial costs C(xl) of all nodes in the first graph layer i = 1, . . . , n partial path costs gm(i,k), m = 1, . . . , M - 1. ,
2.
and
Repeat step 3 for all m = 1, . . , M - l . .
3. Repeat step 4 for all nodes k = 1, . . . , n in the graph layer m.
4.
Let (6.24)
Set pointer from node Xk'+1 back to node predecessor.
x?,·;
where
*
denotes the optimal
optimal node x�1* in the last graph layer M and obtain an optimal path by back-tracking through the pointers from xt.,. to xl · .
5. Find an
It has been shown that heuristic search may be more efficient than dynamic pro gramming for finding a path between two node; in a graph [Martelli, 1976]. FUrther, an A-nlgorithm-bru;cd graph search docs not require explicit definition of the graph. However, dynamic progrnmming prt'.'Scnts an efficient way of simultaneously searching for optimal paths from multiple starting a.ud ending points. If these points are not known, dynamic
6.2 Edge-based segmentation
211
programlning is probably a better choice, especially if computation of the partial costs g m (i, k) is simple. Nevertheless, which approach is more efficient for a particular problem depends on evaluation functions and on the quality of heuristics for an A-algorithm. A comparison between dynamic programming and heuristic search efficiency can be found in [Ney, 1992] ; dynamic programming was found to be faster and less memory demanding for a word recognition problem. Dynamic programming was found to be more computationally efficient than edge relaxation (Section 6.2.2) [Erud, 1988] . Another comparison [Wood, 1985] found dynamic programming more flexible and less restrictive than the Hough transform (Section 6.2.6), and it is a powerful tool in the presence of noise and in textured images. Tracing borders of elongated objects such as roads and rivers in aerial photographs, and vessels in medical images, represents typical applications of dynamic programming in image segmentation. Practical border detection using two-dimensional dynamic programming was developed by Barrett et a1. and Udupa et a1. [r..Iortensen et a1., 1992; Udupa et a1., 1992; Falcao et a1. , 1995 ; Barrett and Mortensen, 1996] . A n interactive real-time border detection method called the live wire and/or intelligent 8ci.�8ors combines automated border detection with manual definition of the boundary start point and interactive positioning of the end point. In dynamic programming, the graph that is searched is always completely constructed at the beginning of the search process; therefore, interactive positioning of the end point invokes no time-consuming reereation of the graph as would be the case in heuristie graph searching (Section 6.2.4). Thus, after eonstruction of the eornplete graph and associated node eosts, optimal borders eonneeting the fixed start point and the interaetivdy ehanging end point ean be determined in real time. In the case of large or more eomplicated regions, the complete region border is usually constructed from several border segments. After definition of the initial start point, the operator interactively steers the end point so that the calculated optimal border is visually correct. If the operator is satisfied with the eurrent border, and if further movement of the end point causes the border to diverge from the desired location, the end point is fixed and becomes a new start point for the next border segment detection. A new complete graph is calculated and the operator interactively defines the next end point. In many cases, a dosed region eontour ean be formed from just two segments. While the border detection in response to the interactive modifieation of the end point is very fast, the initial construetion of a eomplete graph needed for eaeh optimal border segment seareh is computationally demanding, sinee the graph is of the size of the entire image. Clearly, substantial eomputational power is needed for real-time performance. To overcome the computational needs of the live wire method, a modifieation ealled the live lane was developed [Falcao et a1. , 1995] . In this approach, an operator defines a region of interest by approximately tracing the border by moving a square window. The size of the window is either pre-selected or is adaptively defined from the speed and acceleration of the manual tracing. When the border is of high quality, the manual tracing is fast and the live lane method is essentially identical to the live wire method applied to a sequence of rectangular windows. If the border is less obvious, manual tracing is usually slower and the window size adaptively decreases. If the window size reduces to a single pixel, the method degencrates to manual tracing. A flexible method results that combines the speed of automated border detection with the robustness of manual border detection whenever needed. Sincc the graph is constructed using an image portion comparable in size to the size of the moving window, the computational demands of the live lane method are much less than those of the live wire method.
212
Chapter 6: Segmentation I
Several additional features of the two live methods are worth mentioning. As was stressed earlier, design of border-detection cost functions often requires substantial expe rience and experimentation. To facilitate the method 's use by non-experts, an automated approach has been developed that determines optimal border features from examples of the correct borders. Another automated step is available to specify optimal parameters of cost transforms to create a powerful cost function (Section 6.2.4). Consequently, the resultant optimal cost function is specifically designed for a particular application and can be conveniently obtained by presenting a small number of example border segments during the method 's training stage. Additionally, the method can easily be applied to three-dimensional image data by incorporation of a cost element comparing the border positions in adjacent image slices.
6. 2 .6
Hough transforms
If an image consists of objects with known shape and size, segmentation can be viewed as a problem of finding this object within an image. Typical tasks are to locate circular pads in printed circuit boards, or to find objects of specific shapes in aerial or satellite data, etc. One of many possible ways to solve these problems is to move a mask with an appropriate shape and size along the image and look for correlation between the image and the mask, as discussed in Section 6.4. Unfortunately, the specified mask often differs too much from the object's representation in the processed data, because of shape distortions, rotation, zoom, etc. One very effective method that can solve this problem is the Hough transform, which can even be used successfully in segmentation of overlapping or semi-occluded objects. To introduce the main concepts of the Hough transform, consider an example of circle detection. Let the task be to detect a dark circle of a known radius r in an image with a uniform bright background (shown in Figure 6.32a). The method starts with a search for dark image pixels; after such a pixel is found, a locus of potential center points of the circle associated with it can be determined. Such a locus of potential center points forms a circle with the radius yo as demonstrated in Figure 6.32b. If the loci of potential circle centers are constructed for all dark pixels identified in the original image, the frequency can be determined with which each pixel of the image space occurs as an element of the circle-center loci. As seen from Figure 6.32c, the true center of the circle being sought is represented by the pixel with the highest frequency of occurrence in the circle-center loci . Thus, the center of the searched circle is determined. With the known circle radius, the image segmentation is complete. Figure 6.32d presents intuitive proof that the Hough transform can be successfully applied to images with incomplete information about the searched objects (a circle in our case) and/or in the presence of additional structures and noise. The remainder of this section describes the Hough transform methodology in detail. The original Hough transform was designed to detect straight lines and curves [Hough, 1962] , and this original method can be used if analytic equations of object borderlines are known-no prior knowledge of region position is necessary. A big advantage of this approach is robustness of segmentation results; that is, segmentation is not too sensitive to imperfect data or noise. Nevertheless, it is often impossible to get analytic expressions describing borders. Later, a generalized Hough transform will be described that can find objects even if an analytic expression of the border is not known.
6.2 Edge-based segmentation
(.)
(b)
(0)
(d)
213
Figure 6.32: Hough transform----examp]c of circle detection. (a) Original image of a dark circle (known radius r) on a bright background. (b) For each dark pixel , a potential circle-center
locus ill defined by a circle with radius T and c(mter at that pixel . (e) The frequency with which image pixels occllr in the circlc-ceuter loci is determined-the highest.-frequency pixel represents the center of the circle (marked by .). (d) The Hough tran.�form correctly detects the circle (marked by .) in the presence of incomplete circle information and overlapping structures. (See Figure 6.37 for a real-life example . )
The basic idea of the method can be seen from the simple problem of detecting a straight line in an image [Duda and Hart, 1972]. A straight line is defined by two points A (Xl, vd and D (X2, Y2) (shown in Figure 6.33a) . All straight lines going through the point A are given by the expression Yl = kXt + q for some values of k and q. This means that the same equation can bt: interpreted as an equation in the parameter space k, qj all the straight lines going through the point A are then represented by the equation q = -xlk + YI (see Figure 6.33b). Straight lines going through the point B can likewise be represented as q -X2k + Y2. The only common point of both straight lines in the k,q parameter space is the point which in the original image space represents the only existing 8traight line connecting points A and B. This means that any straight line in the image is represenk-d by a 8ingle poin t in the k, q parameter space and any part of this straight line is transformed into the same point. The main idea of line detection is to determine all the possible line pixels in the image, to transform all lines that can go through these pixels into corresponding point8 in the =
=
=
Chapter 6: Segmentation I
214 y
y
= kx + q
q
c
l q
x (a) Figure 6.33:
k
l
k
(b)
Hough transform principles. (a) Image space. (b) k, q parameter space.
parameter space, and to detect the points (a , b) in the parameter space that frequently resulted from the Hough transform of lines y = a:r + b in the image. These main steps will be described in more detail. Detection of all possible line pixels in the image may be achieved by applying an edge detector to the image; then, all pixels with edge magnitude exceeding some threshold can be considered possible line pixels ( referred to as edge pixels below ) . In the most general case, nothing is known about lines in the image, and therefore lines of any direction may go through any of the edge pixels. In reality, the number of these lines is infinite; however, for practical purposes, only a limited number of line directions may be considered. The possible directions of lines define a discretization of the parameter k. Similarly, the parameter q is sampled into a limited number of values. The parameter space is not continuous any more, but rather is represented by a rectangular structure of cells. This array of cells is called the accumulator array A, whose elements are accumulator cells A(k, q) . For each edge pixel, parameters k, q are determined which represent lines of allowed directions going through this pixel. For each such line, the values of line parameters k, q are used to increase the value of the accumulator cell A(k, q). Clearly, if a line represented by an eqnation y = a:r + b is present in the image, the value of the accumulator cell A (a , b) will be increased many times-as many times as the line y = a:r + b is detected as a line possibly going through any of the edge pixels. For any pixel P, lines going through it may have any direction k ( from the set of allowed directions ) , but the second parameter q is constrained by the image co-ordinates of the pixel P and the direction k. Therefore, lines existing in the image will cause large values of the appropriate accumulator cells in the image, while other lines possibly going through edge pixels, which do not correspond to lines existiug in the image, have different k, q parameters for each edge pixel, and therefore the corresponding accumulator cells are increased only rarely. In other words, lines existing in the image may be detected as high-valued accumulator cells in the accumulator array, and the parameters of the detected line are specified by the accumulator array co-ordinates. As a result, line detection in the image is transformed to detection of local maxima in the accumulator space. It has been noted that an important property of the Hough transform is its insensitivity to missing parts of lines, to image noise, and to other non-line structures co-existing in the image. Insensitivity to data imprecision and noise can be seen in Figure 6.34. This is caused by the robustness of transformation from the image space into the accumulator
6.2 Edge-based segmentation
(a)
(b)
(0)
(d)
215
Figure 6.34: Hough transform-line detection. (a) Original image. (b) Edge image (note many edges, which do not belong to the line). (c) Parameter space. (d) Detected lines.
space-a missing part of the line will cause only a lower local maximum because a smaller munber of edge pixels contributes to the corresponding accumulator celL A noisy or only approximately straight line will not be transformed into a point in the parameter
space, hut
rather will result in a cluster of points, and the cluster center of gravity can be
considered the straight line representation. Note that the parametric equation of the line y
=-
kx + q si appropriate only for
explanation of the Hough transform principles-it causes difficulties in vertical line detection
(k
-+
represented as
00
)
and in non-linear discretization of the parameter
s = x cos(J + ysin (J ,
k.
If a line is
(6.25)
the Hough transform does not suffer from these limitations. Again, the straight line is transformed
to
segmentation of an Figure
6.36.
a single point (see Figure
6.35). A practical example showing the MR image of the brain into the left and right hemispheres is given in
Chapter
216
6:
Segmentation I
B
y
•
s
e x
(aj
s
5
(bj
Figure 6.35: Hough �ransform in s,() space. (a) Straight line in image space. (b) s,{J parameter space. Discretization of the parameter �pace is an important part of this approach [Yuen and Hlavac, 1991]; also, detecting the local maxima in the accumulator array is a non�trivia1 problem. In reality, the resulting di.!;Crcte parameter space usually has more than one local maximum per line existing in the image, and smoothing the discrete parameter space may be a solution. All these remarks remain valid if more complex curves are sought in the image using the HOllgh transform, the only difference being the dimensionality of the accllmulator array. Generalization to more complex curves that can he described by all analytic equation
is straightforward. Consider an arbitrary curve represented by an equation f(x, a) = 0, where
a
is the vector of curve parameters.
(.j
(bj
Figure 6.36: Hough transform line detection used for MRJ brain segmentation to the left and right hemispheres. (a) Edge image. (b) Segmentation line in original image data.
6.2 Edge-based segmentation
217
Algorithm 6.14: Curve detection using the Hough transform 1. Quantize parameter space within the limits of parameters a. The dimensionality n of the parameter space is given by the number of parameters of the vector a. 2. Form an n-dimensional accumulator array A(a) with structure matching the quantization of parameter space; set all elements to zero. 3. For each image point ( X l , X2 ) in the appropriately thresholded gradient image, increase all accumulator cells A(a) if f (x, a) = 0 A(a) = A (a) + �A
for all a inside the limits used in step 1 . 4 . Local maxima i n the accumulator array A(a) correspond t o realizations of curves f(x, a) that are present in the original image.
If we are looking for circles, the analytic expression f (x, a) of the desired curve is
(6.26) where the eircle has center ( a, b) and radius r . Therefore, the accumulator data structure must be three-dimensional. For each pixel x whose edge magnitude exceeds a given threshold, all accumulator cells corresponding to potential circle centers ( a, b) are incre mented in step 3 of the given algorithm. The accumulator cell A( a , b, r ) is incremented if the point ( a, b) is at distance r from point x, and this condition is valid for all triplets ( a, b, r ) satisfying equation (6.26). If Home potential center ( a , b) of a circle of radius r is frequently found in the parameter space, it is highly probable that a circle with radius 7" and center ( a, b) really exists in the processed data. The procesHing results in a set of parameters of desired curves f(x, a) = 0 that correspond to local maxima of accumulator cells in the parameter space; these maxima best match the desired curves and processed data. Parameters may represent unbounded analytic curves (e.g., line, ellipse, parabola, etc.) , but to look for finite parts of these curves, the end points must be explicitly defined and other conditions must be incorporated into the algorithm. Even though the Hough transform is a very powerful technique for curve detection, expollential growth of the accumulator data structure with the increase of the number of curve parameters restricts its practical usability to curves with few parameters. If prior information about edge directions is used, computational demands can be decreased significantly. Consider the case of searching the circular boundary of a dark region, letting the circle have a constant radius r = R for simplicity. Without using edge direction information, all accumulator cells A(a, b) are incremented in the parameter space if the corresponding point ( a, b) is on a circle with center x. With knowledge of direction, only a small number of the accumulator cells lleed be incremented. For example, if edge directions are quantized into eight possible values, only one-eighth of the circle need take part in incrementing of accumulator cells. Of course, estimates of edge direction are unlikely to be precise -if we anticipate edge direction errors of 7f / 4, three-eighths of the circle will require accumulator cell incrementing. Using edge directions, candidates
218
Chapter 6: Segmentation J
for parameters a Il.nd b can be identified from the following formulae: x, - Roos (.,(x)) , b � ", - Rs;n (.,(xl) ,
a �
.,(x) E [¢(x) - 11¢, ¢(x) + MJ '
(6.27)
where .p(x) refers to the edge direction in pixel x and iJ..p is the maximum anticipated edge direction error. Accumulator cells in the parameter space are then incremented only if (a, b) satisfy equation (6.27). Another heuristic that has a beneficial influence on the curve search is to weight the contributions to accumulator cells A(a) by the edge magnitude in pixel x; thus the increment �A in step 3 of Algorithm 6.14 [A(a) = A{a) + �Al will be greater if it results from the processing of a pixel with larger edge magnitude. Figure 6.37 demonstrates circle detection when circular objects of known radius overlap and the image contains many additional structures causing the edge image to be very noisy. Note that the parameter space with three local maxima corresponding to centers of three circular objects.
(.)
(0)
(e)
(d)
Figure 6.37: Hough transform-cirde detection. (a) Original image. (b) Edge image (note that the edge information is far from perfect). (c) Parameter space. (d) Detected circles.
6.2 Edge-based segmentation
219
The randomized Hough transform offers a different approach to achieve increased ciency [Xu and Oja, 1993] ; it randomly selects n pixels from the edge image and deter effi n parameters of the detected curve followed by incrementing a single accumulator nes mi only. Extensions to the randomized Hough transform use local information about the l cel edge image and apply the Hough transform process to a neighborhood of the edge pixel [Kalviainen et al., 1 995] . If the parametric representations of the desired curves or region borders are known, this method works very well, but unfortunately this is not often the case. The desired region borders can rarely be described using a parametric boundary curve with a small number of parameters; in this case, a generalized Hough transform [Ballard, 1981; Davis, 1982; Illingworth and Kittler, 1 987] can offer the solution. This method constructs a parametric curve ( region border) description based on sample situations detected in the learning stage. Assume that shape, size, and rotation of the desired region are known. A reference point xR is chosen at any location inside the sample region, then an arbitrary line can be constructed starting at this reference point aiming in the direction of the region border (see Figure 6.38) . The border direction ( edge direction) is found at the intersection of the line and the region border. A reference table (referred to as the R-table in [Ballard, 1 981]) is constructed, and intersection parameters are stored as a function of the border direction at the intersection point; using different lines aimed from the reference point, all the distances of the reference point to region borders and the border directions at the intersections can be found. The resulting table can be ordered according to the border directions at the intersection points. As Figure 6.38 makes clear, different points x of the region border can have the same border direction, cP(x) = cP(x'). This implies that there may be more than one (r, a) pair for each cP that can determine the co-ordinates of a potential reference point. X
2
X
Figure 6.38:
J
Principles of the generalized Hough transform: geometry of R-table construction.
An example of an R-table is given in Table 6 . 1 . Assuming no rotation and known size, remaining description parameters required are the co-ordinates of the reference point (xf , xf) . If size and rotation of the region may vary, the number of parameters increases to four. Each pixel x with a significant edge in the direction cP(x) has co-ordinates of potential reference points {X l + r(cP) cos (a(cP)) , x 2 + r(cP) sin (a(cP))). These must be computed for all possible values of r and a according to the border direction cP(x) given in the R-table. The following algorithm presents the generalized Hough transform in the most general of cases in which rotation ( r ) and size (S) may both change. If either there is no change in rotation ( r = 0) , or there is no size change (S = 1 ) , the resulting accumulator data structure A is simpler.
220
Chapter 6: Segmentation
I
( r } , a D , ('f'?, o:n, . . , ( r?' , a?' ) ( r� , (x�), (r�, (xD, . . . , ( r�2 , a�2 ) ( r� , (x §) , ( r§ , a§ ) , . . . , ( r�" , a�3 )
¢l ¢2 ¢3
.
Table 6 . 1 : R-table
Algorithm 6.15: Generalized Hough transform
1. Construct an R-table description of the desired object. 2. Form a data structure A that represents the potential reference points
Set all accumulator cell values A(Xl , X 2 , S, T) to zero. 3. For each pixel (X l , X 2 ) in a thresholded gradient image, determine the edge direction cp(x); find all potential reference points xR and increase all
for all possible values of rotation and size change xf
= Xl + r ( ¢ + T ) S cos ( a ( ¢ + T )) , x� = X 2 + r ( ¢ + T ) S sin ( a ( ¢ + T )) . 4. The location of suitable regions is given by local maxima in the A data structure.
The Hough transform was initially developed to detect analytically defined shapes, such as lines, circles, or ellipses in general images, and the generalized Hough transform can be used to detect arbitrary shapes. However, even the generalized Hough transform requires the complete specification of the exact shape of the target object to achieve precise segmentation. Therefore, it allows detection of objects with complex but pre-determined, shapes. Other varieties exist that allow detection of objects whose exact shape is unknown, assuming a priori knowledge can be used to form an approximate model of the object. The Hough transform has many desirable features [Illingworth and Kittler, 1988] . It recognizes partial or slightly deformed shapes, therefore behaving extremely well in recognition of occluded objects. It may be also used to measure similarity between a model and a detected object on the basis of size and spatial location of peaks in the parameter space. The Hough transform is very robust in the presence of additional structures in the image (other lines, curves , or objects) as well as being insensitive to image noise. Moreover, it may search for several occurrences of a shape during the same processing pass. Unfortunately, the conventional sequential approach requires a lot of storage and extensive computation. However, its inherent parallel character gives the potential for real-time implementations.
6.2 Edge-based segmentation
221
Many serious implementational problems were only touched upon here (shape param eterization, accumulation in parameter space, peak detection in parameter space, etc.). Details are discussed in surveys [Illingworth and Kittler, 1988; Princen et al., 1994] , where extensive lists of references may also be found. Because of the large time requirements in the sequential version, effort has been devoted to hierarchical approaches [Neveu, 1986; Princen et al. , 1989] ; fast algorithms were developed [Quil et al., 1995]; gray-scale Hough transforms working directly in image data were presented in [Lo and Tsai, 1995] ; methods combining the Hough transform and automated line tracing were studied [Wang and Howarth, 1989; Lerner and Morelli, 1990] , and many parallel implementations were tested [Oyster, 1987; Olariu et a1. , 1993; Chung and Lin, 1995J. The unique properties of the Hough transform also provoke more and more applications [Illingworth and Kittler, 1988; McKenzie and Protheroe, 1 990; Brummer, 1991]. Features of many existing varieties of the Hough transform, together with performance comparisons, are given in [Kalviainen et a1. , 1 995] .
6.2.7
Border detection using border location information
If any information about boundary location or shape is known, it is of benefit to use it. The information may, for instance, be based on some higher-level knowledge, or can result from segmentation applied to a lower-resolution image. One possibility is to determine a boundary in an image as the location of significant edges positioned close to an assumed border if the edge directions of these significant edges match the assumed boundary direction. The new border pixels are sought in directions perpendicular to the assumed border (see Figure 6.39). If a large number of border elements satisfying the given conditions is found, an approximate curve is computed based on these pixels, and a new, more accurate, border results.
Figure 6.39:
A priori information about boundary location.
Another possibility is based on prior knowledge of end points-this approach assumes low image noise and relatively straight boundaries. The process iteratively partitions the border and searches for the strongest edge located on perpendiculars to the line connecting end points of each partition; perpendiculars are located at the center of the connecting straight line--see Figure 6.40. The strongest significant edge located on the perpendicular that is close to the straight line connecting the end points of the current partition is accepted as a new border element. The iteration process is then repeated. Another approach to contour detection has been introduced in [Kass et a1. , 1987] in which active contour models (snakes) start their search for a contour taking advantage of user-provided knowledge about approximate position and shape of the required contour.
222
Chapter 6: Segmentation
I
3
Exact border
l
\
/
2
/
'
/ / / - - - - - ,
'
'
,
,
,
4
B
Divide-and-conquer iterative border detection; numbers show the sequence of
Figure 6.40:
division steps.
An optimization method refines the starting contour estimate and matches the desired contour. This approach is discussed in Section 7.2.
6. 2 . 8
Region construction from borders
All methods considered hitherto have focused on the detection of borders that partially or completely segmented the processed image. If a complete segmentation is achieved, the borders segment an image into regions; but if only a partial segmentation results, regions are not defined uniquely and region determination from borders may be a very complex task requiring cooperation with higher-level knowledge. However, methods exist that are able to construct regions from partial borders which do not form closed boundaries. These methods do not always find acceptable regions, but they are useful in many practical situations. One of them is the superslice method [Milgram, 1979] , which is applicable if regions have dominant gray-level properties. The approach assumes that some border-part locations are known in the image; the image data is then thresholded using different thresholds. Regions resulting from the thresholding for which the detected boundaries best coincide with assumed boundary segments are then accepted as correct. Better results can be obtained by applying a method described in [Hong et al., 1980] based on the existence of partial borders in the processed image. Region construction is based on probabilities that pixels are located inside a region closed by the partial borders. The border pixels are described by their positions and by pixel edge directions ¢(x). The closest 'opposite ' edge pixel is sought along a perpendicular to each Significant image edge, and then closed borders are constructed from pairs of opposite edge pixels. A pixel is a potential region member if it is on a straight line connecting two opposite edge pixels. The final decision on which of the potential region pixels will form a region is probabilistic.
Algorithm
Region forming from partial borders 1. For each border pixel x, search for an opposite edge pixel within a distance not 6.16:
exceeding a given maximum M. If an opposite edge pixel is not found, process the next border pixel in the image. If an opposite edge pixel is found, mark each pixel on the connecting straight line as a potential region member.
6.3 Region-based segmentation
223
2. Compute the number of markers for each pixel in the image (the number of markers tells how often a pixel was on a connecting line between opposite edge pixels). Let be the number of markers for the pixel is then determined as follows: 3. The weighted number of markers
b(x)
B(x)
x
B(x)
= 0.0 = 0. 1 = 0.2 = 0.5 = 1.0
x.
for for for for for
x. x
b(x) 0 , b(x) 1 , b(x) 2 , b(x) = 3 , b(x) > 3 . =
=
(6.28)
=
x
B(Xi)
The confidence that a pixel is a member of a region is given as the sum 2.: i in a 3 x 3 neighborhood of the pixel If the confidence that a pixel is a region member is one or larger, then pixel is marked as a region pixel, otherwise it is marked as a background pixel.
Note that this method allows the construction of bright regions on a dark background as well as dark regions on a bright background by taking either of the two options in the search for opposite edge pixels -step 1 . Search orientation depends on whether relatively dark or bright regions are constructed. If and are directions of edges, the condition that must be satisfied for and to be opposite is
¢(x) ¢(y) x y % < !(¢(x) - ¢(y) ) mod (27r) I < 3; .
(6.29)
Note that it is possible to take advantage of prior knowledge of maximum region sizes-this information defines the value of !vI in step 1 of the algorithm, the maximum search length for the opposite edge pixel. This method was applied to form texture primitives (Chapter 15 [Hong et al., 1980]) as shown in Figure 6.41. The differences between the results of this region detection method and those obtained by thresholding applied to the same data are clearly visible if Figures 6.41b and 6.41c are compared.
6.3
Region-based segmentation
The aim of the segmentation methods described in the previous section was to find borders between regions; the following methods construct regionH directly. It is easy to construct regions from their borders, and it is easy to detect borders of existing regions. However, segmentations resulting from edge-based methods and region-growing methods are not usually exactly the same, and a combination of results may often be a good idea. Region growing techniques are generally better in noisy images, where borders are extremely difficult to detect. Homogeneity is an important property of regions and is used as the main segmentation criterion in region growing, whose basic idea is to divide an image into zones of maximum homogeneity. The criteria for homogeneity can be based on gray-level, color, texture, shape, model (using semantic information) , etc. Properties
224
Chapter 6: Segmentation I
1' • .... ·
.. .- ") -
. ..
. .. � ,."
. .
.
-
.,.
.... .. ," " ..,.
-
,
..
, .
,.
",
,
.
..
.
.
(hi
(-I
· • ••.� .. ....,. . r • •·' ·
�t .. . oo. ,. �·tt.
"... .
(e)
--, _ __ .,. -. ••.
..�" '..0 ' .� ... .•. �
." ." .
... . _
. .. ... . ...-
•
..._
.
·
....... .. ...� .
�'� .... =.fl� • • .,J
•
.. .. (0)
Figure 6.41: Region forming from partial borders. (a) Original image. (b) Thresholding. (e) Edge image. (d) Regions formed frolll partial bordenl. chosen to describe rcgions influence the form, complexity, and amount of prior information in the specific region-growing segmentation method. Methods that !:ipedfically address
region-growing !:icgmentation of color images are reported in [Schettini,
1993; Vlachos and 19931. Regions have already been dcfinl.-d. in Chapter 2 and disclISS(.-d. in Section 6.1, where
Constantinides, equation
(6.1)
1993;
Gauch and Hsia,
1992;
Priese and Rehrmann,
stated the basic requirements of segmentation into regions.
Further
assUlnptions needed in this section are that regions must satisfy the following conditions: .
H(ll;) � TRUE , i � 1 , 2 , . . , 8 , H(� U R;} ::o= FALSE , i i= j , R; adjacent to Rj ,
(6.30) (6.31)
S is the total number of regions in an image and H(R,) is a binary homogeneity
evaluation of the region n.. Resulting regiolls of the segmented image must be both
where
homogeneous and maximal, where by 'maximal' we wean that the homogeneity criterion
would not be true after merging a regioll with any adjacent region. Wc will discuss simplcr versions of region growing first, that is, the merging, splitting, and split-and-merge approaches, and will discuss the possible gains from using semantic
information later, in Chapter lO. Of especial interest are the homogeneity criteria, whose
6.3 Region-based segmentation
225
choice is the most important factor affecting the methods mentioned; general and specific heuristics may also be incorporated. The simplest homogeneity criterion uses an average gray-level of the region, its color properties, simple texture properties, or an m-dimensional vector of average gray values for multi-spectral images. While the region growing methods discussed below deal with two-dimensional images, three-dimensional implementations are often possible. Considering three-dimensional connectivity constraints, homogeneous regions (volumes) of a three-dimensional image can be determined using three-dimensional region growing. Three-dimensional filling represents its simplest form and can be described as a three-dimensional connectivity-preserving variant of thresholding.
6.3.1
Region merging
The most natural method of region growing is to begin the growth in the raw image data, each pixel representing a single region. These regions almost certainly do not satisfy the condition of equation (6.3 1 ) , and so regions will be merged as long as equation (6.30) remains satisfied.
Algorithm 6. 17: Region merging (outline) 1. Define some starting method to segment the image into many small regions satisfying condition (6.30). 2. Define a criterion for merging two adjacent regions. 3. Merge all adjacent regions satisfying the merging criterion. If no two regions can be merged maintaining condition (6.30 ) , stop. This algorithm represents a general approach to region merging segmentation. Specific methods differ in the definition of the starting segmentation and in the criterion for merging. In the descriptions that follow, regions are those parts of the image that can be sequentially merged into larger regions satisfying equations (6.30) and (6.31). The result of region merging usually depends on the order in which regions are merged, meaning that segmentation results will probably differ if segmentation begins, for instance, in the upper left or lower right corner. This is because the merging order can cause two similar adjacent regions RI and R2 not to be merged, since an earlier merge used R I and its new characteristics no longer allow it to be merged with region R2 . If the merging process used a different order, this merge may have been realilled. The simplest methods begin merging by starting the segmentation using regions of 2 x 2, 4 x 4, or 8 x 8 pixels. Region descriptions are then based on their statistical gray-level properties- a regional gray-level histogram is a good example. A region description is compared with the description of an adjacent region; if they match, they are merged into a larger region and a new region description is computed. Otherwise, regions are marked as non-matching. Merging of adjacent regions continues between all neighbors, including newly formed ones. If a region cannot be merged with any of its neighbors, it is marked 'final ' ; the merging process stops when all image regions arc so marked. State space search is one of the essential principles of problem solving in AI, whose application to image segmentation was first published in [Brice and Fennema, 1 970] . According to this approach, pixels of the raw image are considered the starting state,
226
Chapter 6: Segmentation I .
0
O x
•
0
O x
.
0
o x
Figure 6.42:
. 0 • 0 . 0
0 X 0 X 0 X
• 0 • 0 • 0
0 X 0 X 0 X
.
0
.
0
•
0
.
0
.
0
•
0
X
0
X
0
X
0
X
0
X
0
X
0
•
0
•
0
•
0
•
0
X
0
X
0
X
0
X
0
X
•
0
•
0
•
0
•
0
•
0
0
X
0
X
0
X
0
X
0
X
0
data;
0,
0 • 0
Supergrid data structure:
x ,image
. 0 •
0 X 0 X
• 0 . 0 • 0
0 X 0 X 0 X
•
0
•
0
•
0
o x
o x
o x
crack edges; ., unused.
each pixel being a separate region. A change of state can result from the merging of two regions or the splitting of a region into sub-regions. The problem can be described as looking for permissible changes of state while producing the best image segmentation. This state space approach brings two advantages; first, well-known methods of state space search can be applied which also include heuristic knowledge; second, higher-level data structures can be used which allow the possibility of working directly with regions and their borders, and no longer require the marking of each image element according to its region marking. Starting regions are formed by pixels of the same gray-Ievel -these starting regions are small in real images. The first state changes are based on crack edge computations (Section 2.3. 1), where local boundaries between regions are evaluated by the strength of crack edges along their common border. The data structure used in this approach (the so-called supergrid) carries all the necessary information (see Figure 6.42) ; this allows for easy region merging in 4-adjacency when crack edge values are stored in the ' 0 ' elements. Region merging uses the following two heuristics . •
•
Two adjacent regions are merged if a significant part of their common boundary consists of weak edges (significance can be based on the region 'vith the shorter perimeter; the ratio of the number of weak common edges to the total length of the region perimeter may be used). Two adjacent regions are also merged if a significant part of their common boundary consists of weak edges, but in this case not considering the total length of the region borders.
Of the two given heuristics, the first is more general and the second cannot be used alone because it does not consider the influence of different region sizes. Edge significance can be evaluated according to the formula Vij
= 0 if 8ij < Tl 1 otherwise,
,
(6.32)
=
where Vij = 1 indicates a significant edge, Vij = 0 a weak edge, Tl is a preset threshold, and S ij is the crack edge value 8ij = I f(xd - f(Xj ) l .
Algorithm 6.18: Region merging via boundary melting 1. Define a starting image segmentation into regions of constant gray-level. Construct a supergrid edge data structure in which to store the crack edge information. 2. Remove all weak crack edges from the edge data structure (using equation (6.32) and threshold T1 ) .
6.3 Region-based segmentation
3. Recursively remove common boundaries of adjacent regions R ,
227
Rj , if
where W is the number of weak edges on the common boundary, li, lj are the perimeter lengths of regions Ri, Rj , and T2 is another preset threshold. 4. Recursively remove common boundaries of adjacent regions Ri, Rj if W > T3
1 -
(6.33)
or, using a weaker criterion [Ballard and Brown, 1982] (6.34) where 1 is the length of the common boundary and T3 is a third threshold.
Note that even if we have described a region growing method, the merging criterion is based on border properties and so the merging does not necessarily keep condition (6.30) true. The supergrid data structure allows precise work with edges and borders, but a big disadvantage of this data structure is that it is not suitable for the representation of regions- it is necessary to refer to each region as a part of the image, especially if semantic information about regions and neighboring regions is included. This problem can be solved by the construction and updating of a data structure describing region adjacencies and their boundaries, and for this purpose a good data structure to use can be a planar-region adjacency graph and a dual-region boundary graph [Pavlidis, 1977] , (see Section 10.8) . Figure 6.43 gives a comparison of region merging methods. An original image and its pseudo-color representation (to see the small gray-level differences) are given in Figures 6.43a,b. The original image cannot be segmented by thresholding because of the significant and continuous gray-level gradient in all regions. Results of a recursive region merging method, which uses a simple merging criterion that allows pixels to be merged in the row-first fashion as long as they do not differ by more than a pre-specified parameter from the seed pixel is shown in Figure 6 .43c; note the resulting horizontally elongated regions corresponding to vertical changes of image gray-levels. If region merging via boundary melting is applied, the segmentation results improve dramatically; see Figure 6.43d.
6.3.2
Region splitting
Region splitting is the opposite of region merging, and begins with the whole image represented as a single region which does not usually satisfy condition (6.30) . Therefore, the existing image regions are sequentially split to satisfy (6.1), (6.30) and (6.31 ). Even if this approach seems to be dual to region merging, region splitting does not result in the same segmentation even if the same homogeneity criteria are used. Some regions may be homogeneous during the splitting process and therefore are not split any more;
228
Chapter 6: Segmentation
I
(0)
(b)
(d) Figure 6.43: Region m(:rging segmentation. (3) Original image. (b) Pseudo-color representation of the original image (in grayscale). (c) Recursive region merging. (d) Region merging via boundary mclting. CmJ.rte$Y of R. Marik, Cuch Technical Univer.,ity.
cOllsidering the homogeneous regions created by region merging procedures, some may not be constructed because of the impossibility of merging smaller sub-regions earlier ill the process. A fine hlack-a.nd-white chessboa.rd is an example: Let a homogeneity criterion be b&;cd on variance of average gray-levels in the quadrants of the evaluated region in the next lower pyramid level -if the segmentatioll process is based on region splitting, the image will not be split into sub-regions because its quadrants would have the same value of the measure as the starting region consisting of the whole image. The region
llIergiug approach, on the other hand, begins with merging single pixel regions into larger regions, and this process will stop when regions match the chessboard squares. Thus, if splittillg is applied, the whole image will be considered one region; whereas if merging is applied, a dlessboard will be segmented into squares as shown in Figme
6.44.
In this
particulru: case, consideriug gray-level vnriauce within the entire region as a measure of region homogeneity, and not considering the variance of quadrants only, would also solve the problem. However, region merging and region splitting are not dual. Region splitting methods generally usc similar criteri a of homogeneity as region merging methods, and differ olily in the direction of their application. The multi-spectral segmentation discussed in considering thresholding (Section
6.1.3)
can be seen as
an
example of a region splitting method. As mentioned there, other criteria. can be used to split regions (e.g., cluster analysis, pixel cla'>sification, etc. ) .
6.3 Region-based segmentation
229
(0)
(b)
Figure 6.44: Different scglTIentatioIls may result. from region splitting and region merging approaches. (a) Chessboard image, corresponding pyramid. (b) Region splitting segmenta.tion
(upper pyramid level is homog(meous, no splitting possible). (c) Region merging segmentation (lowest pyramid level consists of regions that cannot he merged). 6.3.3
Splitting and merging
A combination of splitting and merging may result in a method with the advantages of both approaches. Split-and-merge approaches work using pyramid image representatiolls; regions are square shaped and correspond to elements of the appropriate pyramid level.
Splitting
!�
;;: r
z /,L-Z -r---Z 7
Figure
6.45: Split-and-merge ill
Merging
a hierarchical data structure.
If any region in any pyramid level is not homogeneous (excluding the lowest level), it is split into four sub-regions-these are elements of higher resolution at the level below. If four regions exist at any pyramid level with approximately the same value of homogeneity measure, they are merged into a single region ill an upper pyramid level ($€e Figure 6.45). The segmentation proeess can be understood as the construction of a segmentation quadtree where each leaf node represents a homogeneous region--that is, an element of some pyramid level. Splitting and merging corresponds to removing or building parts of the segmentation quacitree-t.he number of leaf nodes of the tree corresponds to the number of segmented regions after the segmentation proeess is over. These approaches are sometimes called split-and-link met.hodti if they use segmentation trees for storing information about adjacent regions. Split-and-merge methods usually store the adjacency information in region adjacency graphs (or similar data structures). Using segmentation trees, in which regions do not have to be contiguous, is both implementationally and computationally easier. An unpleasallt drawback of segmentation quadtrees is the square region shape assumption (see Figure 6.46), and it is therefore advantageous to add more processing steps that permit the merging of regions which are not part of the same branch of the segmentatioll t.ree. Starting image regions can either be chosen arbitrarily 01' can be based on priot' knowledge. Because both split-and-merge processing options are available, the st.arting segmentation does not have to satisfy either condition (6.30) 01' (6.31).
Chapter 6: Segmentation I
230
01
00
1
V 310
03
02
30
32
I- 3 1 3
,
2 33
2
00
01
02
33
30
03
310
311
312
313
Figure 6.46: Segmelltal.ion quadtrec.
The homogcneity criterion plil..Ys a major role in 5plit-and-merge algorithms, just it doc> in all at.her rcgion growing met.hods. See [Chen et aI., lOC111 for an adaptive split-and-mergc algorithm and It review of regioll homogeneity analysis. If the image bcing processed is reasonably simple, a split-and-rnerge approach can be based 011 local image properties. If the image is very complex, even elaborate criteria including l;emantic information may Ilot give acceptable results. as
Algorithm 6.19: Split and merge 1.
Define an initial segmentation into regions, a homogeneity criterion, and a pyramid data structure.
2. If any region R in the pyramid data structure is not homogeneous [H(R) = FALSEI, split it into four child-regions; if any four regions with the same parent can be merged into a single homogeneous region, merge them. If no region can be split or merged, go to step 3. 3. If any two adjacent regions R;, Rj (even if they are in different pyramid levels or do not have the same parent) can be merged into a homogeneous region, merge them. 4. Merge small regions with the most similar adjacent region if it is necessary to remove small-size regions.
6.3 Region-based segmentation
231
A pyramid data structure with overlapping regions (Chapter 4) is an interesting modification of this method [Pietikainen et al., 1982] . In this data structure, each region has four potential parent elements in the upper pyramid level and 1 6 possible child elements in the lower pyramid level. Segmentation tree generation begins in the lowest pyramid level. Properties of each region are compared with properties of each of its potential parents and the segmentation branch is linked to the most similar of them. After construction of the tree is complete, all the homogeneity values of all the elements in the pyramid data structure are recomputed to be based on child-region properties only. This recomputed pyramid data structure is used to generate a new segmentation tree, beginning again at the lowest level. The pyramid updating process and new segmentation tree generation is repeated until no significant segmentation changes can be detected between HtepH. Assume that the segmented image has a maximum of 2 n (non-contiguous) regions. Any of these regions must link to at least one element in the highest allowed pyramid level-·let this pyramid level consist of 2 n elements. Each element of the highest pyramid level corresponds to one branch of the segmentation tree, and all the leaf nodes of this branch construct one region of the segmented image. The highest level of the segmentation tree must correspond to the expected number of image regions, and the pyramid height defines the maximum number of segmentation branches. If the number of regions in an image is less than 2 n , some regions can be represented by more than one element in the highest pyramid level. If this is the case, some specific processing steps can either allow merging of some elements in the highest pyramid level or can restrict some of these elements to be segmentation branch rootH. If the number of image regions is larger than 2", the most similar regions will be merged into a single tree branch, and the method will not be able to give acceptable resultH.
Algorithm 6.20: Split and link to the segmentation tree 1. Define a pyramid data structure with overlapping regions. Evaluate the starting region description. 2. Build a segmentation tree starting with leaves. Link each node of the tree to that one of the four possible parents to which it has the most similar region properties. Build the whole segmentation tree. If there is no link to an element in the higher pyramid level, assign the value zero to this element. 3. Update the pyramid data structure; each element must be assigned the average of the values of all its existing children. 4. Repeat steps 2 and 3 until no significant segmentation changes appear between iterations (a small number of iterations is usually sufficient). Considerably lower memory requirements can be found in a single-pass split-and merge segmentation. A local 'splitting pattern ' is detected in each 2 x 2 pixel image block and regions are merged in overlapping blocks of the same size [Suk and Chung, 1 983] . In contrast to previous approaches, a single pass is sufficient here, although a second pass may be necessary for region identification (see Section 8 . 1 ) . The computation is more efficient and the data structure implemented is very simple; the 12 possible splitting patterns for a 2 x 2 block are given in a list, starting with a homogeneous block up to a block consisting of four different pixels (see Figure 6.47) . Pixel similarity can be evaluated
232
Chapter 6: Segmentation I
adaptively according to the mcan and variance of gray-levels of blocks throughout the image.
Algorithm 6.21: Single-pass split-and-merge 1 . Search an entire image line by line except the last column and last line. Perform the following steps for each pixel. 2. Find a splitting pattern for a 2 x 2 pixel block. 3. If a mismatch between assigned labels and splitting patterns in overlapping blocks is found, try to change the assigned labels of these blocks to remove the mismatch (discussed below) . 4. Assign labels to unassigned pixels to match a splitting pattern of the block. 5. Remove small regions if necessary.
EJ EJ EE EB EB EB EB EB EB EB EB EB Figure 6 . 47:
Splitting of 2 x 2 image blocks, all 12 possible cases.
The image blocks overlap during the image search. Except for locations at the image borders, three of the four pixels have been assigned a label in previous search locations, but these labels do not necessarily match the splitting pattern found in the processed block. If a mismatch is detected in step 3 of the algorithm, it is necessary to resolve possibilities of merging regions that were considered separate so far-to assign the same label to two regions previously labeled differently. Two regions R l and R2 are merged into a region R3 if H(Rl u R2 ) = TRUE , (6.35) Irn]
-
rn2 1 < T ,
(6.36)
where rn l and rn 2 are the mean gray-level values in regions R l and R2 , and T is some appropriate threshold. If region merging is not allowed, regions keep their previous labels. To get a final segmentation, information about region merging must be stored and the merged-region characteristics must be updated after each merging operation. The assignment of labels to non-labeled pixels in the processed block is based on the block splitting pattern and on the labels of adjacent regions (step 4) . If a match between a splitting pattern and the assigned labels was found in step 3 , then it is easy to assign a label to the remaining pixel(s) to keep the label assignment and splitting pattern matched. Conversely, if a match was not found in step 3, an unassigned pixel is either merged with an adjacent region (the same label is assigned) or a new region is started. If a 2 x 2 block
6.3 Region-based segmentation
233
size is used, the only applicable pixel property is gray-leveL If larger blocks are used, more complex image properties can be included in the homogeneity criteria (even if these larger blocks are divided into 2 x 2 sub-blocks to determine the splitting pattern) . Many other modifications exist, most o f them trying t o overcome the segmentation sensitivity to the order in which portions of the image are processed. The ideal solution would be to merge only the single most similar pair of adjacent regions in each iteration, which would result in very slow processing. A method performing the best merge within each of sets of local sllbimages (possibly overlapping) is described in [Tilton, 1989] . Another approach insensitive to scanning order is suggested in [Pramotepipop and Cheevasuvit, 1988] . Hierarchical merging where different criteria are employed at different stages of the segmentation process is discussed in [Goldberg and Zhang, 1987] . More and more information is incorporated into the merging criteria in later segmentation phases. A modified split-and-merge algorithm where splitting steps are performed with respect to the edge information and merging is based on gray-value statistics of merged regions is introduced in [Deklerck et aL , 1993] . As splitting is not required to follow a quad tree segmentation pattern, segmentation borders are more natural than borders after the application of standard split-and-merge techniques. Parallel implementations become more and more affordable, and parallel region growing algorithms may be found in [Willebeek-Lemair and Reeves, 1990; Chang and Li, 1995] . Additional sections describing more sophisticated methods of semantic region growing segmentation can be found in Chapter 10.
6.3.4
Watershed segmentation
The concepts of watersheds and catchment basins are well known in topography. Watershed lines divide individual catchment basins. The North American Continental Divide is a textbook example of a watershed line with catchment basins formed by the Atlantic and Pacific Oceans. Working with gradient images and following the concept introduced in Chapter 1 , Figures 1.8 and 1 .9, image data may be interpreted as a topographic surface where the gradient image gray-levels represent altitudes. Thus, region edges correspond to high watersheds and low-gradient region interiors correspond to catchment basins. According to equation (6.30), the goal of region growing segmentation is to create homogeneous regions; in watershed segmentation, catchment basins of the topographic surface are homogeneous in the sense that all pixels belonging to the same catchment basin are connected with the basin's region of minimum altitude (gray-level) by a simple path of pixels (Section 2 .3 1 ) that have monotonically decreasing altitude (gray-level) along the path. Such catchment basins then represent the regions of the segmented image (Figure 6.48) . While the concept of watersheds and catchment basins is quite straightforward, development of algorithms for watershed segmentation is a complex task, with many of the early methods resulting in either slow or inaccurate execution. The first algorithms for watershed segmentation were developed for topographic digital elevation models [Collins, 1975; Soille and Ansoult, 1990] . Most of the existing algorithms start with extraction of potential watershed line pixels using a local 3 x 3 operation, which are then connected into geomorphological networks in subsequent steps. Due to the local character of the first step, these approaches are often inaccurate [Soille and Ansoult, 1990] . .
234
Chapter 6: Segmentation I Watersheds
Catchment basins
•
(a)
(b)
One-dimensional example of watershed segmentation. (a) Gray-level profile of image data. (b) Watershed segmentation-local minima of gray-level (altitude) yield catchment basins, local maxima define the watershed lines. Figure 6.48:
Somewhat independently, watersheds were investigated in digital image processing. The watershed transformation can also be presented in the context of mathematical morphology; details can be found in Chapter 13. Unfortunately, without special hard ware, watershed transformations based on mathematical morphology are computationally demanding and therefore time consuming. There are two basic approaches to watershed image segmentation. The first one starts with finding a downstream path from each pixel of the image to a local minimum of image surface altitude. A catchment basin is then defined as the set of pixels for which their respective downstream paths all end up in the same altitude minimum. While the downstream paths are easy to determine for continuous altitude surfaces by calculating the local gradients, no rules exist to define the downstream paths uniquely for digital surfaces. 'While the given approaches were not efficient because of their extreme computational demands and inaccuracy, the second watershed segmentation approach represented by a seminal paper [Vincent and Soille, 1991] makes the idea practical. This approach is essentially dual to the first one; instead of identifying the downstream paths, the catchment basins fill from the bottom. As was explained earlier, each minimum represents one catchment basin, and the strategy is to start at the altitude minima. Imagine that there is a hole in each local minimum, and that the topographic surface is immersed in water. As a result, the water starts filling all catchment basins, minima of which are under the water level. If two catchment basins would merge as a result of further immersion, a dam is built all the way to the highest surface altitude and the dam represents the watershed line. An efficient algorithm for such watershed segmentation was presented in [Vincent and Soille, 1991]. The algorithm is based on sori'ing the pixc!s in increasing order of their gray values, followed by a flooding step consisting of a fa." t breadth-first scanning of all pixels in the order of their gray-levels. During the sorting step, a brightness histogram is computed (Section 2.3.2). Simul taneously, a list of pointers to pixels of gray-level h is created and associated with each histogram gray-level to enable direct access to all pixels of any gray-level. Information about the image pixel sorting is used extensively in the flooding step. Suppose the Hooding has been completed up to a level (gray-level, altitUde) k. Then every pixel having gray-level less than or equal to k has already been assigned a unique catchment basin label. Next, pixels having gray-level k + 1 must be processed; all such pixeb can be found in the list that was prepared in the sorting step-consequently, all these pixels can be accessed directly. A pixel having gray-level k + 1 may belong to a catchment basin labeled
6.3 Region�based segmentation
235
l if at least one of its neighbors already catTies this label. Pixels that represent potential catchment basin members are put in a first�in firstrout queue and await further processing. Geodesic inftucnce zones are computed for all hitherto determined catchment basins. A geodesic influence zone of a catchment basin li is the locus of non-labeled image pixels of gray�level k + 1 that are contiguous with the catchment b("lSin Ii (contiguous within the region of pixels of gray�level k + 1) for which their distance to li i8 smaller than their distance to any other catchment basin Ij (Figure 6.49). All pixels with gray-level k + 1 that belong to the influence zone of a catchmeut basin labeled I are also labeled with the label I, tbus causing the catchment basin to grow. The pixels from the queue are processed sequentially, and all pixels f!"Om the queue that cuunot be 8&iigned an existing label represent newly discovered catchment basins and are marked with new and unique labels. Pixels of gray level
0
Newly discovered catchment basins
k+1 Geodesic influence zones
Already discovered calchmen! basins
Pixels of higher gray levels
Figure 6.49: Geodesic influence zones of catchment basins.
Fignre 6.50 shows an example of watershed segmentation. Note that the raw watershed segmentation produces a severely oversegmented image with hundreds or thousands of catchment basins (Figure 6.500). To overcome this problem, region markers and other approaches have been suggested to generate good segmentation (Figure 6.5Od) [Meyer and Beucher, 1990; Vincent and Soille, 1991; Higgins mid Ojard, 1993]. While this method would work well in the continuous space with the watershed lines accurately dividing the adjacent cntchment basins, the watersheds in images with large plateaus may be quite thick in discrete spaces. Figure 6.51 illustrates such a situation, consisting of pixels equidistant to two catchment basins in 4�connectivity. To avoid such behavior, detailed rule; using successively ordered distances stored during the breadth-search process were developed that yield exact watershed lines. Full details, and pseudo-code for a fast watershed algorithm, arc in found in [Vincent and Soille, 1991]; the method was found to be hundreds of times faster than several classical algorithms when using a conventional serial computer, is easily extensible to higher·dimensional images (Higgins and Ojard, 1993), and is applicable to square or hexagonal grids. F\.J.rther improvemcnts of the watershed segmentation based on immersion simulations are given in [Dobrin et al., 1994). 6.3.5
Region growing post-processing
Images segmented by region growing methods often contain eit.her too many regions (under�growing) or too few regions (over.growing) as a result of nOIl�optimal parameter
236
Chapter 6: Segmentation I
(b)
« )
(d)
Figure 6.50: Watershed segmentation. (a) Original;. (b) Gradient image, 3 x 3 Sobel edge detection, histogram equalized. (c) Raw watel'shed segmentation. (d) Watershed segmentation using region markers to control oversegmentatioll. COttftesy of W. Higgitul, Penn State University.
setting. To improve classification results, a variety of post-proces.'>Ors has been developed. Some of them combine segment.ation informa.tion obtained from region growing and edge based segmentation. An approach introdnced in [Pavlidis and Liow, 1990J solves several quadtrl.>e-relatcd region growing problcms and incorporates two post-processing steps. First, boundary elimination removes some borders betwl."en adjacent regions according to their contrast propertics and direction changes along the border, taking resulting topology into consideration. Second, contours from the previous step modified to bc located precisely on appropriate image edges. A combination of independent region growing and edge-based detl"Cted borders is described in [Koivuncii and Pietikainen, 1990]. Other .. approaches combining region growing and edge detection can be found ill [Manos et aI., 1993; Gambotto, 1993; Wu, 1993; Chu and Aggarwal, 1993]. Simpler post-processors arc based on general heuristics and decrea.<:>e the number of small regions in the segmented image that cannot be merged with any adjacent region arc
6.4
Matching
237
Figure
�
6.51: Thick watershed lilies may remIt in gray-level plateau!;. Earlier identified catch ment basins are marked as black pixels, and Ilew catchment basin additions resulting from this processing step are shown in the two levels of gray. The thick waten.heds are marked with _. To avoid thick watersheds, specialized rules must be developed.
according to the origillally applied homogeneity criteria. These small regions are usually not significant in further processing and can be considered as segmentation noise. It is possible to remove them from the image a.'i follows. Algorithm 6.22: Removal of small image regions
1. Search for the smallest image region Rmin . 2. Find the adjacent region R most similar to Rmin, according to the homogeneity
criteria used. Merge R and Rmin . 3. Repeat steps 1 and 2 until all regions smaller than a pre-selected size are removed from the image. This algorithm will execute much faster if all regions smaller than a pre-selected size are merged with their neighbors without having to order them by size.
6.4
Matching
Matching is another ba.,>ic approach to segmentation that ean be used to locate known objects in an image, to search for specific patterns, etc. Figure 6.52 shows an example of a desired pattern and its locatiou fouud in the image. Matching is widely applicable; it can be used to determine stereoscopic scene properties if more than olle image of the same scene taken from different locations is available. Matching in dynamic images (e.g., moving cars, clouds, etc.) is another application area. Generally speaking, olle image can
Figure 6.52: Scgmentation by matching; matched pattern and location of the best match.
238
Chapter 6: Segmentation I
be used to extract objects or patterns, and directed search is used to look for the same (or similar ) patterns in the remaining images. The best match is based on some criterion of optimality which depends on object properties and object relations. Matched patterns can be very small, or they can represent whole objects of interest. While matching is often based on directly comparing gray-level properties of image sub regions, it can be equally well performed using image-derived features or higher-level image descriptors. In such cases, the matching may become invariant to image transforms. Criteria of optimality can compute anything from simple correlations up to complex approaches of graph matching.
6.4.1
Matching criteria
Match-based segmentation would be extremely easy if an exact copy of the pattern of interest could be expected in the processed image; however, some part of the pattern is usually corrupted in real images by noise, geometric distortion, occlusion, etc. Therefore, it is not possible to look for an absolute match, and a search for locations of maximum match is more appropriate.
Algorithm 6.23: Match-based segmentation 1. Evaluate a match criterion for each location and rotation of the pattern in the image. 2. Local maxima of this criterion exceeding a preset threshold represent pattern locations in the image. Matching criteria ca.n be defined in many ways; in particular, correlation between a pattern and the searched image data is a general matching criterion (see Section 3.1.2). Let f be an image to be processed, h be a pattern for which to search, and V be the set of all image pixels in the processed image. The following formulae represent good matching optimality criteria describing a match between f and h located at a position ( '11" v).
C1 (71" v) =
1 1 + max I f(i + 71" j + v ) - h(i, j ) I (i,j ) E V
C2 (71" v) =
1+
� �
1 If(i + 71" j + v) - h('i , j) 1
'
(6.37) (6.38)
(i,j) E V
C3(71" v) =
1 + I:
1
( .f ('i + 'U, j + v) - h(i, j)) 2
.
(6.39)
( i ,j ) E V
Whether only those pattern positions entirely within the image are considered, or if partial pa.ttern positions, crossing the image borders, are considered as well, depends on the implementation. A simple example of the C3 optimality criterion values is given in Figure 6.53 for varying pattern locations---the best matched position is in the upper left corner. An X-shaped correlation mask was used to detect positions of magnetic resonance
6.4 Matching
0 0 0 1 1 0 0 I 0 I 0 0 0 0 0 0 0 0 0 0 0 8
1 I 1
(·1
1
1/3 1/6 1/8 1/5 1/7 1/8 1/8 1/9 1/57
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
(h)
Ie)
(e) values of the optimality criterion C3 (the best match uuderlincd) .
(tl) matched pattern;
Figure 6.53: Optimality matching criterion evaluation: (a) image data;
.. &. . .. . ... . ... . .... . ..-�. •
,
.
... •..r
.
' . . _.. , .. • .• • .� ; .- .. ,, . ' . . . "". ' . - ' . .
� -... .
I
"
'
.
• III!! . , . . . _. . .. I. '.',_. ,. . 1 ., · . .. . . .. • Ie .. ,
.
•
•
•
•
•
•
.
.. •
.
..,- . . , . �,. , . . " .. .. . .. .. . r y • " • '. • II .•
�-,.. ".�- ... , . "'" . ., .. • .. � .', ..;� . - � 11 to _ . .. .
In)
239
•
.
•
•
•
Ib)
Figure 6.54: X-shaped mask matching. (a) Original image (see also Figure 16.21). (b) Correlation image; the bet.ler the local correlation with the X-shaped m!lSk, the brighter the correlation
image. Conrt/!sy of D. Fi.,hel',
6.54. 16.3.2).
Collin.., The Univr.rsity of Iowa.
The detected markers are further used in heart motion analysis (see Sect.ion
markers in [Fisher ct Figure
S.
aI., 1991J;
the original image and the correlation image are shown in
If a fast, effcctive Fomier transform algorithm is available, the convolution theorem
can be used t.o cvaluatc matchiug. The correlation between a pattern be determined by first taking the product of the Fourier transform the complex conjugate of the Fourier transform the inver.>e transform (Section
3.2.2).
H#
h and image f can F of the image f and
of the pattern
It and then applying
Note that this approach considers an image to be
image. To compute thc product of Fourier transforms, F and
periodic U I ld thcrefore a targct pattern is allowed to be positioned partially outside an
H*
must be of the same
size; if a pattern size is smaller, zero-valued lines alld columns can be added to inHate it to the lippropriate size. Sometimcs, it may be better to add nOll-zero tJumbers, for example, the average gray-level of proCt.'Ssed images can serve the purpose well.
A
matching algorithm based on chamfering (see Section
2.3.1) can also be defined to
locate features such as known boundaries in edge maps. This is based on the observation tllat matching features such as lines will produce a very good response in correct, or near correct, positions, but very poor elsewhere, meaning that matching may be very hard to optimize. To see this, consider two straight lines rotating about one another-they have
240
Chapter 6: Segmentation I
exactly two matching positions (which are both perfect) , but the crude match strength of all other positions is negligible. A more robust approach is to consider the total distance between the image feature and that for which a match is sought. Recalling that the chamfer image (see Algorithm 2.1) computes distances from image subsets, we might construct such an image from an edge detection of the image under inspection. Then, any position of a required boundary can be judged for fit by summing the corresponding pixel values under each of its component edges in a positioning over the image- -low values will be good and high poor. Since the chamfering will permit gradual changes in this measure with changes in position, standard optimization techniques (see Section 9.6) can be applied to its movement in search of a best match. Examples of the use of chamfering can be found in [Barrow et al., 1977; Gavrila and Davis, 1995] .
6.4.2
Control strategies of matching
Match-based segmentation localizes all image positions at which close copies of the searched pattern are located. These copies must match the pattern in size and orientation, and the geometric distortion must be small. To adapt match-based methods to detect patterns that are rotated, and enlarged or reduced, it would be necessary to consider patterns of all possible sizes and rotations. Another option is to use just one pattern and match an image with all possible geometric transforms of this pattern, and this may work well if some information about the probable geometric distortion is available. Note that there is no difference in principle between these approaches. However, matching can be used even if an infinite number of transformations are allowed. Let us suppose a pattern consists of parts, these parts being connected by rubber links. Even if a complete match of the whole pattern within an image may be impossible, good matches can often be found between pattern parts and image parts. Good matching locations may not be found in the correct relative positions, and to achieve a better match, the rubber connections between pattern parts must be either pushed or pulled. The final goal can be described a;.; the search for good partial matches of pattern parts in locations that cause minimum force in rubber link connections between these parts. A good strategy is to look for the best partial matches first, followed by a heuristic graph construction of the best combination of these partial matches in which graph nodes represent pattern parts. Match-bm.,ed segmentation is time consuming even in the Himplest cases with no geometric transformations, but the proceHs can be made faster if a good operation sequence is found. The sequence of match tests must be data driven. Fast testing of image locations with a high probability of match may be the first step; then it is not necessary to test all possible pattern locations. Another speed improvement can be realized if a mismatch can be detected before all the corresponding pixels have been tested. If a pattern is highly correlated with image data in some specific image location, then typically the correlation of the pattern with image data in some neighborhood of thiH specific location is good. In other words, the correlation changes Hlowly around the best matching location. If this is the case, matching can be tested at lower resolution first, looking for an exact match in the neighborhood of good low-resolution matches only. The mismatch must be detected as soon as possible since mismatches are found much more often than matches. Considering formulae 6 .37-6.39, testing in a specified position must stop when the value in the denominator (measure of mismatch) exceeds some preset threshold. This implies that it is better to begin the correlation test in pixels
6.5 Eval uation issues i n segmentation
241
with a high probability of mismatch in order to get a steep growth in the mismatch criterion. This criterion growth will be faster than that produced by an arbitrary pixel order computation.
6.5
Evaluation issues i n segmentation
The range of segmentation techniques available is large and will grow. Each algorithm has or will have some number of parameters associated with it. Given this large toolbox, and a new problem, how might we decide which algorithm and which parameters are best? Or, less challenging, given two choices, which is better than the other? Such questions require us to evaluate performance in some objective manner. Meanwhile, evaluation of a single algorithm on different datasets provides information about robustness, and ability to handle data acquired under different conditions and by different modalities. The issue of evaluation in computer vision applies in almost all areas as the science matures: where once researchers would devise and publish algorithms, it is now expected that they also provide some evidence of their improved performance-often this is done with respect to accepted databases of images or videos to ensure comparability, a process begun informally many years ago with the widespread use of the 'Lena' [Rosenberg, 2001] image to benchmark compression algorithms. The increasing formalization of these activities is leading to respected workshops and conferences dedicated to evaluation. Segmentation evaluation is no exception to these developments; for example [Chabrier et al. , 2006; Forbes and Draper, 2000; Hoover et al. , 1996; Wang et al., 2006; Zhang, 1996] . Evaluating segmentations raises two problems; •
How do we determine what is 'right' , in order to compare a segmentation with reality?
•
What do we measure? And how do we measure it?
The answer to the second here is dependent on our answer to the first, as there are currently two independent ways of considering evaluation.
6.5.1
Supervised evaluation
Supervised evaluation proceeds on an assumption that the 'right ' answer is known normally this implies the defining of ground truth, perhaps by interactive drawing of correct boundaries on the image(s) via a suitable interface [Williams, 1976; Chalana and Kim, 1997; Heath et al. , 1997; Shin et al., 2001]. Obviously, this is a labor intensive task if a dataset of suitable sufficient size is to be compiled, but it is also the case that 'truth' is often far from clear. Many segmentation problems are fraught by low contrast, blur, and other ambiguities, and issues :mrrounding ullcertainty in human opinion are beginning to attract interest [Dee and Velastin, 2007; Needham and Boyle, 2003] . This issue is well illustrated in Figure 6.55. Clearly, it is simple (if costly) to take the judgments of several experts and somehow average them [Williams, 1976; Alberola-Lopez et al., 2004; Chalana and Kim, 1997] , but the elusiveness of 'truth' remains an issue. As a consequence, the need for a metric which accounts for possible inconsistencies has been identified by many researchers.
242
Chapter 6: Segmentation I
Figure 6.55: A region from a dynamically enhanced Mill study with partly ambiguous boundary. Two different experts have overlaid their judgments. Court,,",y of O. K..ba$�ovfJ, S. Tanner, University
of Leed&.
Nearly all supervised evaluation techniques are based on one of two (very well established) approaches [Bcauchemin and Thomson, 1997; Zhang, 1996]: misclassified area [Dice, 1945], or assesm s ent of border positioning etTors [Yasnoff et al., 1977]. 6.5.1.1
Misdassified area-mutual overlap
The mutual olJ€rlap approach, also known as Dice evaluation, is b!:Ised on computing the area of overlap between ground truth and a segmcnted region [Bowyer, 2000; Dice, 1945; Hoover et al., 19961. This is illustrated in Figure 6.56. The area is lIormalized to the total area of the two defining regions; if AI is the area of the segmented region, A2 is the area. of groulJd truth, MO is the area of their mutual ovedap, then the mutunl overlap metric is defined as 2MO MMO = A . + A, It is customary to measure acceptable quality with respect to this metric by setting a percent,age threshold for AlMO, usually greater than 50% [Bowyer, 20001, but this will vary to reflect the strictlles..'l of the definition. This approach is popular and seen to work well on, for example, binary, RGD or some satellite data, but is not always adequate. The simplicity of the measure often conceals quality differences between different segmentations, and gives little if any information about boundaries which may be partially correct; furt.her it assumes a closed contour, which is 1I0t always available. It is at its best when distances from a segmented. boundary to ground truth are distributed unimodally with low variance, but it is poor at handling uncertainty in ground truth definition. Despite these drawba('ks, this metric is attractive because of its simplicity, and is widely used for evaluation of segmentation algorithms
6.5 Evaluation issues in segmentation
,
,
,
i MO
,
executed
OU,
6.5,1.2
,
, ,
Figure 6.56: :\",utual ovr,rlap: machine segmented region in solid, ground Lruth ill da;;hed.
for example, medical imagery [Dowyer,
2005; Chrastek et
al.,
243
2005;
Prastawa
et.
al.,
2000;
Campadelli and Casirahgi,
2005].
Border positioning errors
Some time ago, an approach considering Euclidean distallce between segmented and ground truth pixels was devised [Yasnoff et al., 1977]. This is related to the Hausdorff measure between the sets [Rote, 1991]; the
Hausdorff distance between t.wo set.s A and B some element
s i comput.ed by finding the minimum distance from each element of one to of the other, and then finding the maximum such.
(
)
h(A,B) = max mind(a,b» , where a
and
SOIllC
suitable distance
ilEA
bED
h. The Hausdorff distauce is oriented
d(a,b)
is
(6.40)
metric, commonly the Euclidean distance between (a.'>ymmetric); usually h(A, B) ¥ h(B, A).
A gencml definition of the Hausdorff distance between two sets is [Rate, 1991]:
(
H(A, B) � max h(A, B), h(D, A)
).
( 6. 41 )
This defines a mea..<;ure of the set.s' mutual proximity, indicating how far (at most.) two sets of points are from each other.
H(A, B)
has been adapted by some authors [Chalana and Kim, 19971 as an evaluatioll
measme for the quality of segmelltation results, where region, and
B the pixels of a segmented regio!l.
A is the pixels of a ground
truth
Again, this does not afford an application
adaptable threshold for a degree of tolerance ill segmentation error and does not permit quality measurement of partial boundaries. This idea has been adapted to consider
only boundary pixels-measuring the distance
between boundaries of the regiolls iustead of the regions themselves permits evaluation of open boundaries. Local border positioning errors are determined for each point of the segmented borders
a.-;
a directiollal distance between pairs of points, the first being on
computer-determined border and a the second on the ground truth Euclidean metric). Clearly,
the (usually using the
the direction of measurement is still relevant,
as Figure 6.57
demonstrates. Border positiolling errors are usually averaged fot" the entire length of the segmented border l:lnd reported as mean
±
standard deviation.
Other statistics might assist in
assesis ng different a.'lpects of the segmentation performance; for example, signed and/or
unsigned mean border pooitioning errors, maximum border positioning errors, and/or root-mean-square surface positioning errors are typically computed. For signed border positioning errors, an arbit.rary convelltion must be followed in which a computer-border point located on one side of ground truth has a positive sign, and on the other side of the border a negative sign. Then, the mean signed border positioning error represents a
244
Chapter 6: Segmentation I .
, ,
.
•
, ,
•
•
IndelH'ndent mmdard
Compuler�ele
,.,
Ib)
Figure 6.57: Border positioniJlg errors. (a) Assuming that ground truth is known, border positioning errors are computed as directed distances between the computer-d�termined and correct borders. (b) If the errors are calculated in the opposite direction (from ground truth to the computer-determined border) , a substantially different answer may result. (c) Zoomed area showing the difference in calculating directional errors.
global bias of the computer segmentation, and its standard deviation describes
a.
degree
of dcpartme from the independent standard along the entire length of the border. Using the mean error distributions for the entire test set of multiple segmented objects, border ct aL,
positioning errors can be summarized as test-set mean Recently
[Kubassova
2006J
±
test-set standard deviation.
this approach has been enhanced to consider
tolerance is.<;ucs. Let NA be the number of pixels in boundary of A within a distance
Nil,
t of a pixel of B.
A, and At(D) be the pixels AdB), and NB and
If NA, is the cardinality of
are defined similarly,
( �� Ht A , B ) 2
(
NA' NA
+ NB
NB,
)
(6.42)
provides a metric that will increase monotonically with t, and converge to The parameter
t is an interval
of tolerance, within which pixels from
l.
OtiC
boundary
are considered as being 'close enough' to the other. This reffects the acceptable error of segmentation which may be acquired from width of ambiguous boundary sections, or the opinion of experts. As the tolerance can be extracted from the domain, it can reflect an applicatioll-dependent acceptable segmentation error. algorithm comparison [Kubassova et aI., Figure
6.58 illustrates the use of this metric, which has been shown 20061.
•
t
•
10
12
to be of use in
14
Figure 6.58: Use of the Ht metric on a segmentatiou from dYlla.mica!iy enhanced MIll; ground truth is dotted and a sample llCgmentation is solid. CourteSTJ 0/ O. KUOOssQlJo, University 4 Leed3.
6.5 Evaluation issues in segmentation
6.5.2
245
U nsupervised evaluation
Difficulties in acquiring ground truth such as imprecise definition, paucity of information, and time consumption make unsupervised approaches attractive: these quantify quality by considering different statistics derived from the properties of an image and segmentation, without knowledge of ground truth. Of course, this is trying to answer a poorly defined question; in many images the nature of a 'good segmentation ' will depend upon the application-for example, in a picture of traffic we may seek to segment out cars if monitoring congestion, or parts of cars if counting the number of Morgans driving past. Unsupervised evaluation metrics bypass such issues completely, and will be based on the location, shape, size, contrast, or intensity of segmented regions [Peters and Strickland, 1992] . They depend on either global image statistics, which can be derived from the pixels in the image, or regional statistics, which characterize the regions segmented. Characteristically, certain assumptions are made about a 'good segmentation' and these are either verified or not from the presented data. A simple example is the inter-region dissimilarity criterion [Levine and Nazif, 1985] which assumes that a good segmentation produces regions of uniform intensity with high contrast along borders. If a gray-scale image contains an object with average intensity level fo , and the average intensity of the local background is fb , the measure M at its most straightforward is defined as (6.43) This early metric is clearly very simple: successors include the intra-region uniformity criterion [Nazif and Levine, 1984; Weszka and Rmienfeld, 1978] (which assumes that an adequate segmentation should produce images with high intra-region uniformity), the Borsotti criterion [Borsotti et al., 1998; Lui and Yang, 1994; Chabrier et al., 2005] (which assumes that an imagc should be segmented into homogeneous regions, of simple shape), and the Zeboudj criterion [Jourlin et al. , 1989] (which assumes a good segmentation delivers regions of high contrast) . All of these have advantages and disadvantages, but the more sophisticated they become, the more complex and less intuitive their definitions become. All unsupervised metrics have their merits and can be demonstrated to be of value: this can be done, for example, by correlating their performance with a trusted supervised metric (or ground truth) on a large database [Chabrier et al. , 2006] . Frequently, the results of such exercises are inconclusive and sometime contradictory as a result of definitions being very limiting and inapplicable to challenging domains. Evaluation of segmentation algorithms is clearly important, but there does not currently exist a consensus on approach. Existing supervised approaches are labor intensive and of limited performance, while unsupervised approaches are often demonstrated on synthetic data sets and put constraints on image properties which often cannot be satisfied in real world applications. For practical purposes, one must typically answer three questions: 1 . How frequently a method fails to provide a meaningful segmentation: the answer is typically task-dependent and is often left to human experts to identify.
Cha pter 6: Segmentation I
246
2. How accurate the method is: segmentation accuracy can be assessed by the methods described, or some other performance assessment index. 3. How reproducible is the segmentation in successful cases: even if not absolutely accurate, segmentation reproducibility ( precision) is valuable in many applications. For example, if changes of some objeet property are followed over time, reproducibility may be more important than absolute accuracy. Since many segmentation techniques are dependent on a number of parameters and /or on initiali:wtion, such sensitivity can be assessed by determination of reproducibility. The Bland-Altman statistical approach is frequently used for this purpose [Bland and Altman, 1986, 1 999] . To evaluate segmentation performance, the reader has access to a number of approaches to this important, if unglamorous, phase. It is probable that this activity will see significant steps forward in the next few years.
6.6 •
Summary
Image segmentation The main goal of image segmentation is to divide an image into parts that have a strong correlation with objects or areas of the real world depicted in the image. Segmentation methods can be divided into three groups: thresholding, edge based segmentation and region-based segmentation. Each region can be represented by its closed boundary, and each closed boundary describes a region. Image data ambiguity is one of the main segmentation problems, often accompa nied by information noise. The more a priori information is available to the segmentation process, the better the segmentation results that can be obtained.
•
Thresholding Thresholding represents the simplest image segmentation process, and it is com putationally inexpensive and fast. A brightness constant called a threshold is used to segment objects and background. - Single thresholds can either be applied to the entire image ( global threshold ) or can vary in image parts ( local threshold ) . Only under very unusual cir cumstances can thresholding be successful using a single threshold for the whole image. Many modifications of thresholding exist: local thresholding, band threshol ding, semi-thresholding, multi-thresholding, etc. - Threshold detection methods are used to determine the threshold automati cally. If some property of an image after segmentation is known a priori, the task of threshold detection is simplified, since the threshold can be selected to ensure that this property is satisfied. Threshold detection can use p-tile thresholding, histogram shape analysis, optimal thresholding, etc. In bi-modal histograms, the threshold can be determined as a minimum between the two highest local maxima.
6.6 Summary
•
247
Optimal thresholding determines the threshold as the closest gray-level corre sponding to the minimum probability between t.he maxima of two or more normal distributions. Such thresholding results in minimum error segmentation. - Multi-spectral thresholding is appropriate for color or multi-band images . Edge-based image segmentation Edge-based segmentation relies on edges found in an image by edge detecting operators-- -these edges mark image locations of discontinuities in gray-level, color, texture, etc. The most common problems of edge-based segmentation, caused by image noise or unsuitable information in an image, are an edge presence in locations where there is no border, and no edge presence where a real border exists. Edge image thresholding is based on construction of an edge image that is processed by an appropriate threshold. - In edge relaxation, edge properties are considered in the context of neighboring edges. If sufficient evidence of the border presence exists, local edge strength increases and vice versa. Using a global relaxation ( optimization ) process, contin uous borders are constructed. Three types of region borders may be formed: inner, outer, and extended. The inner border is always part of a region, but the outer border never is. Therefore, using inner or outer border definition, two adjacent regions never have a common border. Extended borders are defined as single common borders between adjacent regions still being specified by standard pixel co-ordinates. - If the criterion of optimality is defined, globally optimal borders can be determined using (heuristic) graph searching or dynamic programming. Graph-search based border detection represents an extremely powerful segmentation approach. The border detection process is transformed into a search for the optimal path in t.he weighted graph. Cm;ts are associated with each graph node that reflect the likelihood that the border passes through the particular node (pixel ) . The aim is to find the optimal path (optimal border, with respect to some objective function) that connects two specified nodes or sets of nodes that represent the border's beginning and end. Cost definition (evaluation functions) is the key to successful border detection. Cost calculation complexity may range from simple inverted edge strength to com plex representation of a priori knowledge about the sought borders, segmentation task, image data, etc. Graph searching llses Nilsson 's A-algorithm and guarantees optimality. Heuris tic graph search may substantially increase search speed, although the heuristics must satisfy additional constraints to guarantee optimality. Dynamic programming is based on the principle of optimality and presents an efficient way of simultaneously searching for optimal paths from multiple starting and ending points. Using the A-algorithm to search a graph, it is not necessary to construct the entire graph since the costs associated with expanded nodes are calculated only if needed. In dynamic programming, a complete graph must be constructed. If calculation of the local cost functions is computationally inexpensive, dynamic programming may represent a computationally less demanding choice. However,
248
•
Chapter 6: Segmentation I
which of the two graph searching approaches (A-algorithm, dynamic programming) iH more efficient for a particular problem depends on the evaluation functions and on the quality of heuristics for an A-algorithm. Hough transform segmentation is applicable if objects of known shape are to be detected within an image. The Hough tranHform can detect straight lines and curves (object borderH) if their analytic equations are known. It is robust in recognition of occluded and noisy objects. The generalized Hough transform can be used if the analytic equationH of the searched Hhapes are not available; the parametric curve (region border) description is based on sample situations and is determined in the learning stage. While forming the regionH from complete borders is trivial, region determina tion from partial borders may be a very complex task. Region construction may be based on probabilities that pixels are located inside a region closed by the partial borders. Such methods do not always find acceptable regions bllt they are useful in many practical Hituations. Region-based image segmentation - Region growing segmentation should satisfy the following condition of complete segmentation (6.1) 8
i i: j ,
R = U Ri , i l =
and the maximum region homogeneity conditionH (6.30), (6.31)
H(Ri) = TRUE, i 1 , 2, . . . , 5 , H(Ri U Rj) = FALSE, i i: j , R adjacent to Rj . =
Three basic approaches to region growing exist: region merging, region split ting, and split-and-merge region growing. Region merging starts with an oversegmented image in which regions satisfy equation (6.30) . RegionH are merged to satisfy condition (6.31) as long as equation (6.30) remains satisfied. Region splitting is the opposite of region merging. Region splitting begins with an underHegmented image which does not satisfy condition (6.30) . Therefore, the existing image regions are sequentially split to satisfy conditionH ( 6 . 1 ) , (6.30), and (6.31). A combination of splitting and merging may result in a method with the advantages of both other approaches. Split-and-merge approaches typically use pyramid image representations. Because both split-and-merge processing options are available, the starting segmentation does not have to satisfy either condition (6.30) or (6.31 ) . - I n watershed segmentation, catchment basins represent the regions o f the seg mented image. The first watershed segmentation approach starts with finding a downstream path from each pixel of the image to local minima of image surface altitude. A catchment basin is then defined as the set of pixels for which their respective downstream paths all end up in the same altitude minimum. In the
6.7 References
•
•
249
second approach, each gray-level minimum represents one catchment basin and the strategy is to start filling the catchment basins from the bottom. Images segmented by region growing methods often contain either too many regions (under-growing) or too few regions (over-growing) as a result of non optimal parameter setting. To improve classification results, a variety of post processors has been developed. Simpler post-processors decrease the number of small regions in the segmented image. More complex post-processing may combine segmentation information obtained from region growing and edge-based segmentation . Matching Matching can be used to locate objects of known appearance in an image, to search for specific patterns, etc. The best match is based on some criterion of optimality which depends on object properties and object relations. Matching criteria can be defined in many ways; in particular, correlation between a pattern and the searched image data is often used as a general matching criterion. Chamfer matching may be used to locate one-dimensional features that might otherwise defeat cost-based optimality approaches. Evaluation Evaluation of segmentation is useful in deciding between algorithms, or parameter choice for a given algorithm. Supervised evaluation compares algorithm output to ground truth. Supervised approaches usually compare area overlap, or distance between bound aries--there are several ways of doing this. Ground truth is often poorly defined or expensive to extract. Unsuperv'ised approaches judge segmentations in ignorance of it. Many unsupervised approaches exist but they are mmally constrained by assump tions about image regions.
6.7
References
Alberola-Lopez c., Martin-Fernandez M . , and Ruiz-Alzola J. Comments on: A methodology for evaluation of boundary detection algorithms on medical images. IEEE Transactions on Medical Imaging, 23(5) :658-660, 2004. Ballard D. H. Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition, 13: 1 1 1--122, 198 1 . Ballard D. H. and I3rown C. M . Computer Vision. Prentice-Hall, Englewood Cliffs, N J , 1982. Barrett W. A. and Mortensen E. N. Fast, accurate, and reproducible live-wire boundary extraction. In Vis1wlization in Biomedical Computing, pages 1 83- 192, Berlin, Heidelberg, 1996. Springer Verlag.
Barrow H. G . , Tenenbaum J . M . , Bolles R. C., and Wolf H_ C. Parametric correspondence and chamfer matching: Two new techniques for i mage matching. In 5th International Joint Conference on Artificial Intelligence, Cambridge, CA, pages 659-663. Carnegie-Mellon University, 1977. Beauchemin M. and Thomson K. P. B. The evaluation of segmentation results and the overlapping area matrix. Remote Sensing, 18:3895-3899, 1997.
250
Chapter 6: Segmentation
I
Bellmann R. Dynamic Programming. Princeton University Press, Princeton, NJ, 1957. Bland J. M. and Altman D. G . Statistical methods for assessing agreement between two methods of clinical measurement. Lancet, 1 (8476) :307-310, 1986.
Bland .J . M. and Altman D. G. Measuring agreement in method comparison studies. Stat Methods Med Res, 8 : 1 35-160, 1999. Borsotti IvI., Campadelli P., and Schettini R. Quantitative evaluation of colour image segmentation results. Pattern Recognition Letters, 19(8):74 1--747, 1998.
Bowyer K. W. Validation of medical image analysis techniques. In Sonka M. and Fitzpatrick .1. M., editors, Handbook of Medical Imaging, volume 2, pages 567--607. Press Monograph, Belling ham, WA, 1 edition, 2000. ISBN 0-81 94-3622-4. Brice C. R. and Fennema C. L. Scene analysis using regions. Artificial Intelligence, 1 :205-226, 1 970. Brnel E. Pr'ecision of Line Following in Digital Images. Ph.D. thesis, ETN-89-93329, Technische University, Delft, The Netherlands, 1988. Brummer M. E. Hough transform detection of the longitudinal fissure in tomographic head images. IEEE Transactions on Medical Imaging, 1 0 ( 1 ) :74--81 , 1991 . Campadelli P. and Casirahgi E. Lung field segmentation in digital posterior-anterior chest radiographs. 3rd International Confer'ence on Advances in Pattern Recognition, Bath, UK, 3687:736- 745, 2005. Canny J. F. A computational approach to edge detection. IEEE Transactions on Pattern Analysis and Machine Intelligence, 8(6):679-698, 1 986. Chabrier S., Rosenberger C., Laurent R., and Rakotomamonjy A. Segmentation evaluation using a support vector machine. 3rd International Conference on Advances in Pattern Recognition, Bath, UK, 2:889-896, 2005. Chabrier S., Emile B., Rosenberger C., and Laurent H. Unsupervised performance evaluation of image segmentation. E URASIP Journal on Applied Signal Processing, 2006:1·-12, 2006. Chalana V. and Kim Y. A methodology for evaluation of boundary detection algorithms on medical images. IEEE Transactions on Medical Imaging, 16(5):642-652, 1997. Chang Y. L. and Li X. Fast image region growing. Image and Vision Computing, 1 3:559-571, 1995. Chen S. Y., Lin W. C., and Chen C. T. Split-and-merge image segmentation based on localized feature analysis and statistical tests. CVGIP - Graphical Models and Image Pr-ocessing, 53 (5):457- 475, 1991. Cho S., Haralick R., and Yi S . Improvement of Kittler and Illingworth's minimum error thresholding. Pattern Recogm:tion, 22(5) :609-617, 1989.
Chrastek R. , vVolf M., Donath K., Niemann H., Paulus D., Hothorn T., Lausen B . , Lammer R., Mardin C. Y., and Michelson C . Automated segmentation of the optic nerve head for diagnosis of glaucoma. Medical Image Analysis, 9(4) :297-314, 2005. Chu C. C. and Aggarwal J. K. The integration of image segmentation maps using region and edge information. IEEE Transactions on Patte'm Analysis and Machine Intelligence, 15: 124 1 - 1252, 1993.
Chung K. L. and Lin H. Y. Hough transform on reconfigurable meshes. Computer Vision and Image Understanding, 6 1 :278-284, 1 995. Collins S. H. Terrain parameters directly from a digital terrain model. Canadian Surveyor, 29 (5):507--518, 1975.
6.7 References
251
Davis L. S. Hierarchical generalized Hough transforms and line segment based generalized Hough transforms. Pattern Recognition, 15(4):277 -285, 1982. Dee H. M . and Velastin S. How close are we to solving the problem of automated visual surveillance? Machine Vision and Applications, 2007. To appear. Deklerck R., Cornelis J . , and Bister M . Segmentation of medical images. Image and Vision Computing, 1 1 :486-503, 1993. Demi M. Contour tracking by enhancing corners and junctions. Computer Vision and Image Understanding, 63: 1 18-134, 1996. Dice L. R. Measures of the amount of ecologic association between species. Ecology, 26(3): 297-302, 1945. Dobrin B. P. , Viero T., and Gabbouj M. Fast watershed algorithms: Analysis and extensions. In Proceedings of the SPIE Vol. 2180, pages 209-220, Bellingham, WA, 1994. SPIE. Duda R. O. and Hart P. E. Using the Hough transforms to detect lines and curves in pictures. Communications of the ACM, 1 5 ( 1 ) : 1 1-15, 1972. Dudani S. A. Region extraction using boundary following. In Chen C. H., editor, Pattern Recognition and Artificial Intelligence, pages 216-232. Academic Press, New York, 1976. Falcao A. X., Udupa J . K . , Samarasekera S . , Sharma S . , Hirsch B . E . , and Lotufo R. A. User steered image segmentation paradigms: Live wire and live lane. Technical Report MIPG213, Deptartment of Radiology, University of Pennsylvania. , 1995.
Fisher D . .1 . , Ehrhardt J. C., and Collins S. M. Automated detection of noninvasive magnetic resonance markers. In Computers in Cardiology, Chicago, IL, pages 493-496, Los Alamitos, CA, 199 1 . IEEE. Fleagle S. R., Johnson M. R., Wilbricht C . .1 . , Skorton D . .1 . , Wilson R. F., White C. W . , Marcus M . L . , and ColIin.<; S. M . Automated analysis o f coronary arterial morphology in cineangiograms: Geometric and physiologic validation in humans. IEEE TmnsactioU8 on Medical Imaging, 8(4):387-400, 1989.
Flynn M . 1 . Some computer organizations and their effectivness. Computers, 2 1 (9):948-960, 1972. .
IEEE Transactions on
Forbes L. A. and Draper B . A. Inconsistencies in edge detector evaluation. Computer Vision and Patte771, Recognition, 2(5):398-404, 2000. Gambotto J. P. A new approach to combining region growing and edge detection. Pattern Recognition Letters, 14:869-875, 1993. Gauch J. and Hsia C. W. A comparison of three color image segmentation algorithms in four color spaces. In Proceedings of the SPIE Vol, 1 81 8, pages 1 168-1 181, Bellingham, WA, 1992. SPIE. Gavrila D. M. and Davis L. S. Towards 3D model-based tracking and recognition of human movement: A multi-view approach. In Proceedings of the International Workshop on Face and Gesture Recognition, Zurich, 1995. Glasbey C. A. An analysis of histogram-based thresholding algorithms. C VGIP - Gmphical Models and Image Processing, 55:532-537, 1993. Goldberg M. and Zhang J. Hierarchical segmentation using a composite criterion for remotely sensed imagery. Photogmmrnetria, 42:87-96, 1987. Gonzalez R. C. and Wintz; P. Digital Image Pmcessing. Addison-Wesley, Reading, MA, 2nd edition, 1987.
Guil N., Villalba .1 . , and Zapata E. L. A fast Hough transform for segment detection. IEEE Transactions on Image Processing, 4:1541-1548, 1995.
Chapter 6: Segmentation
252
I
Hanson A . R. and Riseman E. M . , editors. Computer Vision Systems. Academic Press, New York, 1978. Heath M . , Sarkar S., Sanocki T., and Bowyer K. W. A robust visual method for assessing the relative performance of edge detection algorithms. IEEE Transactions on Pattern Analysis and Machine Intelligence, 19(12): 1338- 1359, 1997. Higgins W. E. and Ojard E. J. 3D images and use of markers and other topological information to reduce oversegmentations. Computers in Medical Imaging and Graphics, 17:387-395, 1993. Hong T. H . , Dyer C. R. , and Rosenfeld A. Texture primitive extraction using an edge-based approach. IEEE Transactions on Systems, Man and Cybernetics, 10(10) :659-675, 1980. Hoover A., Jean-Baptiste G . , .Jiang X., Flynn P. J . , Bunke H., Goldof D. B . , Bowyer K., Eggert D . W., Fitzgibbon A., and Fisher R. B . An experimental comparison of range segmentation algorithms. IEEE Transactions on Pattern Analysis and Machine Intelligence, 18(7) :673-689, 1996. Hough P. V. C. A Method and Means for Recognizing Complex Patter·ns. US Patent 3,069,654, 1962. Illingworth J. and Kittler J. The adaptive Hough transform. IEEE Tr'ansactions on Pattern Analysis and Machine Intelligence, 9(5):690-698, 1987. Illingworth J. and Kittler J. Survey of the Hough transform. Comp-uter Vision, Graphics, and Image Processing, 44( 1 ) :87- 1 16, 1988 . .Jourlin M., Pinoli J. C., and Zeboudj R. Contrast definition and contour detection for logarithmic images. Jou,rnal of Microscopy, 156:33 40, 1 989. Kalviainen H., Hirvonen P., Xu L., and Oja E. Probabilistic and non-probabilistic Hough transforms: Overview and comparisons. Image and Vision Comp'uting, 13:239-252, 1995. Kass M . , Witkin A., and Terzopoulos D. Snakes: Active contour models. In 1st International Conference on Computer' Vision, London, England, pages 259-268, Piscataway, NJ, 1987. IEEE. Kim J. S. and Cho H. S. A fuzzy logic and neural network approach to boundary detection for noisy imagery. Fuzzy Sets and Systems, 65: 141-159, 1994. Kittler
.J.
and Illingworth J. Minimum error thresholding. Pattern Recognition, 1 9:41-47, 1 986.
Koivunen V. and Pietikainen M. Combined edge and region-based method for range image segmentation. In Proceedings of SPIE- The International Society for Optical Engineering, volume 138 1 , pages 50 1 -512, Bellingham, WA, 1990. Society for Optical Engineering. Kovalevsky V. A. Topological foundations of shape analysis. In Shape in Pictur'e, pages 2 1-36. Springer Verlag, I3erlin, 1 994.
Kubassova 0 . , Boyle R. D., and Radjenovic A. A novel method for quantitative evaluation of segmentation outputs for dynamic contrast-enhanced MRI data in RA studies. In Proceedings of the Joint Disease Workshop, 9th International Conference on Medical Image Computing and Computer Assisted Interoention, volume 1 , pages 72-79, 2006. Kundu A. and Mitra S. K. A new algorithm for image edge extraction using a statistical classifier approach. IEEE Transactions on Pattern Analysis and Machine Intelligence, 9(4):569-577, 1987. Law T., Itoh H., and Seki H. Image filtering, edge detection, and edge tracing using fuzzy reasoning. IEEE Transactions on Pattern Analysis and Machine Intelligence, 18:481--491 , 1 996.
6.7 References
253
Lerner B. T. and Morelli M. V. Extensions of algebraic image operators: An approach to model based vision. In Third Ann'ual Workshop on Space Operations Automation and Robotics (SOAR 1 989), pages 687--695, Lyndon B Johnson Space Center, 1990. NASA. Levine M. D. and Nazif A. M. Dynamic measurement of computer generated image segmentations. IEEE Transactions on Pattem Analysis and Machine Intelligence, 7(2):1 55-164, 1985. Levy M. New theoretical approach to relaxation, application to edge detection, In 9th Inter national Conference on Pattem Recognition, Rome, Italy, pages 208-2 1 2, New York, 1988. IEEE. Liow Y. T. A contour tracing algorithm that preserves common boundaries between regions. CVGIP - Image Understanding, 53 (3) : 313-321, 1991. Lo R. C . and Tsai W . H. Gray-scale Hough transform for thick line detection in gray-scale images. Pattern Recognition, 28:647-66 1 , 1995. Lui J. and Yang Y. H. Multiresolution color image segmentation. IEEE Transactions on Pattern Analysis and Machine Intelligence, 16(7) :689-700, 1994. Manos G., Cairns A. Y., Ricketts 1 . W., and Sinclair D. Automatic segmentation of hand-wrist radiographs. Image and Vision Comp'uting, 1 1 : 100- 1 1 1 , 1993.
Marquardt D. W. An algorithm for least squares estimation of non-linear parameters. Journal of the Society for Industrial and Applied Mathematics, 1 1 :431-444, 1963. Martelli A. Edge detection using heuristic search methods. Computer Graphics and Image Processing, 1: 169-182, 1972. Martelli A. An application of heuristic search methods to edge and contour detection. Commu nications of the A CM, 19(2):73-83, 1 976. McKenzie D. S. and Protheroe S. R. Curve description using the inverse Hough transform. Pattern Recognition, 23(3 -4):283-290, 1990. Meyer F. and Beucher S. Morphological segmentation. JO'urnal of Visual Communication and Image Representation, 1:21-46, 1990.
Milgram D. L. Region extraction using convergent evidence. Computer Graphics and Image Processing, 1 1 : 1-12, 1979.
Mortensen E., Morse B., Barrett W., and Udupa J. Adaptive boundary detection using 'live-wire' two-dimensional dynamic programming. In Computers in Cardiology, pages 635-638, Los Alamitos, CA, 1992. IEEE Computer Society Press.
Nazif A. M. and Levine Iv'I. D. Low level image segmentation: an expert system. Transactions on Pattem Analysis and Machine Intelligence, 6(5):555-577, 1984.
IEEE
Needham C. J. and Boyle R. D. Performance evaluation metrics and statistics for positional tracker evaluation. In Crowley J . , Piater J., Vincze M . , and Paletta L., editors, Proc. Intl. Conference on Computer Vision Systems, number 2626 in LNCS, pages 278-289, Graz, Austria, 2003. Springer Verlag. Neveu C. F. Two-dimensional object recognition using rnultiresolution models. Computer Vision, Graphics, and Image Processing, 34( 1 ) : 52-65, 1986. Ney H. A comparative study of two search strategies for connected word recognition: Dynamic programming and heuristic search. IEEE Transactions on Pattern Analysis and Machine Intelligence, 14(5) :586-595, 1992. Nilsson N. J, Principles of Artificial Intelligence. Springer Verlag, Berlin, 1982. Olariu S., Schwing J. L . , and Zhang J. Computing the Hough transform on reconfigurable meshes. Image and Vision Computing, 1 1 :623-628, 1993.
254
Cha pter 6: Segmentation I
Otsu N. A threshold selection method from gray-level histograms. IEEE Transactions on Systems, Man and Cybernetics, 9 ( 1 ) : 62--66, 1 979. Oyster J. M . Associative network applications to low-level machine vision. Applied Optics, 26: 19 19-1926, 1987. Pavlidis T. Structural Pattem Recognition. Springer Verlag, Berlin, 1977. Pavlidis T. and Liow Y . Integrating region growing and edge detection. IEEE Transactions on Pattern Analysis and Machine Intelligence, 12(3):225-233, 1 990. Peters R. A. and Strickland R. N. A review of image complexity metrics for automatic target recognizers. 8th Meeting of Optical Eng'ineeTing, 1 992. http://www.vuse.vanderbilt,edu/ -rap2/ resume,htmL
Pietikainen M., Rosenfeld A., and Walter 1. Split-and-link algorithms for image segmentation. Pattern Recognition, 15 (4) : 287-298, 1982. Pontriagin L. S . The Mathematical TheoTY of Optimal Pmcesses. Interscience, New York, 1962. Prager J. M. Extracting and labeling boundary segments in natural scenes. IEEE Transactions on Pattern Analysis and Machine Intelligence, 2 ( 1 ) : 16-27, 1980. Pramotepipop Y. and Cheeva.�uvit F. Modification of split-and-merge algorithm for image segmentation. In Asian ConfeTence on Remote Sensing, 9th, Bangkok, Thailand, pages Q-26-1-Q--26- 6, Tokyo, 1988. Asian Association on Remote Sensing. Prastawa M., Gilmore J. H . , Lin W., and Gerig G. Automatic segmentation of MR images of the developing newborn brain. Medical Image Analysis, 5 (9) :457-466, 2005. PreHs W. H., Teukolsky S. A., Vetterling W. T., and Flannery B. P. Numerical Recipes in C: The ATt of Scientific Computing. Cambridge University Press, Cambridge, 2nd edition, 1992. Priese L. and Rehrmann V. On hierarchical color segmentation and applications, In ComputeT Vision and Pattern Recognition (Pmceedings), pages 633-634, Los Alamitos, CA, 1 993. IEEE.
Princen J . , Illingworth J . , and Kittler J. Hierarchical approach to line extraction. In Pmceedings: IEEE Computer' Society Confer'ence on ComputeT Vision and Pattem Recognition, Rosemont, IL, pages 92-97, Piscataway, NJ, 1989. IEEE. Princen J . , Illingworth J . , and Kittler J. Hypothesis testing: A framework for analyzing and optimizing Hough tranHform performance. IEEE Transact'ions on PatteTn Analysis and Machine Intelligence, 16:329-341 , 1994. Ridler T. W . and Calvard S. Picture thresholding using an iterative selection method. IEEE Tmnsactions on Systems, Man and Cybernetics, 8(8) : 630-632, 1978. Rosenberg C. The Lenna Story, 2001 . http: //www.cs.cmu.edu/-chuck/lennapg/. Rosenfeld A. and Kak A. C. Digital PictuTe Pmcessing. Academic Press, New York, 2nd edition, 1982. Rote G . Computing the minimum Hausdorff distance between two point sets on a line under translation. InfoTmation Pmcessing LetteTs, 38(3) : 1 23-127, 199 1 . Sahoo P . K., Soltani S . , Wong A . K . C . , and Chen Y. C. Survey o f thresholding techniques. ComputeT Vision, Graphics, and Image Pmcessing, 4 1 (2) :233-260, 1988. Santago P. and Gage H. Q. Quantification of MR brain images by mixture density and partial volume modeling. IEEE Transactions on Medical Imaging, 12:566 -574, 1993, Schettini R. A segmentation algorithm for color images. Pattem Recognition Letter's, 14:499-506, 1993.
6.7 References
255
Sher D. B . A technique for deriving the distribution of edge neighborhoods from a library of occluding objects. In Proceedings of the 6th International Confer'ence on Image Analysis and Processing. Progress 'in Image Analysis and Processing II, pages 422-429, Singapore, 1992. World Scientific. Shin M. C., Goldgof D. B . , and Bowyer K W. Comparison of edge detector performance through use in an object recognition task. Computer Vision and Image Understanding, 84 ( 1 ) :160-178, 200 1 . Soille P. and Ansoult M . Automated basin delineation from DEMs using mathematical morphol ogy. Signal Processing, 20: 171-182, 1990. Sonka M . , Wilbricht C. J . , Fleagle S. R., Tadikonda S. K , Winniford M. D., and Collins S. M . Simultaneous detection of both coronary borders. IEEE Transactions o n Medical Imaging, 12 ( 3 ) :588-599, 1993. Sonka M., Winniford M. D., Zhang X., and Collins S. M. Lumen centerline detection in complex coronary angiograms. IEEE Transactions on Biomedical Engineering, 41:520-528, 1994.
Suk M. and Chung S. M . A llew image segmentation technique based on partition mode test. Pattern Recognition, 1 6 ( 5 ) :469-480, 1983.
Tilton J . C. Image segmentation by iterative parallel region growing and splitting. In Proceedings of IGARSS '89 and Canadian Symposium on Remote Sensing, Vancouver, Canada, page>! 2420-2423, New York, 1989. IEEE. Udupa J. K, Samarasekera S., and Barrett W. A. Boundary detection via dynamic programming. In Visualization in Biomedical Comp'uting, Proc. SPIE Vol. 1 808, pages 33-39, Bellingham, WA, 1992. SPIE. Heijden F. v. d. Edge and line feature extraction based on covariance models. IEEE Transactions on Pattern Analysis and Machine Intelligence, 1 7:69-77, 1995. van der Zwet P. M. J. and Reiber J. H. C. A new approach for the quantification of complex lesion morphology: The gradient field transform; basic principles and validation results. Journal of the Amer"Cian College of Cardiologists, 82:216 -224, 1994. Vincent L. and Soille P. Watersheds in digital spaces: An efficient algorithm based on immersion simulations. IEEE Transactions on Pattern Analysis and Machine Intell-igence, 1 3 ( 6 ) : 583--598, 199 1 . Vlachos T. and Constantinides A. G. Graph-theoretical approach to colour picture segmentation and contour classification. lEE Proceedings Communication, Speech and Vis'ion, 140:36- 45, 1993.
Wang J . F. and Howarth P. J . Edge following as graph searching and Hough transform algorithms for lineament detection. In Proceed'ings of IGARSS '89 and Canad-ian Symposium on Remote Sensing, Vancouver, Canada, pages 93- 96, New York, 1989. IEEE.
Wang S., Ge F., and Liu T. Evaluating edge detection through boundary detection. E URASIP Journal on Applied Signal Processing, 2006 : 1 -15, 2006. Weszka J . S. and Rosenfeld A. Threshold evaluation techniques. IEEE Transactions on Systems, Man and Cybernetics, 8 ( 8 ) :622- 629, 1978. Willebeek-Lemair M. and Reeves A. Solving nonuniform problems on SIMD computers- -case study on region growing. Journal of Parallel and Distributed Computing, 8:135-149, 1990.
Williams G. W. Comparing the joint agreement of several raters with another rater. Biometrics, 32 (3 ) :619-627, 1976. Wood J. W. Line finding algorithms for SAR. Technical report, AD-A162024; RSRE-MEMO384 1 ; BR9730l, Royal Signals and Radar Establishment, Malvern, England, 1985.
256
Chapter 6: Segmentation I
Wu X. Adaptive split-and-merge segmentation based on piecewise least-square approximation . IEEE Transactions on Pattern Analysis and Machine Intelligence, 15:808--815, 1993. Wu Z. and Leahy R. An optimal graph theoretic approach to data clustering: Theory and its application to image segmentation. IEEE Transactions on Pattern Analysis and Machine Intelligence, 1 5 : 1 101-1 1 13, 1993. Xu L. and Oja E. Randomized Hough transform (RHT ) : Basic mechanisms, algorithms, and computational complexities. CVGIP - Image Understanding, 57: 13 1-154, 1993. Yasnoff W . A., Mui J. K., and Bacus J. W. Error measures for scene segmentation. Pattern Recognition Letters, 9:217-23 1 , 1 977. Yuen S. Y. K. and Hlavac V. An approach to quantization of the Hough space. In Proceedings of the 7th Scandinavian Conference on Image Analysis, Aalborg, Denmark, pages 733- 740, Copenhagen, Denmark, 199 1 . Pattern Recognition Society of Denmark, Copenhagen. Zhang Y . J. A survey on evaluation methods for image segmentation. Pattern Recognition, 29 (8):1335-1346, 1996. .
Chapter
7
Segmentation I I
Many standard methods of image segmentation have been introduced in Chapter 6, where stressed the importance and paramount role of Regmentation in almost all aspects of image analysis. Unsurprisingiy, image segmentation methods arc rapidly developing as novel and more powerful approaches continue to appear. New approaches must be able to cope with ever-increasing !lumbers of image datasets, of increltSing size of individual images, as well as with increasing dimensionality. This chapter contains more advanced material on segmentation, and focuses on techniques with three-dimensional or higher-dimensional capabilities. The methods presented have several other features in common--they were introduced relatively fe<:entiy, each called for a paradigm shift when introduced, and all of them proved valuable, flexible, and highly applicable. Of a variety of segmentation techniques reported in the literature, we have selected techniques using mean shift segmentation, fuzzy connectivity, deformable models, gradient vector flow, graph search, graph cuts, and optimal single and multiple surface detection for inclusion here. These methods bring a number of new concepts, clearly demonstrating the departure of newly-introduced segmentation methods from 2D to 3D (and higher dimensionality), with their multi-dimensional capabilities inherently present rather than appearing as an afterthought.
we
7.1
Mean Shift Segmentation
In Section 6.1.2, an optimal thrcsholding method was introduced in which gray-level statistics of individual objects and background were estimated to yield a set of segmentation thresholds. The estimates assumed that the gray level distributions were Caussian. In this and other similar approachcs, the main problem is to identify a number of parameters of a pre-determined probability density function. For example, equation (6.10) requires that three parameters be determined. Unfortunately, the assumptions of specific statistical distributions (which are rarely Gau�ian) as well as the need to estimate a number of its paranleters complicate this otherwise elegant approach.
258
Chapter 7: Segmentation I I
Mean shift image segmentation avoids estimation o f the probability density function and consists of 2 main steps-discontinuity preserving filtering and mean shift clustering. A non-parametric technique for the analysis of a complex multi-modal feature space and identification of feature clusters called the mean shift procedure was originally introduced in [Fukunaga and Hostetler, 1975J . After being forgotten for 20 years, it was re-introduced in [Cheng, 1 995] . Use of the mean shift approach in a number of image processing and vision tasks appeared in [Comaniciu and Meer, 1997, 2002] ' its use for real-time object tracking is reported in [Comaniciu et al. , 2000J (see also Section 16.5.2). In image processing, the feature space consists of quantitative image properties, which are mapped into a point in a multi-dimensional space of image description parameters. Once the mapping of all image points is completed, the feature space is more densely populated in locations corresponding to the significant image features. These denser regions of the multi-dimensional feature space form clusters, which in the image segmentation context may correspond to the individual image objects and background. More generally, the goal of the feature space analysis is delineation of the underlying clusters (compare Section 9.2.5). An intuitive understanding of the mean shift procedure can be gained from Figure 7.l. Note that the only free parameters of this process are the size and shape of the region of interest--or more precisely identification of the multivariate density kernel
•
• \ .,
•
Initial windoW'-
•
Mean shift
•
•
•
•
•
-. -
(b )
(a)
•
•
•
•
•
• •
•
.\ .
•
,
"-
•
(c)
•
Figure 7 . 1 : Principle of the mean shift procedure. The most dense region of data is identified in an iterative process. (a) The initial region of interest is randomly positioned over data and its centroid is determilled. The new region is moved to the location of the identified centroid. The vector determining the region's positional change is the mean shift. (b) Next step of the mean shift procedure-a new mean shift vector is determined and the region is moved accordingly. (c) The mean shift vectors are determined in the remaining steps of the procedure until convergence. The final location identifies the local density maximum, or the local mode, of the probability density function.
7 . 1 Mean Shift Segmentation estimator. For all practical purposes, radially symmetric kernels
259
K(x) are used satisfying
K(x) = c k ( l xln ' ( 7.1 ) where c is a strictly positive constant that makes K(x) to integrate to one. Two typical such kernels include the normal KN(X) and Epanechnikov KE(x) kernels. The normal kernel is defined by KN(X) = c exp (_� I X I12) ( 7.2 ) the kernel profile kN(x) of which is ( 7.3 )
The normal kernel is often symmetrically truncated to obtain a kernel with finite support. The Epanechnikov kernel is defined as if II x li :::; 1 , otherwise,
{l-X
( 7.4)
the kernel profile kE(x) of which is given by
kE(:r) =
0
for 0 :::; x :::; 1 , for x > 1 ,
and is not differentiable at the boundary. Given n data points in d-dimensional space estimator computed at point x is
lh ,K (x)
Xi
Rd, the multivariate kernel density
1 n X - Xi (X) fh , K = n hd 8 K ( -h- ) _
( 7.5 )
,
( 7.6 )
where h represents the kernel size, also called kernel bandwidth. As became obvious in Figure 7.1, we are interested in locating zeros of the gradient of i.e., identifying for which = O. The mean shift procedure is an elegant way of identifying these locations witho'ut estimating the underlying probability density function. In other words, from estimating the density, the problem becomes one of estimating the density gradient
ih, K (X),
X
'l.fh,K(X)
( 7.7 )
Using the kernel form in which k(x) is the kernel's profile, and assuming that its derivative exists -k' (:r ) = g(x) for all x E [0, 00) except for a finite set of points, ( 7.8 )
260
Chapter 7: Segmentation I I
where C k i s a normalizing constant, h represents the kernel si2e. ( Note that the profile gE (X) is uniform if K ( x ) = KE (X); for K ( x ) = KN (X) , the profile of YN (.T) is defined by the same exponential expression as kN (X). ) Using y(x) for a profile-defining kernel G ( x ) = cg g ( jj xF), equation (7.7) changes to
8 2 Ck = n (d+ 2) 8 (Xi - X) g h
2 Ck 'V !h , K (X) = n Md + 2) �
n
(II T 1 ) (II 1 )
(x - Xi ) k'
n
x - x· 2
X - Xi 2
� -I-
(7.9)
where 2:7= 1 gi is designed to be positive; gi g ( j (x - x;)/hf ) · The fi �t term of equation (7.9) 2ck/nh( d + 2 ) 2:�� 1 gi is proportional to a density estimator !h ,c computed with the kernel G: =
( 7 1 0) .
The second term ( 2:7=1 Xi y,j 2:� 1 Yi) - X represents the mean shift vector m h ,C (x) (7. 1 1 ) The successive locations {Yj L=1,2, ... of the kernel G are then
( 7. 1 2) where Y 1 is the initial position of the kernel G. The corresponding sequence of density estimates computed with kernel K is therefore (7.13) If the kernel K has a convex and monotonically decreasing profile, the sequences { Yj L=1,2, .. . and { .fh , K (j ) } j=1 ,2 . ... converge while { .fh, K (j ) } j = 1 ,2, . .. increases monotoni cally. The proof of this can be found in [Comaniciu and Meer, 2002]. The guaranteed convergence of the mean shift algorithm to the local maximum of a probability density function, or the density mode, is obtained due to the adaptive magnitude of the mean shift vector (the mean shift vector magnitude converges to zero). The convergence speed depends on the kernel employed. vVhen using the Epanechnikov kernel on discrete data ( uniform kernel profile), convergence is achieved in a finite number of steps. When data point weighting is involved, such as when using the normal kernel, the mean shift procedure is infinitely convergent. Clearly, a small lower bound value of change between steps may be used to stop the convergence process.
7,1 Mean Shift Segmentation
261
The set of all locations that converge to the same mode Yeon defines the basin of attraction associated with this mode. Note that convergence may also stop at a local plateau or a saddle point. To avoid such behavior, each stationary point (seemingly a point of convergence) is perturbed by a small random vector and the mean shift procedure process is restarted. If the proces..<; converges to the same location (with some tolerance allowed), the point is a local maximum anel identifies the density mode. A general algorithm for density fUllction mode detectioll cml therefore be summarizt.'
1. Using multiple initializations covering the entire fe�ure space, employ the mean shift procedure to identify the stationary points of ih.K. 2. Prune these points to only retain the local maxima corresponding to the density modes. The mean shift procedure has a number of advantages and some disadvantages, both connected to the global nature of its data representation. Among the advantages, the generality of the tool is one of the strongest. Due to substantial noise robustness, the approach is well suited to real·world applications. It can handle arbitrary cluster shapes and feature spaces. The only parameter to choose-· the size h of the kernel-actuaUy has a physical and understandable meaning. However, behavior in response to the choice of h is an important limitation since defining an appropriate va1ue is not always trivial. Its importance is further strengthened by the fact that too large a value of h may cause modes to he merged, while too small a value may allow introduction of insignificant additional modes and thus cause artificial cluster splitting. Methods for locally adaptive data-driven identification of h exist although they are more computationally expensive [Comaniciu et al., 2001; Georgescu et al., 2003]. The figures in this section werc generated using EDISON software package [Chris. toudia;; et al., 2002]. Figure 7,2 shows a color image represented in an L, u, v perceive d
(b) Figure 7.2: Color image L,u,v feature space. (a) Example color image. (h) Corresponding L, 1.1., V feature space. Courtesy 0/ P. Meer, Rutgers University, 02002 IEEE {Comaniciu a"d Meer, 2002}. A color version 0/ this figure may be seen in Ute calm· inset- -Plate 9.
262
Chapter 7: Segmentation I I 1OOr------
,
�
60� I
,
,
,
�
o
• c'
'00
la)
I
.. •., �.,.'.- ..
-
•
��,�.�{
. , " .;.4:":':f1�.�) '._,
:
•
I 1
1
� .• .. _
', 40
I _:1Ol
l I
--�--- -
._
'",,,;.r;- " '�.
. :10
�
40
�_')"" "
______
...._."-.. � � ro c'
I")
�I
I
�
�
I
, �
_. --
"
(e)
Figure 7.3: 20 fcaturc space analysis lIsing the mean shift proccdure. (a) Featurc space consisting of over 1 10,000 points representing the first two t:omponcnts of L, ll, v color de;;criptor;; (f>eC Figure 7.2). (b) Clustering of the feature space r�ulting from 159 !reparate initializatiolls. (c) Mean shift proct.'dure trajcctoriel (the Epam:chnikov kernel was used) . Note that some of the paths were pruned and stopped prematurely due to the plateau presence. C(rortesy of P. M"-er, Rl.ltgcn University, 02002 IEEE [CQmrl1l;cil.l (Iud MF.er, faOej. A c% r l!ersion oj this figure may be .�een in the c% r in.�et-Plate 10.
color feature space {Connoily, 1996; Wyszecki and Stiles, 1982]. L corresponds to the lightness or relative pixel brightness, tL and v are chromaticity features. Figure 7.3 gives an example of a 20 space analysis initialized from 159 distinct starting points. A (i-dimensional imagc is represented by a d-dimensional grid (spatial domain) of p-dimcnsional pixels (voxels), where p represents the number of spectral bands a.'iSOciated with the image (range domain); p 1 for grayscale images, p 3 for color images, etc. Assuming a Euclidean metric fol' both domains, the spatial and range vectors representing the complete information about the pixel's location and image properties can be concatenated to form a joint spatial-range domain. The resulting joint-domain kernel K""h. (x) consists of two radially symmetric kernels with parameters Il" and hr :=
:=
7.1 Mean Shift Segmentation
263
representing spatial- and range-domain kernel sizes, respectively; p, d. denote the space dimensionality. Kh.,h. (X) =
�
h: h�
k
o�: n k (II�: n ·
k(x)
(7.14)
is the common where XA and xr are the spatial and range parts of it feature vector, profile llsed in both domains, and c is a normalization constant. The Epanechttikov and normal kernels were shown to provide good performance. Therefore, setting the resolution level of the mode detection is obtaim.'"Cl by two parameters of a single v/.."Ctor h (I��,hr)' For mean shift image segmentation, a 2-step sequence of discontinuity p1'€serving filterin.q and mean shift clustering is employed. Let pixels in the original d-dimensional image be denoted by Xi and pixels of the filtered image by Zi. these pixels being represented in the joint spatial-range domain. -=
Algorithm 7.2: Mean shift discontinuity preserving filtering
1. For each image pixel X;, initialize step j
2. Compute Yi,j+l
as
=
1 and
Y;,l
= X;.
given in equation (7.12) until convergence Yi,coll '
3. The filtered pixel values are defined as Zi = (xl, Yi'oon ) ' i.e., the value of the filtered pixel at the location xi is assigned the image value of the pixel of convergence y[con ' Figure 7.4 provides an example of a mean shift filtering process.
(b) Figure 7.4: Meanshift filtering. (a) Original X-ray computed tomography image of human kidney and spine. (b) Filtered image. Courtesy of R. Beichel, Gnu University of TechnolQ{JIJ.
Once the image is filtered, the mean ."hijt ima.ge segmentation takes advantage of the association between each filtered image pixel Zi and a. significant mode of the jOint domain density located in this pixel's neighborhood after pruning nearby less significant modes. Let pixels X; alld Z; be dcfined in the joint spatial·· range domain as above, and let Lj be the segmcntation label associated with pixel i in the segmented image.
264
Chapter 7: Segmentation 11
Algorithm 7.3: Mean shift image segmentation
1. Employ the mean shift discontinuity presenJing filtering and store all information about the d-dimensional convergence points Yi.con'
2. Determi ne the clusters {C,,}p=I,.. . ,m by grouping all Zi, which are cio;;er than h., in the spatial domain and hr in the range domain. In other words, merge the basins of attraction of these convergence points. 3. Assign L; = {plZi E
Cp} for each pixel i = 1, . ,n. ..
4. If desired, eliminate regions smaller than P pixels as described in Algorithm 6.22. Figure 7.5 offers an example of a mean shift segmentation.
( hi
(01 Figure 7.5: Mean shift-based image segmentation. (a) Original image. (b) Image segmentation obtained with h. 5, h,. = 10, P 20. Note the meaningful segmentation of regions with slowly varying brightlles.'!, e.g., the sky or roofs. (c) Segmentation boundaries. Segmentation generated lIsing EDISON wftware package [Christolldias et al., 20021. =
=
7.2 Active contou r models-sna kes
7.2
265
Active contour models-snakes
The development of active contour models results from the work of Kass, Witkin, and Terzopoulos [Kass et al., 1987a; Witkin et al., 1987; Terzopoulos et al. , 1 987] , and they offer a solution to a va,riety of tasks in image analysis and machine vision. This section is based on the paper [Kass et al., 1 987b] in which the energy-minimization approach to achieve computer vision goals was first presented; the original notation is used. Active contour models may be used in image segmentation and understanding, and are also suitable for analysis of dynamic image data or 3D image data. The active contour model, or snake, is defined as an energy-minimizing spline (see Section 8.2.5)-the snake's energy depends on its shape and location within the image. Local minima of this energy then correspond to desired image properties. Snakes may be understood as a special case of a more general technique of matching a deformable model to an image by means of energy minimization. Snakes do not solve the entire problem of finding contours in images; rather, they depend on other mechanisms such as interaction with a user, interaction with some higher-level image understanding process, or information from image data adjacent in time or space. This interaction must specify an approximate shape and starting position for the snake somewhere near the desired contour. A priori as well as image-based information are then used to push the snake toward an appropriate solution-sec Figures 7.6 and 7.7. Unlike most other image models, the snake is active, always minimizing its energy functional, therefore exhibiting dynamic behavior.
( a)
(b)
(c)
Figure 7.6: Active contour model-snake. ( a) Initial snake position ( dotted ) defined interactively near the true contour. (b) , ( c) Iteration steps of snake energy minimization: the snake is pulled toward the true contour.
7.2.1
Traditional snakes and balloons
The energy functional which is minimized is a weighted combination of internal and external forces. The internal forces emanate from the shape of the snake, while the external forces come from the image and/or from higher-level image understanding processes. The snake is defined parametrically as v(s) = [x(s), y(s)] , where x (s), y(s) are X, y co-ordinates along the contour and s E [0, 1] (see Figure 8.1 1a) . The energy functional to be minimized
Chapter 7: Segmentation I I
266
(b)
(a)
•
•
(e)
(d)
Figure 7.7:
Snake-based detection of the intravascular ultrasourld catheter (dark line positioned inside the coronary artery lumen) in an aflgiographic X-ray illlage of a pig heart. (a) Original angiogram. (b) Initial position of the snake. (c) Snake deformation after 4 iterations. (d) Final position of the snake after 10 iterations.
may be written us
11 E�nakc {V(S)) ds � l' (E,,,.(v( ,)) + E'm" , (V(')) + E,,,,.(v(.,)) ) ds .
E:"skc =
(7.15)
where E;nt represent,s the internal energy of the spline due to bending, E;>U!lg" denot<.'$ image forces, and Econ external constraint forces. Usually, v(s) is approximated as a spline to ensurc desirable properties of continuity. The internal spline energy can be written Eint = u(s)
1 I' dv ds
+ f3(.�)
1 I' d'v ds2
(7.16)
where o:(s),,8(s) specify the elasticity and stiffness of the snake. Note that setting ('i(Sk) 0 at a point Sk allows the snake to become second-order discontinuous at that point, and develop a corner. The second term of the energy integral (7.15) is derived from the image data over which the snake lies. As an example, a weighted combinatiOIl of three different functionais =
7.2 Active contou r models-sna kes
267
is presented which attracts the snake to lines, edges, and terminations: Eimage = Wline Eline + Wedge Eedge + Wterm Ete rm
(7. 17)
.
The line-based functional may be very simple El ine =
f(x, y) ,
(7. 1 8)
where f(:1:, y) denotes image gray-levels at image location (x , V ) . The sign of Wl ine specifies whether the snake is attracted to light or dark lines. The edge-based functional Eedge
= - I V f(x, y) 1 2
(7. 1 9)
attracts the snake to contours with large image gradients -that is, to locations of strong edges. Line terminations and corners may influence the snake using a weighted energy functional Eterm : Let 9 be a slightly smoothed version of the image f, let 1/J (x , y) denote the gradient directions along the spline in the smoothed image g , and let
n (x, y) = ( cos '1/) (x, y) , sirql) (x, y)) ,
nR(:r: , y) = ( - sin 'l/) (x , y), cos 1/J (x, y))
be unit vectors along and perpendicular t o the gradient directions 1/J (x , V). Then the curvature of constant-gray-lcvel contours in the smoothed image can be written as [Kass et a1., 1987a] Eterm
EN 82g/8n'h - 8nR - 8g / 8n ( EPg/Dy2) (8g/8x)2 _
_
2 (82g/ax8y) (8g/8x) (8g/8y) + (82g/8x2) (8g/8y)2
-
((8g/8x) 2 + (8g/8y) 2 ) 3/ 2
The snake behavior may be controlled by adjusting the weights A snake attracted t o edges and terminations i s shown in Figure 7.8.
a
( 7.2 0 )
Wl i ne , Wed ge W t e r m .
,
0 /
/ CJ (a)
0
� (b)
Figure 7.8: A snake attracted to edges and terminations. (a) Contour illusion. (b) A snake attracted to the subjective contour. Adapted from [Kass et al. , 19S7bj.
The third term of the integral (7.15) comes from external constraints imposed either by a user or some other higher-level process which may force the snake toward or away
268
Chapter 7: Segmentation I I
from particular features. I f the snake is near to some desirable feature, the energy minimization will pull the snake the rest of the way. However, if the snake settles in a local energy minimum that a higher-level process determines as incorrect, an area of energy peak may be made at this location to force the snake away to a different local minimum. A contour is defined to lie in the position in which the snake reaches a local energy minimum. From equation (7.15) , the functional to be minimized is E:nakc
=
101 Esnake (V(S) ) ds .
Then, from the calculus of variations, the Euler-Lagrange condition states that the spline
v(s) which minimizes E:nakc must satisfy
d (7.21 ) - Ev., - Ev 0 , ds where Evs is the partial derivative of E with respect to dv / ds and Ev is the partial derivative of E with respect to v. Using equation (7.16) and denoting Eext = Eirn agc + Econ , the previous equation reduces to d dV d2 d2v O. (7.22) 0: (8) + "V Eext v(s) + 2 ;3(s) d s2 ds d8 ds To solve the Euler-Lagrange equation, suppose an initial estimate of the solution is available. An evolution equation is formed: =
(
�
(
)
(
)
(r:I (
)
( )
)
(
=
)
82v( t) . 8v(s , t) � 0 . (7.23) v Eex t V ( s, t ) 0: ( 8 ) +" + !OJ 2 P S ) !OJ s, !OJ !OJ u.�. uS uS uS2 The solution is found if 8v ( s, t) /8t = O. Nevertheless, minimization of the snake energy integral is still problematic; numerous parameters must be designed (weighting factors, iteration steps, etc. ) , a reasonable initialization must be available, and, moreover, the solution of the Euler-Lagrange equation suffers from numerical instability. Originally, a resolution minimization method was proposed [Kass et al. , 1987aJ ; partial derivatives in ,<; and t were estimated by the finite-differences method. Later [Amini et al. , 1988, 1990] , a dynamic programming approach was proposed which allows 'hard ' constraints to be added to the snake. Further, a requirement that the internal snake energy must be a continuous function may thus be eliminated and some snake configurations may be prohibited (that is, have infinite energy), allowing more a priori knowledge to be incorporated. Difficulties with the numerical instability of the original method were overcome by Berger [Berger and Mohr, 1990J by incorporating an idea of snake growing. A different approach to the energy integral minimization that is based on a Galerkin solution of the finite-element method was proposed in [Cohen, 1991J and has the advantage of greater numerical stability and better efficiency. This approach is especially useful in the case of closed or nearly closed contours. An additional pressure force is added to the contour interior by considering the curve as a balloon which is inflated. This allows the snake to overcome isolated energy valleys resulting from spurious edge points, giving better results all over (see Figures 7.9 and 7.10). Another approach using a finite-element method [Karaolani et al., 1992] also significantly improves the solution's efficiency; forces are scaled by the size of an element, preventing very small contributions (which may be noise) from contributing to the global solution as much as longer elements. 8v ( s, t) !OJ ut
_
=
7.2 Active contour models-snakes --
,
r ('I
"
./
D ,, /
\
/
/'
"\
\
(bl
Figure 7.9: Active contour model- balloon. (a) Initial contour. (b) Fi nal contour after and energy minimization. Adapted from [Cohen and Cohen, 1992].
(·1
269
(hi
iuRation
« I
Figure 7.10: Balloou�based image segmentation of all ultrasound image of a fetal head. (a) Initial position of the balloon. (b) Balloon deformation after 1 0 iterations. (e) Final position of the balloon after 25 iterations. Courtesy of v. Chrna1lll.
7.2.2
Extensions
Deformable models based on active contours were generalized to three dimensions by Terzopoulos [Terzopoulos et 11.1., 1987, 1988; Mclnerney and Ten:opou!os, 1993], and 3D balloons were introduced in [Cohen and Cohen, 1992]; more recently [Bulpitt and Efford, 1996J, a 3D generalization using an adaptive mesh that can refine and decimate has been successfully applied to modeling MR images of human heads and hands. In [Zhang and Braun, 1997], 8. fully three-dimensional active surface model with self-inflation and self-deflation forces has been introduced. Further, fast algorithms for active contour models [Williams and Shah, 1992; Olstad and Tysdahl, 1993; Lam and Yan, 19941 and a number of other extensions exist. Scveral problems often accompany the snake-based approach: Snakes tend to be attracted to spurious edges, they sometimes degenerate in shape by shrinking and flattening, and the convergence and stability of the contour deformation process may be unpredictable. Additionally, while their initialization is not
270
Chapter 7: Segmentation I I
straightforward, it may affect their performance substantially. Many approaches have been designed to overcome these limitations, some of them using more complex knowledge and models, employing neural networks, adaptively modifying the number of control points in snakes represented by D-splines [Figueiredo et al., 1 997] , designing internal forces independent of contour shape, determining external forces from edge images [Xu and Prince, 1 998] , limiting the region of interest by a pair of snakes, simplifying the initialization process [Neuenschwander et al. , 1994] ' considering region-based information [Etoh et al., 1993; Ronfard, 1994] ' and allowing topological snake adaptation so that the snake can How into complex shapes including branches [McInerney and Terzopoulos, 1 995] . Over the years, several variants of active contour models emerged as improvements of the original finite difference method discussed above. These variants aimed at an increase of robustness against noise, decrease of initialization sensitivity, improved selectivity for certain classes of objects, etc. The main such improvements include finite element snakes [Cohen and Cohen, 1993] , B-snakes [Menet et al., 1 990; Blake and Isard, 1998] , and Fourier deformable models [Staib and Duncan, 1 992] . None of them has emerged as a gold standard. Recently, a snake unification approach appeared called the united snakes combining several snake variants- -namely the finite difference, B-spline, and Hermite polynomial snakes in a comprehensive finite element formulation [Liang et al. , 1999, 2006] . The united snakes also include unification with live wire and intelligent scissor methods for interactive contour-based segmentation (Section 6.2.5). Detailed description of the united snakes theory and framework can be found in [Liang et al., 2006] .
7.2.3
G radient vector flow snakes
Two main limitations common to these approaches are the requirement of snake initial ization being close to the desired solution, and difficulties in segmenting concave portions of the boundary. To overcome these problems, gradient vector flow (GVF) fields and their use in snake image segmentation were reported in [Xu and Prince, 1998] . GVF fidd is a non-irrotational external force field that points toward the boundaries when in their proximity and varies smoothly over homogeneous image regions all the way to image borders. Consequently, it can drive a snake toward a border from a. large distance and can segment object concavities. In comparison to the classical snake approach [Kass et al., 1987aJ in which similar behavior can be attempted (but not obtained) by blurring the edge image or using pressure forces, it does not suffer from edge localization problems caused by edge distortion from their smoothing, it does not require to carefully fine-tune the balloon pressure forces to overcome the noise but not overcome the salient image features, and can attract the snake when initialized at either side of the boundary. The GVF field is derived from an image by minimization of an energy functional by solving decoupled linear partial differential equations via diffusing the gradient vectors of the edge image. The GVF is then used as an external force in the snake equations (7. 15), (7.22) forming a GVF snake. Considerable insensitivity to initialization and ability to segment concave boundaries result. The GVF field g (:c , y) = (u(x, y) , v(x, y)) minimizes the energy functional (7.24)
7.2 Active contour models-snakes
271
, ..- . '
'
-
-. .
(b)
(,)
-- -
(c)
Figure 7.11: Classic snake convergence. (a) Convergent sequence of snake locations. Note that the snake fails segmenting the concave boundary. (b) Classic external forces. (c) Close-up of the concave object region. No forces exist capable of pulling the snake inside the bay. CQ1.rtesll of J.
L. Prince and C. Xu, Johns Hopkins Ulli�'·5itll. 01998 IEEE {Xu and Prince, 1 99B/.
where JL is a regularization parameter balancing the weight of the first and second terms (increasing JL with increased noh;e), the subscripts denote directional partial derivatives. As described in [Xu and Prince, 1998], the GVF can be obtained by solving the Euler equations
'V2u - (u - Ix) (1; + I;) =: 0 , � \1'" - (v - I,) U; + g) � 0 ,
IL
(7.25) (7.26)
where 'Vz is a Laplacian operator. The second term in equa.tions (7.25), (7.26) is zero in homogeneous regions since the directional gradients lx, III arc zero. Consequently, the GVF hehavior in the homogeneous regions is fully defined by the Laplace equation effectively diffusing the information from the boundaries to the homogeneous parts of the image. Solutions to equations (7.25), (7.26) call be found by trea.ting 11 and v as functions of time and solving the following two decoupled equations for t ...... 00:
.,(x, y,t) � � \1'u(x, y,t) - (..(x,y,t) - /.(x,y)) (I.(x,y)' + /,(x,y)') , v,(x, y,t) � 1,\1'V(X, y,t) - (v(x,y,t) - /,(x,y)) (I.(x,y)' + /,(x,y)') .
(7.27) (7.28)
These generalized diffusion equations can be solved as separate scalar partial differ ential equations in 11 and v alld are used in heat conduction, fluid flow, etc. [Charles a.nd Porsching, 1990). Once g(x , Y) is computed, equation (7.22) is modified using the GVF external force Ee....t :=: g(x,Y) yielding the GVF snake equation Vt (S, t)
= 0' v/J ( s, t) - (J V/JI/ (8, t) + g ,
(7.29)
which can be solved as the traditional snake equation by an iterative process following discretizatioll. Figure 7.1l shows a convergence process and snake-attracting forces of a classic snake. It can be seen tha.t there is no force that would pull the snake towards the concave portio!! of the boundm-y. Consequently, the segmenta.tion fails in that area.
272
Chapter 7: Segmentation II
.",' .
•
·
·
·
1·1
Ibl
_
• .
' . � .
0'
.
.
.
, . . .: ". . . - .. .. .-
.. .
.
,
.
.
�
. ...
. -, : : "':. - . . -:. - . . ' . . ' . . . . .
i
:..
i
lei
Figure 7.12: GVF snake convergence. (a) Convergent !>equencc of �nake locations. Note that the snake succeeded in segmenting the concave boundary. (b) GVF external forces. (c) Close-up of the concave ohject region. Forces exist capable of pulling the snake inside the bay. Courtesy of J. L. Prince and C. Xu, Johru Hopkins University, 01998 JEEE (Xu (md PrinGC, 1998J.
1.1 Figure 7.13: Streamlines originating in a regular 32x32 grid of points. (8) Classic potential force ficld-only locations very close to the border can be attracted to the object. (b) Distance-based external force field. Note that there is insufficient pull of the location� inside the bay to correctly segment the concave region. However, the snake can be initiali?-ed at a distance from the object. (c) CVF force field demoll$trating the ability to correctly segment the concave region and maintaining the ability of a large-distancc initialization. Courtesy of J. L. p,-jnce and C. Xu, Johns
Hopkins University, 01998 IEEE [Xu and Prince, 199B).
When adding distance-based forces, thc snake segmentation fails in a similar fashiOll. In comparison, the GVF snake successfully segments the object as demonstrated in Figure 7.12. Figure 7.13 shows the attraction force coverage of an entire image using the classic, distance-based, and GVF field forces clearly demonstrating the advantages of the GVF approach. Figure 7.14 compares the segmentation of all object with incomplete, concave, and convex boundary segments when initialized from within the object.. Importantly, the GVF snake gives virtually the same segmentation if initialized from the outside with no change of the parameters. Figure 7.15 shows an application of a GVF snake to cardiac MR segmentation.
7.2 Active contour models-snakes
[ o
J \ l,-�f
Q
(0)
(d)
I
(.)
(b)
273
Figure 7.14: Snake behavior. (a) Initialization-common to a balloon, ciistance potential, and GVF snakes. (b) Balloon with an outward prcssnre force. (el Distance potential force snake. (d) GVF snake. CQTl1te" lJ of J. L. Prince and C. Xu, J()/",.s Hopkin.s Univel'sity, ()1998 IEEE {Xu and
Prince, J 998/.
can be generalized to higher dimensiolls defining the d-dimensional GYF field minimizing t.he energy functional (compa.re equation 7.24).
GVF
g(x)
as
E�
+ dx Jrn ' � l'\7gl' 1'\7/1' Ig - '\7II' ,
(7.30)
where the gradient operator is applied to each component. of g separately. The GVF field must then satisfy the Euler equation (compare equations 7.25, 7.26).
'\7'g - (g - '\7!) 1'\7II' � 0 ,
(7.31)
g, � � '\7'g - (g - '\7 f) 1'\7/1' ,
(7.32)
�
where again '\72 is applied to each component of g separately. Introducing a time variable t as before allows finding a solution for t -+ 00 of equation (compare equations 7.27, 7.28).
(a)
(b)
Figure 7.15: CnrdillC MR segmentation using GVF snakes. (a) Original short axis MR image of the left cardiac ventricle. (b) GVF snake segmentation showing the convergence process.
Courtesy of J. L. Prince and C. Xu, Johm Hopkim Univer.9ity, 01998 IEEE IXu a.nd Prince, 1998}.
274
Chapter 7: Segmentation II .t·
·
•
.
.
-
,
"
.
(0)
(b) . .,
(d)
(.)
(f)
.
.
(g)
Figure 7.16: GVP snake scgmcntation in 3D. (8.) lsosurfacc of a 3D object. defined on a 643 grid. (b) Position of plane A 011 which the 3-D GVF vectors arc depicted in (c). (d) Tile initial configuration of a deformable surface using GVF and its positions after (e) 10, (f) 40, and (g) 100
iterations. Courtesy of J. L. Prince and C. Xu, Johns HOl!ans Uni'lersity, 019981£££ {XII and Prince, 1998}.
where gt denotes a partial derivative with respect to t. Similarly to the 2D case, equation (7.32) contains d d{.'COupled scalar linear second order parabolic partial differential equations in each element of g and can be solved iteratively. Figure 7.16 demonstrates a GVF snake segmentation of a star-shaped object in 3D. Figure 7.17 shows an application of I). 3D GVF snake in brain segmentation [Tosun et aI., 2004J. Active contour models represent a recent approach to contour detection and image intcrprctation. They differ substantially from classical approaches, where features are extracted fmm an image and higher-level processes try to interpolate sparse data to find a representation that matches the original data--active contour models start from an initial estimate based on higher-level knowledge, and an optimization method is used to refine the initial estimate. During the optimization, image data, an initial estimate, desired contour properties, and knowledge-based constraints are considered. Feature extraction and knowledge-based constrained grouping of these features are integrated into a single process, which seems to be the biggest advantage. Active contour models, however, search for local energy minima not attempting to achieve globa!ly optimal solutions. Applications can be found in many areas of machine vision and medical image analysis [Cohen and Coilen, 1992; Hyche et aL, 1992; Lobregt and Viergever, 19951.
7.3 Geometric deformable models-level sets and geodesic active contours
('I
(bl
(al
275
(el
(dl
Figure 7.17: 3D segmentation of the MR brain image using eVF snakes. (a-c) Fuzzy classification of the white matter (a), gray matter (b), and cercbrospinal fluid (c) in the cerebrum. A fuzzy classification yielded three membership functions, cross-sections of which are shown. (d,e) GVF snake segmentation was used to ohtain anatomically feasible surfaces representing the central (d), and pial (el surfaces bounding t.he cortex. Courtesy of J. L. Prinr.'e, Johfl:S Hopkins University.
Geometric deformable models-level sets
7.3
and geodesic active contours There are t.wo main groups of deformable contour/surface models: the snakes discussed in the previous
section
belong
to thc parametric model family as horders are represented
in a parametric form. Whilc appropria.te for many segmentation tasks, they may yield cusps or intersecting boundaries in some situations. The second family of deformable
surfaces�geometric deformable models-'"""'"ve "i) rcomc
this problem by representing
developing l:iUrfaecs by partial differential equations. The geometric deformable model
literature has grown extensively in the past years, in many cases reporting a variety of applica.tions in which deformable model based segmentation can be used. An excellent
et aL,
treatment of deformable model principles and