Image Processing Toolbox
®
For Use with MATLAB
Computa tion
Visua liza tion
Progra m ming
User’s Guide
Version 2.1
www.MatlabSite.com
How to Contact The M athW orks:
☎
508-647-7000
Phone
508-647-7001
Fax
The MathWorks, Inc.
24 Prime Park Way
Natick, MA 01760-1500
Mail
http://www.mathworks.com
Web
Anonymous FTP server
Newsgroup
PHONE
FAX
✉
MAIL
INTERNET
ftp.mathworks.com
comp.soft-sys.matlab
@
support@mathworks.com
suggest@mathworks.com
bugs@mathworks.com
doc@mathworks.com
subscribe@mathworks.com
service@mathworks.com
info@mathworks.com
Technical support
Product enhancement suggestions
Bug reports
Documentation error reports
Subscribing user registration
Order status, license renewals, passcodes
Sales, pricing, and general information
Image Processing Toolbox User’s Guide
COPYRIGHT 1993 - 1998 by The MathWorks, Inc. All Rights Reserved.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathWorks, Inc.
U.S. GOVERNMENT: If Licensee is acquiring the Programs on behalf of any unit or agency of the U.S.
Government, the following shall apply: (a) For units of the Department of Defense: the Government shall
have only the rights specified in the license under which the commercial computer software or commercial
software documentation was obtained, as set forth in subparagraph (a) of the Rights in Commercial
Computer Software or Commercial Software Documentation Clause at DFARS 227.7202-3, therefore the
rights set forth herein shall apply; and (b) For any other unit or agency: NOTICE: Notwithstanding any
other lease or license agreement that may pertain to, or accompany the delivery of, the computer software
and accompanying documentation, the rights of the Government regarding its use, reproduction, and disclosure are as set forth in Clause 52.227-19 (c)(2) of the FAR.
MATLAB, Simulink, Handle Graphics, and Real-Time Workshop are registered trademarks and Stateflow
and Target Language Compiler are trademarks of The MathWorks, Inc.
Other product or brand names are trademarks or registered trademarks of their respective holders.
Printing History: August 1993
May 1997
January 1998
First printing
Version 1
Second printing Version 2
Revised for MATLAB 5.2 (online version)
www.MatlabSite.com
Ima ge Credits
moon
Copyright Michael Myers. Used with permission.
cameraman
Copyright Massachusetts Institute of Technology. Used with permission.
trees
Trees with a View, watercolor and ink on paper, copyright Susan Cohen.
Used with permission.
forest
Photograph of Carmanah Ancient Forest, British Columbia, Canada,
courtesy of Susan Cohen.
circuit
Micrograph of 16-bit A/D converter circuit, courtesy of Steve Decker and
Shujaat Nadeem, MIT, 1993.
m83
M83 spiral galaxy astronomical image courtesy of Anglo-Australian
Observatory, photography by David Malin.
alumgrns
bacteria
blood1
bonemarr
circles
circlesm
debye1
enamel
flowers
ic
ngc4024l
ngc4024m
ngc4024s
rice
saturn
shot1
testpat1
testpat2
text
tire
Copyright J. C. Russ, The Image Processing Handbook, Second Edition,
1994, CRC Press, Boca Raton, ISBN 0-8493-2516-1. Used with permission.
www.MatlabSite.com
www.MatlabSite.com
Contents
Before You Begin
What is the Image Processing Toolbox? . . . . . . . . . . . . . . . . . . . . . . . x
New Features in Version 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x
Installing the Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
About This Manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xii
Typographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Introduction
1
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Images in MATLAB and the Image Processing Toolbox . . . . 1-3
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Image Types in the Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
Indexed Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
Intensity Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
Binary Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7
RGB Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
Multiframe Image Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10
Working with Image Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Reading and Writing Images . . . . . . . . . . . . . . . . . . . . . . . . . .
Converting Images to Other Types . . . . . . . . . . . . . . . . . . . . . .
Color Space Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Working with uint8 Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Converting Between Data Types . . . . . . . . . . . . . . . . . . . . .
Turning the Logical Flag on or off . . . . . . . . . . . . . . . . . . . .
www.MatlabSite.com
1-11
1-11
1-11
1-13
1-13
1-14
1-15
i
Coordinate Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Pixel Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Spatial Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using a Nondefault Spatial Coordinate System . . . . . . . . .
1-16
1-16
1-17
1-18
Displaying Images
2
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Standard Display Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Displaying Images with imshow . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
The truesize Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
Displaying Indexed Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
Displaying Intensity Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
Displaying Binary Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Changing the Display Colors . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Displaying RGB Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Displaying Images in Graphics Files . . . . . . . . . . . . . . . . . . . . . 2-8
Displaying Nonimage Data as an Intensity Image . . . . . . . . . . 2-8
Special Display Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Adding a Colorbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Displaying Multiframe Image Arrays . . . . . . . . . . . . . . . . . . . .
Displaying Frames Individually . . . . . . . . . . . . . . . . . . . . . .
Displaying All Frames at Once . . . . . . . . . . . . . . . . . . . . . . .
Converting the Array to a Movie . . . . . . . . . . . . . . . . . . . . .
Displaying Multiple Images . . . . . . . . . . . . . . . . . . . . . . . . . . .
Displaying Each Image in a Separate Figure . . . . . . . . . . .
Displaying Multiple Images in the Same Figure . . . . . . . . .
Zooming in on a Region of an Image . . . . . . . . . . . . . . . . . . . . .
Texture Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-10
2-10
2-11
2-11
2-12
2-13
2-14
2-14
2-15
2-16
2-17
Printing Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19
ii
Contents
www.MatlabSite.com
Geometric Operations
3
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Image Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Image Resizing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5
Image Rotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6
Image Cropping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7
Neighborhood and Block Operations
4
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Types of Block Processing Operations . . . . . . . . . . . . . . . . . . . . 4-2
Sliding Neighborhood Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4
Padding of Borders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
Linear and Nonlinear Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
Distinct Block Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8
Overlap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9
Column Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sliding Neighborhoods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Distinct Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
www.MatlabSite.com
4-11
4-11
4-12
4-14
iii
Linear Filtering and Filter Design
5
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Linear Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Convolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Rotating the Convolution Kernel . . . . . . . . . . . . . . . . . . . . . . 5-4
Determining the Center Pixel . . . . . . . . . . . . . . . . . . . . . . . . . 5-4
Applying the Computational Molecule . . . . . . . . . . . . . . . . . . 5-4
Padding of Borders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
The filter2 Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7
Separability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8
Determining Separability . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9
Higher-Dimensional Convolution . . . . . . . . . . . . . . . . . . . . . . . . 5-9
Using Predefined Filter Types . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9
Filter Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
FIR Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Frequency Transformation Method . . . . . . . . . . . . . . . . . . . . .
Frequency Sampling Method . . . . . . . . . . . . . . . . . . . . . . . . . .
Windowing Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating the Desired Frequency Response Matrix . . . . . . . . .
Computing the Frequency Response of a Filter . . . . . . . . . . . .
5-13
5-13
5-14
5-15
5-16
5-18
5-19
Transforms
6
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Fourier Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4
The Discrete Fourier Transform . . . . . . . . . . . . . . . . . . . . . . . . . 6-8
Relationship to the Fourier Transform . . . . . . . . . . . . . . . . . 6-8
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9
iv
Contents
www.MatlabSite.com
Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Frequency Response of Linear Filters . . . . . . . . . . . . . . . . .
Fast Convolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Locating Image Features . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-11
6-11
6-12
6-13
Discrete Cosine Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-15
The DCT Transform Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16
The DCT and Image Compression . . . . . . . . . . . . . . . . . . . . . . 6-17
Radon Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-19
Using the Radon Transform to Detect Lines . . . . . . . . . . . . . . 6-22
The Inverse Radon Transform . . . . . . . . . . . . . . . . . . . . . . . . . 6-25
Analyzing and Enhancing Images
7
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
Pixel Values and Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3
Pixel Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3
Intensity Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4
Image Contours . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7
Image Histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8
Summary Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9
Feature Measurement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9
Image Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10
Edge Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10
Quadtree Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-11
www.MatlabSite.com
v
Image Enhancement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Intensity Adjustment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Gamma Correction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Histogram Equalization . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Noise Removal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Linear Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Median Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Adaptive Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7-14
7-14
7-16
7-18
7-20
7-21
7-21
7-23
Binary Image Operations
8
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Neighborhoods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Padding of Borders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Displaying Binary Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3
Morphological Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4
Dilation and Erosion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4
Related Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-7
Predefined Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-8
Object-Based Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4- and 8-Connected Neighborhoods . . . . . . . . . . . . . . . . . . . . . .
Perimeter Determination . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Flood Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Connected-Components Labeling . . . . . . . . . . . . . . . . . . . . . . .
Object Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8-10
8-10
8-12
8-13
8-15
8-16
Feature Measurement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-18
Image Area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-18
Euler Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-19
Lookup-Table Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-20
vi
Contents
www.MatlabSite.com
Region-Based Processing
9
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Specifying a Region of Interest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-3
Selecting a Polygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-3
Other Selection Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-5
Filtering a Region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6
Filling a Region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-8
Color
10
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Working with Different Color Depths . . . . . . . . . . . . . . . . . . . . . 10-3
Reducing the Number of Colors in an Image . . . . . . . . . . . . . .
Using rgb2ind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Quantization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Colormap Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using imapprox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Dithering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10-5
10-5
10-6
10-7
10-7
10-8
Converting to Other Color Spaces . . . . . . . . . . . . . . . . . . . . . . . . . 10-9
NTSC Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-9
YCbCr Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-10
HSV Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-10
Reference
11
www.MatlabSite.com
vii
viii Contents
www.MatlabSite.com
Before You Begin
What is the Image Processing Toolbox? . . . . . . . . . x
New Features in Version 2.1 . . . . . . . . . . . . . . . x
Installing the Toolbox . . . . . . . . . . . . . . . . . . xi
About This Manual . . . . . . . . . . . . . . . . . .xii
Typographical Conventions . . . . . . . . . . . . . . xiii
www.MatlabSite.com
Before You Begin
W ha t is the Ima ge Processing Toolbox ?
The Image Processing Toolbox is a collection of functions that extend the
capability of the MATLAB® numeric computing environment. The toolbox
supports a wide range of image processing operations, including:
• Geometric operations
• Neighborhood and block operations
• Linear filtering and filter design
• Transforms
• Image analysis and enhancement
• Binary image operations
• Region of interest operations
Many of the toolbox functions are MATLAB M-files, series of MATLAB
statements that implement specialized image processing algorithms. You can
view the MATLAB code for these functions using the statement:
type function_name
You can extend the capabilities of the Image Processing Toolbox by writing
your own M-files, or by using the toolbox in combination with with other
toolboxes, such as the Signal Processing Toolbox and the Wavelet Toolbox.
N ew Fea tures in Version 2 .1
Version 2.1 of the Image Processing Toolbox offers a number of advances over
versions 1 and 2. For information about the differences between versions 1 and
2, and versions 2 and 2.1, type this command at the MATLAB prompt:
helpwin images/Readme
For a list of all of the functions in the Image Processing Toolbox, type this
command:
helpwin images/Contents
x
www.MatlabSite.com
W hat is the Image Processing Toolbox?
Insta lling the Toolbox
To determine if the Image Processing Toolbox is installed on your system, type
this command at the MATLAB prompt:
ver
When you enter this command, MATLAB displays information about the
version of MATLAB you are running, including a list of all toolboxes installed
on your system and their version numbers.
For information about installing the toolbox, see the MATLAB Installation
Guide for your platform.
www.MatlabSite.com
xi
Before You Begin
About This M a nua l
This manual has three main parts:
• Chapters 1 and 2 discuss working with image data and displaying images in
MATLAB and the Image Processing Toolbox.
• Chapters 3 to 10 provide in-depth discussion of the concepts behind the
software. Each chapter covers a different topic in image processing. For
example, Chapter 5 discusses linear filtering, and Chapter 9 discusses
binary image operations. Each chapter provides numerous examples that
apply the toolbox to representative image processing tasks.
• Chapter 11 gives a detailed reference description of each toolbox function.
Reference descriptions include a synopsis of the function’s syntax, as well as
a complete explanation of options. Many reference descriptions also include
examples, a description of the function’s algorithm, and references to
additional reading material.
All users should read Chapters 1 and 2. Less experienced users will find
Chapters 3 to 10 a valuable introduction to image processing, while more
experienced users may prefer to use Chapter 11.
xii
www.MatlabSite.com
About This M anual
Ty pogra phica l Conventions
To Indica te...
This M a nua l Uses...
Ex a m ple
Example code
Monospace type
To assign the value 5 to A,
enter:
A = 5
MATLAB output
Monospace type
MATLAB responds with:
A =
5
Function names
Monospace type
The cos function finds
the cosine of each array
element.
New terms
Italics
An array is an ordered
collection of information.
Keys
Boldface with an
initial capital letter
Press the Return key.
Menu names,
items, and GUI
controls
Boldface with an
initial capital letter
Choose the Print option
from the File menu.
Mathematical
expressions
Variables in italics.
Functions, operators,
and constants in
standard type
This vector represents the
polynomial:
www.MatlabSite.com
p = x2 + 2x + 3
xiii
Before You Begin
xiv
www.MatlabSite.com
1
Introduction
Overview
. . . . . . . . . . . . . . . . . . . . . 1-2
Images in MATLAB and the Image Processing Toolbox 1-3
Data Types . . . . . . . . . . . . . . . . . . . . . 1-3
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
1-5
1-5
1-6
1-7
1-8
1-9
Working with Image Data . . .
Reading and Writing Images . . .
Converting Images to Other Types
Working with uint8 Data . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
1-11
1-11
1-11
1-13
Image Types in the Toolbox
Indexed Images . . . . . .
Intensity Images . . . . . .
Binary Images . . . . . . .
RGB Images . . . . . . . .
Multiframe Image Arrays . .
.
.
.
.
.
.
Coordinate Systems . . . . . . . . . . . . . . . . 1-16
Pixel Coordinates . . . . . . . . . . . . . . . . . . 1-16
Spatial Coordinates . . . . . . . . . . . . . . . . . . 1-17
www.MatlabSite.com
1
Introduction
O verview
This chapter introduces you to the fundamentals of image processing using
MATLAB and the Image Processing Toolbox. It describes the types of images
supported, and how MATLAB represents them. It also explains the basics of
working with image data and coordinate systems.
1-2
www.MatlabSite.com
Images in M ATLAB and the Image Processing Toolbox
Ima ges in M ATLAB a nd the Ima ge Processing Toolbox
The basic data structure in MATLAB is the array, an ordered set of real or
complex elements. This object is naturally suited to the representation of
images, real-valued, ordered sets of color or intensity data. (MATLAB does not
support complex-valued images.)
MATLAB stores most images as two-dimensional arrays (i.e., matrices), in
which each element of the matrix corresponds to a single pixel in the displayed
image. (Pixel is derived from picture element and usually denotes a single dot
on a computer display.) For example, an image composed of 200 rows and 300
columns of different colored dots would be stored in MATLAB as a 200-by-300
matrix.
This convention makes working with images in MATLAB similar to working
with any other type of matrix data, and makes the full power of MATLAB
available for image processing applications. For example, you can select a
single pixel from an image matrix using normal matrix subscripting:
I(2,15)
This command returns the value of the pixel at row 2, column 15 of the image I.
Da ta Ty pes
By default, MATLAB stores most data in arrays of class double. The data in
these arrays is stored as double precision (64-bit) floating-point numbers. All
of MATLAB’s functions and capabilities work with these arrays.
For image processing, however, this data representation is not always ideal.
The number of pixels in an image may be very large; for example, a
1000-by-1000 image has a million pixels. Since each pixel is represented by at
least one array element, this image would require about 8 megabytes of
memory.
In order to reduce memory requirements, MATLAB supports storing image
data in arrays of class uint8. The data in these arrays is stored as 8-bit
unsigned integers. Data stored in uint8 arrays requires one eighth as much
memory as data in double arrays.
Because the types of values that can be stored in uint8 arrays and double
arrays differ, the Image Processing Toolbox uses different conventions for
interpreting the values in these arrays. (Noninteger values cannot be stored in
www.MatlabSite.com
1-3
1
Introduction
uint8 arrays, for example, but they can be stored in double arrays.) The next
section discusses how the toolbox interprets image data, depending on the class
of the data array.
In addition to differences in the types of data values they store, uint8 arrays
and double arrays differ in the operations that MATLAB supports. See page
1-13 for information about the operations MATLAB supports for uint8 arrays.
1-4
www.MatlabSite.com
Image Types in the Toolbox
Ima ge Types in the Toolbox
The Image Processing Toolbox supports four basic types of images:
• Indexed images
• Intensity images
• Binary images
• RGB images
This section discusses how MATLAB and the Image Processing Toolbox
represent each of these image types.
Index ed Im a ges
An indexed image consists of two arrays, an image matrix and a colormap. The
colormap is an ordered set of values that represent the colors in the image. For
each image pixel, the image matrix contains a value that is an index into the
colormap.
The colormap is an m-by-3 matrix of class double. Each row of the colormap
matrix specifies the red, green, and blue (RGB) values for a single color:
color = [R G B]
R, G, and B are real scalars that range from 0 (black) to 1.0 (full intensity).
www.MatlabSite.com
1-5
1
Introduction
The figure below illustrates the structure of an indexed image. The pixels in
the image are represented by integers, which are pointers (indices) to color
values stored in the colormap.
75 10 12 21 40 53 53
75 14 17 21 21 53 53
75
8
5
8 10 30 15
51 15 18 31 31 18 16
56 31 18 31 31 31 31
0
0.0627
0.2902
0
0.2902
0.3882
0.4510
0.2588
0
0.0627
0.0314
0
0.0627
0.0314
0.0627
0.1608
.
.
.
0
0.0314
0
1.0000
0.0627
0.0941
0
0.0627
The relationship between the values in the image matrix and the colormap
depends on whether the image matrix is of class double or uint8. If the image
matrix is of class double, the value 1 points to the first row in the colormap, the
value 2 points to the second row, and so on. If the image matrix is of class
uint8, there is an offset; the value 0 points to the first row in the colormap, the
value 1 points to the second row, and so on. The uint8 convention is also used
in graphics file formats, and enables 8-bit indexed images to support up to 256
colors. In the image above, the image matrix is of class double, so there is no
offset. For example, the value 5 points to the fifth row of the colormap.
Intensity Im a ges
MATLAB stores an intensity image as a single matrix, with each element of the
matrix corresponding to one image pixel. The matrix can be of class double, in
which case it contains values in the range [0,1], or of class uint8, in which case
the data range is [0,255]. The elements in the intensity matrix represent
various intensities, or gray levels, where the intensity 0 represents black and
the intensity 1 (or 255) represents full intensity, or white.
1-6
www.MatlabSite.com
Image Types in the Toolbox
This figure depicts an intensity image of class double.
0.5342
0.5342
0.5342
0.4308
0.4510
0.2051
0.2251
0.1789
0.2483
0.3344
0.2157
0.2563
0.1307
0.2624
0.2624
0.2826
0.2826
0.1789
0.3344
0.3344
0.3822
0.2826
0.2051
0.3344
0.3344
0.4391
0.4391
0.3256
0.2624
0.3344
0.4391
0.4391
0.2483
0.2549
0.3344
Bina r y Im a ges
In a binary image, each pixel assumes one of only two discrete values.
Essentially, these two values correspond to on and off. A binary image is
stored as a two-dimensional matrix of 0’s (off pixels) and 1’s (on pixels).
A binary image can be considered a special kind of intensity image, containing
only black and white. Other interpretations are possible, however; you can also
think of a binary image as an indexed image with only two colors.
A binary image can be stored in an array of class double or uint8. However, a
uint8 array is preferable, because it uses far less memory. In the Image
Processing Toolbox, any function that returns a binary image returns it as a
uint8 logical array. The toolbox uses the presence of the logical flag to signify
that the data range is [0,1]. (If the logical flag is off, the toolbox assumes the
data range is [0,255].)
www.MatlabSite.com
1-7
1
Introduction
This figure shows an example of a binary image.
1
0
0
0
0
0
1
0
1
0
0
0
0
0
1
0
1
0
0
0
0
0
1
0
0
0
1
0
0
1
0
0
0
0
0
1
0
1
0
0
0
0
0
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
RGB Im a ges
Like an indexed image, an RGB image represents each pixel color as a set of
three values, representing the red, green, and blue intensities that make up
the color. Unlike an indexed image, however, these intensity values are stored
directly in the image array, not indirectly in a colormap.
In MATLAB, the red, green, and blue components of an RGB image reside in a
single m-by-n-by-3 array. m and n are the numbers of rows and columns of pixels
in the image, and the third dimension consists of three planes, containing red,
green, and blue intensity values. For each pixel in the image, the red, green,
and blue elements combine to create the pixel’s actual color.
For example, to determine the color of the pixel (112,86), look at the RGB
triplet stored in (112,86,1:3). Suppose (112,86,1) contains the value 0.1238,
(112,86,2) contains 0.9874, and (112,86,3) contains 0.2543. The color for the
pixel at (112,86) is:
0.1238 0.9874 0.2543
1-8
www.MatlabSite.com
Image Types in the Toolbox
An RGB array can be of class double, in which case it contains values in the
range [0,1], or of class uint8, in which case the data range is [0,255]. The figure
below shows an RGB image of class double:
0.5804 0.2235 0.1294 0.2902
Blue 0.4196 0.4824 0.4824
0.5804 0.2902 0.0627 0.2902 0.2902 0.4824 0.4824
0.5804 0.0627 0.0627 0.0627 0.2235 0.2588 0.2588
0.5176
0.2588
0.0627
0.0941
0.0941
0.0627
0.0627
0.5176
0.1922
0.0627
0.1294
0.1922
0.2588
0.2588
Green
0.4510
0.0941
0.0627
0.0941
0.0941
0.0941
0.0941
0.5176
0.1294
0.1608
0.1294
0.1294
0.2588
0.2588
0.5176 0.1608 0.0627 0.1608 0.1922 0.2588 0.2588
0.4196
0.2588
0.3529
0.4196
0.4196
0.3529
0.2902
0.5490
0.2235
0.5490
0.5804
0.7412
0.7765
0.7765
Red
0.4510
0.4196
0.3529
0.4196
0.4196
0.4196
0.4196
0.5490
0.3882
0.5176
0.5804
0.5804
0.7765
0.7765
0.5490 0.2588 0.2902 0.2588 0.2235 0.4824 0.2235
0.4196 0.2235 0.1608 0.2588 0.2588 0.1608 0.2588
0.4510 0.2588 0.1608 0.2588 0.2588 0.2588 0.2588
M ultifra m e Im a ge Arra y s
For some applications, you may need to work with collections of images related
by time or view, such as magnetic resonance imaging (MRI) slices or movie
frames.
The Image Processing Toolbox provides support for storing multiple images in
the same array. Each separate image is called a frame. If an array holds
multiple frames, they are concatenated along the fourth dimension. For
example, an array with five 400-by-300 RGB images would be
400-by-300-by-3-by-5. A similar multiframe intensity or indexed image would
be 400-by-300-by-1-by-5.
www.MatlabSite.com
1-9
1
Introduction
For example, if you have a group of images A1, A2, A3, A4, and A5, you can store
them in a single array using:
A = cat(4,A1,A2,A3,A4,A5)
You can also extract frames from a multiframe image. For example, if you have
a multiframe image MULTI, this command extracts the third frame:
FRM3 = MULTI(:,:,:,3)
Note that in a multiframe image array, each image must be the same size and
have the same number of planes. In a multiframe indexed image, each image
must also use the same colormap.
Limitations
Many of the functions in the toolbox operate only on the first two or first three
dimensions. You can still use four-dimensional arrays with these functions, but
you must process each frame individually. For example, this call displays the
seventh frame in the array MULTI:
imshow(MULTI(:,:,:,7))
If you pass an array to a function and the array has more dimensions than the
function is designed to operate on, your results may be unpredictable. In some
cases, the function will simply process the first frame of the array, but in other
cases the operation will not produce meaningful results.
See the reference entries in Chapter 11 for information about how individual
functions work with the dimensions of an image array. For more information
about displaying the images in a multiframe array, see Chapter 2.
1-10
www.MatlabSite.com
W orking w ith Image Data
W ork ing w ith Ima ge Da ta
This section discusses ways of working with the data arrays that represent
images, including:
• Reading in image data from files, and writing image data out to files
• Converting images to other image types
• Working with uint8 arrays in MATLAB and the Image Processing Toolbox
Rea ding a nd W riting Im a ges
You can use the MATLAB imread function to read image data from files.
imread can read these graphics file formats:
• BMP
• HDF
• JPEG
• PCX
• TIFF
• XWD
To write image data from MATLAB to a file, use the imwrite function. imwrite
can write the same file formats that imread reads.
In addition, you can use the imfinfo function to return information about the
image data in a file.
See the reference entries for imread, imwrite, and imfinfo in Chapter 11 for
more information about these functions.
Conver ting Im a ges to O ther Ty pes
For certain operations, it is helpful to convert an image to a different image
type. For example, if you want to filter a color image that is stored as an
indexed image, you should first convert it to RGB format. When you apply the
filter to the RGB image, MATLAB filters the intensity values in the image, as
is appropriate. If you attempt to filter the indexed image, MATLAB simply
applies the filter to the indices in the indexed image matrix, and the results
may not be meaningful.
www.MatlabSite.com
1-11
1
Introduction
The Image Processing Toolbox provides several functions that enable you to
convert any image to another image type. These functions have mnemonic
names; for example, ind2gray converts an indexed image to a grayscale
intensity format.
Note that when you convert an image from one format to another, the resulting
image may look different from the original. For example, if you convert a color
indexed image to an intensity image, the resulting image is grayscale, not
color. For more information about how these functions work, see their
reference entries in Chapter 11.
The table below summarizes these image conversion functions:
1-12
Function
Purpose
dither
Create a binary image from a grayscale intensity image
by dithering; create an indexed image from an RGB
image by dithering
gray2ind
Create an indexed image from a grayscale intensity
image
grayslice
Create an indexed image from a grayscale intensity
image by thresholding
im2bw
Create a binary image from an intensity image,
indexed image, or RGB image, based on a luminance
threshold
ind2gray
Create a grayscale intensity image from an indexed
image
ind2rgb
Create an RGB image from an indexed image
mat2gray
Create a grayscale intensity image from data in a
matrix, by scaling the data
rgb2gray
Create a grayscale intensity image from an RGB image
rgb2ind
Create an indexed image from an RGB image
www.MatlabSite.com
W orking w ith Image Data
You can also perform certain conversions just using MATLAB syntax. For
example, you can convert an intensity image to RGB format by concatenating
three copies of the original matrix along the third dimension:
RGB = cat(3,I,I,I);
The resulting RGB image has identical matrices for the red, green, and blue
planes, so the image displays as shades of gray.
In addition to these standard conversion tools, there are some functions that
return a different image type as part of the operation they perform. For
example, the region of interest routines each return a binary image that you
can use to mask an indexed or intensity image for filtering or for other
operations.
Color Space Conversions
The Image Processing Toolbox represents colors as RGB values, either directly
(in an RGB image) or indirectly (in an indexed image). However, there are
other methods for representing colors. For example, a color can be represented
by its hue, saturation, and value components (HSV). Different methods for
representing colors are called color spaces.
The toolbox provides a set of routines for converting between RGB and other
color spaces. The image processing functions themselves assume all color data
is RGB, but you can process an image that uses a different color space by first
converting it to RGB, and then converting the processed image back to the
original color space. For more information about color space conversion
routines, see Chapter 10.
W ork ing w ith uint8 Da ta
MATLAB provides limited support for operations on uint8 arrays. imread
reads images into MATLAB as uint8 arrays, and the image and imagesc
functions can display uint8 images.
MATLAB also supports these operations on uint8 arrays:
• Displaying data values
• Indexing into arrays using standard MATLAB subscripting
• Reshaping, reordering, and concatenating arrays, using functions such as
reshape, cat, and permute
www.MatlabSite.com
1-13
1
Introduction
• Saving to and loading from MAT-files
• The all and any functions
• Logical operators and indexing
• Relational operators
In addition, MATLAB supports the find function for uint8 arrays, but the
returned array is of class double.
Aside from the ones listed above, MATLAB does not support most operations
for uint8 arrays. In particular, mathematical operations are not supported. If
you attempt to perform an unsupported operation on a uint8 array, you receive
an error. For example:
BW3 = BW1 + BW2
??? Function '+' not defined for variables of class 'uint8'.
Most of the functions in the Image Processing Toolbox accept uint8 input. See
the reference entries in Chapter 11 for information about the individual
functions.
Converting Betw een Data Types
If you want to perform operations that are not supported for uint8 arrays,
convert the data to double precision using the double function. For example:
BW3 = double(BW1) + double(BW2);
Keep in mind that converting between data types changes the way MATLAB
and the toolbox interpret the image data. If you want the resulting array to be
interpreted properly as image data, you need to rescale or offset the data when
you convert it.
The toolbox has two functions, im2double and im2uint8, for converting images
from one data type to another. These functions automatically handle the
rescaling and offsetting of the original data. For example, this command
converts a double-precision RGB image with data in the range [0,1] to a uint8
RGB image with data in the range [0,255]:
RGB2 = im2uint8(RGB1);
To convert an indexed image, the input to the conversion function is the image
matrix, not the colormap. Colormaps are always of class double in MATLAB.
1-14
www.MatlabSite.com
W orking w ith Image Data
Also, an indexed image cannot be converted from double to uint8 if the image
matrix contains values greater than 256.
For more information about im2double and im2uint8, see the reference entries
for those functions in Chapter 11.
Turning the Logical Flag on or off
As discussed on page 1-7, a uint8 binary image must have its logical flag on. If
you use im2uint8 to convert a binary image of type double to uint8, this flag
is turned on automatically. If you do the conversion manually, however, you
must use the logical function to turn on the logical flag. For example:
B = logical(uint8(round(A)));
To turn the logical flag off, you can use the unary plus operator. For example,
if A is a uint8 logical array:
B = +A;
www.MatlabSite.com
1-15
1
Introduction
Coordina te Systems
Locations in an image can be expressed in various coordinate systems,
depending on context. This section discusses the two main coordinate systems
used in the Image Processing Toolbox, and the relationship between them.
These systems are:
• The pixel coordinate system
• The spatial coordinate system
Pix el Coordina tes
Generally, the most convenient method for expressing locations in an image is
to use pixel coordinates. In this coordinate system, the image is treated as a
grid of discrete elements, ordered from top to bottom and left to right. For
example:
1
2
3
c
1
2
3
r
For pixel coordinates, the first component r (the row) increases downward,
while the second component c (the column) increases to the right. Pixel
coordinates are integer values and range between 1 and the length of the row
or column.
There is a one-to-one correspondence between pixel coordinates and the
coordinates MATLAB uses for matrix subscripting. This correspondence
makes the relationship between an image’s data matrix and the way the image
displays easy to understand. For example, the data for the pixel in the fifth
row, second column is stored in the matrix element (5,2).
1-16
www.MatlabSite.com
C oordinate Systems
Spa tia l Coordina tes
In the pixel coordinate system, a pixel is treated as a discrete unit, uniquely
identified by a single coordinate pair, such as (5,2). From this perspective, a
location such as (5.3,2.2) is not meaningful.
At times, however, it is useful to think of a pixel as a square patch, having area.
From this perspective, a location such as (5.3,2.2) is meaningful, and is distinct
from (5,2). In this spatial coordinate system, locations in an image are positions
on a plane, and they are described in terms of x and y.
This figure illustrates the spatial coordinate system used for images. Notice
that y increases downward:
0.5
0.5
1
1.5
2
2.5
3
3.5
x
1
1.5
2
2.5
3
3.5
y
This spatial coordinate system corresponds quite closely to the pixel coordinate
system in many ways. For example, the spatial coordinates of the center point
of any pixel are identical to the pixel coordinates for that pixel.
There are some important differences, however. In pixel coordinates, the
upper-left corner of an image is (1,1), while in spatial coordinates, this location
by default is (0.5,0.5). This difference is due to the pixel coordinate system
being discrete, while the spatial coordinate system is continuous. Also, the
upper-left corner is always (1,1) in pixel coordinates, but you can specify a
nondefault origin for the spatial coordinate system. See “Using a Nondefault
Spatial Coordinate System” on page 1-18 for more information.
Another potentially confusing difference is largely a matter of convention: the
order of the horizontal and vertical components is reversed in the notation for
these two systems. Pixel coordinates are expressed as (r,c), while spatial
coordinates are expressed as (x,y). In the reference entries in Chapter 11, when
www.MatlabSite.com
1-17
1
Introduction
the syntax for a function uses r and c, it refers to the pixel coordinate system.
When the syntax uses x and y, it refers to the spatial coordinate system.
Using a N ondefault Spatial Coordinate System
By default, the spatial coordinates of an image correspond with the pixel
coordinates. For example, the center point of the pixel in row 5, column 3 has
spatial coordinates x=3, y=5. (Remember, the order of the coordinates is
reversed.) This correspondence simplifies many of the toolbox functions
considerably. Several functions primarily work with spatial coordinates rather
than pixel coordinates, but as long as you are using the default spatial
coordinate system, you can specify locations in pixel coordinates.
In some situations, however, you may want to use a nondefault spatial
coordinate system. For example, you could specify that the upper-left corner of
an image is the point (19.0,7.5), rather than (0.5,0.5). If you call a function that
returns coordinates for this image, the coordinates returned will be values in
this nondefault spatial coordinate system.
To establish a nondefault spatial coordinate system, you can specify the XData
and YData image properties when you display the image. These properties are
two-element vectors that control the range of coordinates spanned by the
image. By default, for an image A, XData is [1 size(A,2)], and YData is
[1 size(A,1)].
For example, if A is a 100 row by 200 column image, the default XData is
[1 200], and the default YData is [1 100]. The values in these vectors are
actually the coordinates for the center points of the first and last pixels (not the
pixel edges), so the actual coordinate range spanned is slightly larger; for
instance, if XData is [1 200], the x-axis range spanned by the image is
[0.5 200.5].
1-18
www.MatlabSite.com
C oordinate Systems
These commands display an image using nondefault XData and YData:
A = magic(5);
x = [19.5 23.5];
y = [8.0 12.0];
image(A,'XData',x,'YData',y), axis image, colormap(jet(25))
See the reference entries in Chapter 11 for information about functions in the
Image Processing Toolbox that can establish nondefault spatial coordinate
systems.
www.MatlabSite.com
1-19
1
Introduction
1-20
www.MatlabSite.com
2
Displaying Images
Overview
. . . . . . . . . . . . . . . . . . . . . 2-2
Standard Display Techniques . . . . . . .
Displaying Images with imshow . . . . . . .
Displaying Indexed Images . . . . . . . . .
Displaying Intensity Images . . . . . . . . .
Displaying Binary Images . . . . . . . . . .
Displaying RGB Images . . . . . . . . . . .
Displaying Images in Graphics Files . . . . . .
Displaying Nonimage Data as an Intensity Image
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
2-3
2-3
2-5
2-5
2-6
2-7
2-8
2-8
Special Display Techniques . . .
Adding a Colorbar . . . . . . . .
Displaying Multiframe Image Arrays
Displaying Multiple Images . . . .
Zooming in on a Region of an Image .
Texture Mapping . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
2-10
2-10
2-11
2-14
2-16
2-17
Printing Images
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. . . . . . . . . . . . . . . . . . 2-19
www.MatlabSite.com
2
Displaying Images
O verview
The Image Processing Toolbox supports a number of image display techniques.
For example, the function imshow displays any image type with a single
function call. Other functions handle more specialized display needs. This
chapter describes basic display techniques and discusses topics such as
multiple image display and texture mapping. In addition, it includes
information about printing images.
2-2
www.MatlabSite.com
Standard Display Techniques
Sta nda rd Displa y Techniques
In MATLAB, the primary way to display images is by using the image function.
This function creates a Handle Graphics® image object, and it includes syntax
for setting the various properties of the object. MATLAB also includes the
imagesc function, which is similar to image but which automatically scales the
input data.
The Image Processing Toolbox includes an additional display routine, imshow.
Like image and imagesc, this function creates a Handle Graphics image object.
However, imshow also automatically sets various Handle Graphics properties
and attributes of the image to optimize the display.
This section discusses displaying images using imshow. In general, imshow is
preferable to image and imagesc for image processing applications. For
information about image and imagesc, see the online MATLAB Function
Reference. These functions are also described in more detail in the Using
MATLAB Graphics manual.
Displa y ing Im a ges w ith im show
When you display an image using the imshow function, MATLAB sets figure,
axes, and image properties that control the way image data is interpreted.
These properties include the image CData and CDataMapping property, the axes
CLim property, and the figure Colormap property. In addition, depending on the
arguments you specify and the settings of toolbox preferences, imshow may
also:
• Set other figure and axes properties to tailor the display. For example, axes
and tick marks may not display.
• Include or omit a border around the image.
• Call the truesize function to display the image without interpolation.
This section describes how you can control the behavior of imshow. The sections
that follow it discuss how imshow displays specific image types.
Preferences
The Image Processing Toolbox includes a function, iptsetpref, that you can
use to set preferences that affect the behavior of imshow:
www.MatlabSite.com
2-3
2
Displaying Images
• The ImshowBorder preference controls whether imshow leaves a border
between the axes containing the image and the edges of the figure.
• The ImshowAxesVisible preference controls whether imshow displays
images with the axes box and tick labels.
• The ImshowTruesize preference controls whether imshow calls the truesize
function.
To determine the current value of a preference, use the iptgetpref function.
For more information about these and other toolbox preferences, and the
values they accept, see the reference entries for iptsetpref and iptgetpref in
Chapter 11.
The truesize Function
The truesize function assigns a single screen pixel to each image pixel. This
is generally the preferred way to display an image.
If you display an image without calling truesize, the image displays at the
default axis size; MATLAB must use interpolation to determine the values for
display pixels that do not correspond to elements in the image matrix. (See
Chapter 3 for a discussion of interpolation.)
In most situations, the imshow command calls truesize automatically. If you
do not want imshow to call truesize (for example, if you display an image with
a small number of pixels), you can set the ImshowTruesize preference to
'manual'. For example:
iptsetpref('ImshowTruesize','manual')
You can also override the setting of the ImshowTruesize preference for a single
imshow command. For example, this command prevents imshow from calling
truesize, regardless of the preference setting:
imshow(X,map,'notruesize')
For more information about the imshow and truesize functions, see the
reference entries for those functions in Chapter 11.
2-4
www.MatlabSite.com
Standard Display Techniques
Displa y ing Index ed Im a ges
To display an indexed image with imshow, you specify both the image matrix
and the colormap:
imshow(X,map)
For each pixel in X, imshow displays the color stored in the corresponding row
of map. imshow sets the Handle Graphics properties that control how colors
display:
• The image CData is set to the data in X.
• The image CDataMapping property is set to direct.
• The axes CLim property does not apply, because CDataMapping is set to
direct.
• The figure Colormap property is set to the data in map.
The relationship between the values in the image matrix and the colormap
depends on whether the image matrix is of class double or uint8. If the image
matrix is of class double, the value 1 points to the first row in the colormap, the
value 2 points to the second row, and so on. If the image matrix is of class
uint8, there is an offset; the value 0 points to the first row in the colormap, the
value 1 points to the second row, and so on. The offset is handled automatically
by the image object, and is not controlled through a Handle Graphics property.
Displa y ing Intensity Im a ges
To display a grayscale intensity image, the syntax is:
imshow(I)
imshow displays the image by scaling the intensity values to serve as indices
into a grayscale colormap. This is done as follows:
• The image CData is set to the data in the image matrix.
• The image CDataMapping property is set to scaled.
• The axes CLim property is set to [0 1] if the image matrix is of class double,
or [0 255] if the image matrix is of class uint8.
• The figure Colormap property is set to a grayscale colormap whose values
range from black to white.
www.MatlabSite.com
2-5
2
Displaying Images
By default, the number of levels of gray in the colormap is 256 on systems with
24-bit color, and 64 on other systems.
You can explicitly specify the number of gray levels with imshow. For example,
you can display an image I with 32 gray levels using:
imshow(I,32)
Note that this is not equivalent to:
imshow(I,gray(32))
If you use the latter syntax, imshow interprets the values in I as indices into a
colormap and therefore does not set CDataMapping to scaled.
Because MATLAB scales intensity images to fill the colormap range, you can
use any size colormap. Larger colormaps allow you to see more detail, but they
also use up more color slots. For information about the number of color slots
available on your system, see page 2-14.
Displa y ing Bina r y Im a ges
To display a binary image, the syntax is:
imshow(BW)
If the image matrix is of class double, imshow treats a binary image as an
intensity image, setting CDataMapping to scaled, CLim to [0 1], and Colormap
to a grayscale colormap. This means that the 0 values in the image matrix
display as black, and the 1 values display as white.
If the image matrix is of class uint8, the behavior depends on whether or not
the matrix has its logical flag on:
• If the logical flag is off, imshow treats the matrix as a uint8 intensity image,
setting CLim to [0 255].
• If the logical flag is on, imshow sets CLim to [0 1].
In general, this means that a uint8 binary image must have its logical flag on
to display properly. Therefore, all of the toolbox routines that return binary
images return them as uint8 logical matrices.
imread reads in an image as a uint8 logical array of 0’s and 1’s only if the image
is stored in the file with 1 bit per pixel. If a binary image is stored in a file with
2-6
www.MatlabSite.com
Standard Display Techniques
4 or 8 bits per pixel, imread interprets this as a grayscale intensity image; the
resulting array has values of 0 and 255, and the logical flag is off. You can
convert this image to a uint8 logical array using the NOT EQUAL (~=)
operator in MATLAB:
BW2 = BW ~= 0;
Changing the Display Colors
You may prefer to invert binary images when you display them, so that 0
values display as white and 1 values display as black. To do this, use the NOT
(~) operator in MATLAB. For example:
imshow(~BW)
You can also display a binary image using a colormap. If the image is of class
uint8, the 0 values display as the first color in the colormap, and the 1 values
display as the second color. For example, the following command displays 0 as
red and 1 as blue:
imshow(BW,[1 0 0; 0 0 1])
If the image is of class double, you need to add 1 to each value in the image
matrix, because there is no offset in the colormap indexing:
imshow(BW + 1,[1 0 0; 0 0 1])
Displa y ing RGB Im a ges
RGB images, also called truecolor images, represent color values directly,
rather than through a colormap.
To display an RGB image, the syntax is:
imshow(RGB)
RGB is m-by-n-by-3 array. For each pixel (r,c) in RGB, imshow displays the color
represented by the triplet (r,c,1:3).
As with other image types, MATLAB sets the image CData to the data in the
image array. However, in this case CData is a three-dimensional array, rather
than a two-dimensional matrix. If CData is three-dimensional, MATLAB
interprets the array as truecolor data, and ignores the values of the
CDataMapping, CLim, and Colormap properties.
www.MatlabSite.com
2-7
2
Displaying Images
An RGB image array can be of class double, in which case it contains values in
the range [0,1], or of class uint8, in which case the data range is [0,255].
Systems that use 24 bits per screen pixel can display truecolor images directly,
because they allocate 8 bits (256 levels) each to the red, green, and blue color
planes. On systems with fewer colors, MATLAB displays the image using a
combination of color approximation and dithering. See Chapter 10 for more
information.
Displa y ing Im a ges in Gra phics Files
Generally, when you display an image, the image data is stored as one or more
variables in the MATLAB workspace. However, if you have an image stored in
a graphics file that imread can read, you can display a file directly using this
syntax:
imshow filename
The file must be in the current directory or on the MATLAB path.
For example, to display a file named flowers.tif:
imshow flowers.tif
This syntax is very useful for scanning through images stored in graphics files.
Note, however, that when you use this syntax, the image data is not stored in
the MATLAB workspace; if you want to process the image, you need to use
imread to read in the data, or else use getimage to get the image data from the
Handle Graphics image object. Also, if you use this syntax with a file
containing more than one image, imshow displays only the first image.
Displa y ing N onim a ge Da ta a s a n Intensity Im a ge
In some cases, you may have data you want to display as an intensity image,
even though the data is outside the appropriate range (i.e., [0,1] for double
arrays or [0,255] for uint8 arrays). For example, if you filter an intensity
image, the output data may not fall in the range of the original data, but you
may still want to display the results as an image.
To display this data as an image, you can specify the data range directly, using:
imshow(I,[low high])
2-8
www.MatlabSite.com
Standard Display Techniques
When you use this syntax, imshow sets the axes CLim property to [low high].
CDataMapping is always scaled for intensity images, so the image data is
scaled so that low corresponds to the first row of the grayscale colormap and
high corresponds to the last row.
If you use an empty matrix ([]) for the data range, imshow scales the data
automatically, setting low and high to the minimum and maximum values in
the array. For example:
I = imread('testpat1.tif');
J = filter2([1 2;–1 –2],I);
imshow(J,[])
www.MatlabSite.com
2-9
2
Displaying Images
Specia l Displa y Techniques
In addition to imshow, the toolbox includes functions that perform specialized
display operations, or exercise more direct control over the display format.
These functions, together with the MATLAB graphics functions, provide a
range of image display options.
This section includes the following topics:
• Adding a colorbar to an image display
• Displaying multiframe image arrays
• Displaying multiple images
• Zooming in on a region of an image
• Texture mapping an image onto a surface
Adding a Colorba r
You can use the colorbar function to add a colorbar to an axes object. If you
add a colorbar to an axes object that contains an image object, the colorbar
indicates the data values that the different colors in the image correspond to.
Seeing the correspondence between data values and the colors displayed is
especially useful if you are displaying nonimage data as an image, as described
2-10
www.MatlabSite.com
Special Display Techniques
on page 2-8. In the example below, you filter a grayscale image of class uint8,
and the resulting data is no longer in the range [0,255]:
I = imread('saturn.tif');
h = [1 2 1; 0 0 0; –1 –2 –1];
I2 = filter2(h,I);
imshow(I2,[]), colorbar
Displa y ing M ultifra m e Im a ge Arra y s
To view the images in a multiframe array, you can use any of these options:
• Display the frames individually, using the imshow function
• Display all of the frames at once, using the montage function
• Convert the array to a MATLAB movie, using the immovie function
Displaying Frames Individually
To view an individual frame, call imshow and specify the frame using standard
MATLAB indexing notation. For example, to view the seventh frame in the
intensity array I:
imshow(I(:,:,:,7))
www.MatlabSite.com
2-11
2
Displaying Images
Displaying All Frames at O nce
To view all of the frames in a multiframe array at one time, use the montage
function. montage divides a figure into multiple display regions and displays
each image in a separate region.
The syntax for montage is similar to the imshow syntax. To display a
multiframe intensity image, the syntax is:
montage(I)
To display a multiframe indexed image, the syntax is:
montage(X,map)
Note that all of the frames in a multiframe indexed array must use the same
colormap.
The commands below display a multiframe image array. Notice that montage
displays images in a row-wise manner. The first frame appears in the first
2-12
www.MatlabSite.com
Special Display Techniques
position of the first row, the next frame in the second position of the first row,
and so on. montage arranges the frames so that they roughly form a square.
load mri
montage(D,map)
Converting the Array to a M ovie
To create a MATLAB movie from a multiframe image array, use the immovie
function. This function works only with indexed images; if you want to convert
another type of image array to a movie, you must first convert it to an indexed
image, using one of the conversion functions described in Chapter 1.
This call creates a movie from the multiframe indexed image shown above:
mov = immovie(D,map);
www.MatlabSite.com
2-13
2
Displaying Images
You can play the movie in MATLAB using the movie function:
movie(mov)
Note that when you play the movie, you need to supply the colormap used by
the original image array. For example:
mov = immovie(D,map);
colormap(map), movie(mov)
Displa y ing M ultiple Im a ges
MATLAB does not place any restrictions on the number of images you can
display simultaneously. However, there are usually system limitations that
are dependent on the computer hardware you are using.
The main limitation is the number of colors your system can display. This
number depends primarily on the number of bits that are used to store the color
information for each pixel. Most systems use either 8, 16, or 24 bits per pixel.
If you are using a system with 16 or 24 bits per pixel, you are unlikely to run
into any problems, regardless of the number of images you display. However,
if your system uses 8 bits per pixel, it can display a maximum of 256 different
colors, so you can quickly run out of color slots if you display multiple images.
(Actually, the total number of colors you can display is slightly fewer than 256,
because some color slots are reserved for Handle Graphics objects. The
operating system usually reserves a few colors as well.)
To determine the number of bits per pixel on your system, enter this command:
get(0,'ScreenDepth')
See Chapter 10 for more information about working with different color depths.
This section discusses methods you can use to display multiple images at the
same time, and includes information about working around system limitations.
This section discusses:
• Displaying each image in a separate figure
• Displaying multiple images in the same figure
Displaying Each Image in a Separate Figure
The simplest way to display multiple images is to display them in different
figure windows. imshow always displays in the current figure, so if you display
2-14
www.MatlabSite.com
Special Display Techniques
two images in succession, the second image replaces the first image. Therefore,
if you want to display two or more images in separate windows, you must
explicitly create a new empty figure before calling imshow for the second and
subsequent images. For example:
imshow(I)
figure, imshow(I2)
When you use this approach, the figures you create are empty initially, so the
images are displayed using truesize.
If you have an 8-bit display, you must make sure that the total number of
colormap entries does not exceed 256. For example, if you try to display three
images, each having a different colormap with 128 entries, at least one of the
images will display with the wrong colors. (If all three images use the same
colormap, there will not be a problem, because only 128 color slots are used.)
Note that intensity images are displayed using colormaps, so the color slots
used by these image count toward the 256-color total.
One way to avoid these display problems is to manipulate the colormaps to use
fewer colors. There are various ways to do this, such as using the imapprox
function. See Chapter 10 for information about reducing the number of colors
used by an image.
Another solution is to convert images to RGB (truecolor) format for display.
The colors used by truecolor images do not count toward the 256-color total,
because MATLAB automatically uses dithering and color approximation to
display these images.
For example, to display an indexed image as an RGB image:
imshow(ind2rgb(X,map))
To display an intensity image as an RGB image:
imshow(cat(3,I,I,I))
Displaying M ultiple Images in the Same Figure
You can display multiple images in a single figure window by using imshow in
conjunction with the subplot function. This function divides a figure into
multiple display regions. The syntax of subplot is:
subplot(m,n,p)
www.MatlabSite.com
2-15
2
Displaying Images
This call divides the figure into an m-by-n matrix of display regions and makes
the p-th display region active. For example, you can display two images side by
side using:
subplot(1,2,1), imshow(X1,map)
subplot(1,2,2), imshow(X2,map)
To display multiple images in the same figure with imshow, the images must
use the same colormap, as in the example above. If the colormaps differ, the
images will not display properly. This is because there is only one colormap for
a given figure, and this figure colormap is replaced each time you use imshow.
For example, if you display a second image in the figure, that image’s colormap
will become the figure colormap, and the first image will use it as well, even if
it is not appropriate.
To avoid this problem, the toolbox provides a function, subimage, that you can
use instead of imshow to display images in subplots. For example, to display two
images in the same figure:
subplot(1,2,1), subimage(X1,map1)
subplot(1,2,2), subimage(X2,map2)
Both images display correctly, even if they have different colormaps.
Generally, subimage converts the images to RGB format for display purposes.
Z oom ing in on a Region of a n Im a ge
The zoom command enables you to examine the details of an image by using the
mouse to zoom in or out. When you zoom in, the figure remains the same size,
but only a portion of the image is displayed, at a higher magnification. (zoom
works by changing the axis limits; it does not change the image data in the
figure.)
To turn zoom mode on, type:
zoom on
There are two ways to zoom in on an image:
2-16
www.MatlabSite.com
Special Display Techniques
• Click on a spot in the image by placing the cursor on the spot and the
pressing the left mouse button. The view changes automatically. The center
of the new view is the spot where you clicked.
• Select a region by clicking on the image, holding down the mouse button, and
dragging the mouse. A dotted rectangle appears. When you release the
mouse button, the region enclosed by the rectangle is displayed.
To zoom out, click on the image with the right mouse button. (If you have a
single-button mouse, hold down the Shift key and click.) To zoom out
completely and restore the original view, enter:
zoom out
To turn zoom mode off:
zoom off
Tex ture M a pping
When you use the imshow command, MATLAB displays the image in a
two-dimensional view. However, it is also possible to display an image on a
parametric surface, such as a sphere, or below a surface plot. The warp function
creates these displays by texture mapping the image. Texture mapping is a
process that maps an image onto a surface grid using bilinear interpolation.
www.MatlabSite.com
2-17
2
Displaying Images
This example texture maps an image of a test pattern onto a cylinder:
[x,y,z] = cylinder;
I = imread('testpat1.tif');
warp(x,y,z,I);
For more information about texture mapping, see the reference entry for the
warp function in Chapter 11.
2-18
www.MatlabSite.com
Printing Images
Printing Ima ges
If you want to output a MATLAB image to use it in another application (such
as a word-processing program or graphics editor), use imwrite to create a file
in the appropriate format.
If you want to print the contents of a MATLAB figure (including nonimage
elements such as labels), use the MATLAB print command, or choose the
Print option from the File menu of the figure window. If you produce output
this way, the results reflect the settings of various Handle Graphics properties.
In some cases, you may need to change the settings of certain properties to get
the results you want.
Here are some tips that may be helpful when you print images:
• Image colors print as shown on the screen. This means that images do not
obey the InvertHardcopy figure property.
• To ensure that printed images have the proper size and aspect ratio,
you should set the figure’s PaperPositionMode property to auto. When
PaperPositionMode is set to auto, the width and height of the printed figure
are determined by the figure’s dimensions on the screen. By default, the
value of PaperPositionMode is manual. If you want the default value of
PaperPositionMode to be auto, enter this line in your startup.m file:
set(0,'DefaultFigurePaperPositionMode','auto')
For more information about printing and about Handle Graphics, see the
Using MATLAB Graphics manual.
www.MatlabSite.com
2-19
2
Displaying Images
2-20
www.MatlabSite.com
3
Geometric Operations
Overview
. . . . . . . . . . . . . . . . . . . . . 3-2
Interpolation . . . . . . . . . . . . . . . . . . . 3-3
Image Types . . . . . . . . . . . . . . . . . . . . 3-4
Image Resizing . . . . . . . . . . . . . . . . . . . 3-5
Image Rotation . . . . . . . . . . . . . . . . . . . 3-6
Image Cropping
. . . . . . . . . . . . . . . . . . 3-7
www.MatlabSite.com
3
G eometric O perations
O verview
This chapter describes some basic image processing tools, the geometric
functions. These functions modify the geometry of an image by resizing,
rotating, or cropping the image. These functions support all image types.
The chapter begins with a discussion of interpolation, an operation common to
most of the geometric functions. It then discusses each of the geometric
functions separately, and shows how to apply them to sample images.
3-2
www.MatlabSite.com
Interpolation
Interpola tion
The imresize and imrotate geometric functions use two-dimensional
interpolation as part of the operations they perform. (The improfile image
analysis function also uses interpolation. See Chapter 7 for information about
this function.) Interpolation is the process by which the software resamples the
image data to determine values between defined pixels. For example, if you
resize an image so it contains more pixels than it did originally, the software
obtains values for the additional pixels through interpolation.
The Image Processing Toolbox provides three interpolation methods:
• Nearest neighbor interpolation
• Bilinear interpolation
• Bicubic interpolation
The interpolation methods all work in a fundamentally similar way. In each
case, to determine the value for an interpolated pixel, you find the point in the
input image that the output pixel corresponds to. You then assign a value to
the output pixel by computing a weighted average of some set of pixels in the
vicinity of the point. The weightings are based on the distance each pixel is
from the point.
The methods differ in the set of pixels that are considered:
• For nearest neighbor interpolation, the output pixel is assigned the value of
the pixel that the point falls within. No other pixels are considered.
• For bilinear interpolation, the output pixel value is a weighted average of
pixels in the nearest 2-by-2 neighborhood.
• For bicubic interpolation, the output pixel value is a weighted average of
pixels in the nearest 4-by-4 neighborhood.
The number of pixels considered affects the complexity of the computation.
Therefore the bilinear method takes longer than nearest neighbor
interpolation, and the bicubic method takes longer than bilinear. However, the
greater the number of pixels considered, the more accurate the effect is, so
there is a tradeoff between processing time and quality.
www.MatlabSite.com
3-3
3
G eometric O perations
Im a ge Ty pes
The functions that use interpolation take an argument that specifies the
interpolation method. For these functions, the default method is nearest
neighbor interpolation. This method produces acceptable results for all image
types, and is the only method that is appropriate for indexed images. For
intensity and RGB images, however, you should generally specify bilinear or
bicubic interpolation, because these methods produce better results than
nearest neighbor interpolation.
For RGB images, interpolation is performed on the red, green, and blue image
planes individually.
For binary images, interpolation has effects that you should be aware of. If you
use bilinear or bicubic interpolation, the computed values for the pixels in the
output image will not all be 0 or 1. The effect on the resulting output image
depends on the class of the input image:
• If the class of the input image is double, the output image is a grayscale
image of class double. The output image is not binary, because it includes
values other than 0 and 1.
• If the class of the input image is uint8, the output image is a binary image
of class uint8. The interpolated pixel values are rounded off to 0 and 1 so the
output image can be of class uint8.
If you use nearest neighbor interpolation, the result is always binary, because
the values of the interpolated pixels are taken directly from pixels in the input
image.
3-4
www.MatlabSite.com
Image Resizing
Ima ge Resizing
The toolbox function imresize changes the size of an image using a specified
interpolation method. If you do not specify an interpolation method, the
function uses nearest neighbor interpolation.
You can use imresize to resize an image by a specific magnification factor. To
enlarge an image, specify a factor greater than 1. For example, this command
doubles the number of pixels in X in each direction:
Y = imresize(X,2)
To reduce an image, specify a number between 0 and 1 as the magnification
factor.
You can also specify the actual size of the output image. This command creates
an output image of size 100-by-150:
Y = imresize(X,[100 150])
If the specified size does not produce the same aspect ratio as the input image
has, the output image will be distorted.
If you reduce the image size and use bilinear or bicubic interpolation, imresize
applies a lowpass filter to the image before interpolation. This reduces the
effect of Moiré patterns, ripple patterns that result from aliasing during
resampling. Note, however, that even with lowpass filtering, the resizing
operation can introduce artifacts, because information is always lost when you
reduce the size of an image.
imresize does not apply a lowpass filter if nearest neighbor interpolation is
used, unless you explicitly specify the filter. This interpolation method is
primarily used for indexed images, and lowpass filtering is not appropriate for
these images.
For information about specifying a different filter, see the reference entry for
imresize in Chapter 11.
www.MatlabSite.com
3-5
3
G eometric O perations
Ima ge Rota tion
The imrotate function rotates an image, using a specified interpolation
method and rotation angle. If you do not specify an interpolation method, the
function uses nearest neighbor interpolation.
You specify the rotation angle in degrees. If you specify a positive value,
imrotate rotates the image counterclockwise; if you specify a negative value,
imrotate rotates the image clockwise.
For example, these commands rotate an image 35˚ counterclockwise:
I = imread('ic.tif');
J = imrotate(I,35,'bilinear');
imshow(I)
figure, imshow(J)
Notice that the resulting image is larger than the input image, in order to
include the entire original image. imrotate adds 0’s to the image to fill the area
outside the original image.
imrotate has an option for cropping the output image to the same size as the
input image. See the reference entry for imrotate in Chapter 11 for more
information.
3-6
www.MatlabSite.com
Image C ropping
Ima ge Cropping
The function imcrop extracts a rectangular portion of an image. You can
specify the crop rectangle through input arguments, or select it with a mouse.
If you call imcrop without specifying the crop rectangle, the cursor changes to
a cross hair when it is over the image. Click on one corner of the region you
want to select, and while holding down the mouse button, drag across the
image. imcrop draws a rectangle around the area you are selecting. When you
release the mouse button, imcrop creates a new image from the selected region.
In this example, you display an image and call imcrop. The rectangle you select
is shown in red.
imshow ic.tif
I = imcrop;
Now display the cropped image:
imshow(I)
If you do not provide any output arguments, imcrop displays the image in a
new figure.
www.MatlabSite.com
3-7
3
G eometric O perations
3-8
www.MatlabSite.com
4
Neighborhood and Block
Operations
Overview . . . . . . . . . . . . . . . . . . . . . 4-2
Types of Block Processing Operations . . . . . . . . . . 4-2
Sliding Neighborhood Operations . . . . . . . . . . 4-4
Padding of Borders . . . . . . . . . . . . . . . . . . 4-5
Linear and Nonlinear Filtering . . . . . . . . . . . . . 4-5
Distinct Block Operations . . . . . . . . . . . . . . 4-8
Overlap . . . . . . . . . . . . . . . . . . . . . . 4-9
Column Processing . . . . . . . . . . . . . . . . . 4-11
Sliding Neighborhoods . . . . . . . . . . . . . . . . 4-11
Distinct Blocks . . . . . . . . . . . . . . . . . . . 4-12
www.MatlabSite.com
4
N eighborhood and Block O perations
O verview
Certain image processing operations involve processing an image in sections
called blocks, rather than processing the entire image at once. For example,
many linear filtering operations and binary image operations work this way.
The Image Processing Toolbox provides several functions for specific
operations that work with blocks; for example, the dilate function for binary
image dilation. In addition, the toolbox provides more generic functions for
processing an image in blocks. This chapter discusses these generic block
processing functions.
To use one of the functions described in this chapter, you supply information
about the size of the blocks, and specify a separate function to use to process
the blocks. The block processing function does the work of breaking the input
image into blocks, calling the specified function for each block, and
reassembling the results into an output image.
Ty pes of Block Processing O pera tions
Using these functions, you can perform various block processing operations,
including sliding neighborhood operations and distinct block operations:
• In a sliding neighborhood operation, the input image is processed in a
pixelwise fashion. That is, for each pixel in the input image, some operation
is performed to determine the value of the corresponding pixel in the output
image. The operation is based on the values of a block of neighboring pixels.
• In a distinct block operation, the input image is processed a block at a time.
That is, the image is divided into rectangular blocks, and some operation is
performed on each block individually to determine the values of the pixels in
the corresponding block of the output image.
In addition, the toolbox provides functions for column processing operations.
These operations are not actually distinct from block operations; instead, they
are a way of speeding up block operations by rearranging blocks into matrix
columns.
Note that even if you do not use the block processing functions described in this
chapter, the information here may be useful to you, as it includes concepts
fundamental to many areas of image processing. In particular, the discussion
of sliding neighborhood operations is applicable to linear filtering and binary
4-2
www.MatlabSite.com
O verview
morphological operations. See Chapter 5 and Chapter 8 for information about
these applications.
www.MatlabSite.com
4-3
4
N eighborhood and Block O perations
Sliding N eighborhood O pera tions
A sliding neighborhood operation is an operation that is performed a pixel at a
time, with the value of any given pixel in the output image being determined
by applying some algorithm to the values of the corresponding input pixel’s
neighborhood. A pixel’s neighborhood is some set of pixels, defined by their
locations relative to that pixel, which is called the center pixel. The
neighborhood is a rectangular block, and as you move from one element to the
next in an image matrix, the neighborhood block slides in the same direction.
The figure below shows the neighborhood blocks for some of the elements in a
6-by-5 matrix with 2-by-3 sliding blocks. The center pixel for each
neighborhood is marked with a dot.
The center pixel is the actual pixel in the input image being processed by the
operation. If the neighborhood has an odd number of rows and columns, the
center pixel is actually in the center of the neighborhood. If one of the
dimensions has even length, the center pixel is just to the left of center or just
above center. For example, in a 2-by-2 neighborhood, the center pixel is the
upper left one.
For any m-by-n neighborhood, the center pixel is:
floor(([m n]+1)/2)
In the 2-by-3 block shown in the figure above, the center pixel is (1,2), the pixel
in the second column of the top row of the neighborhood.
A sliding neighborhood operation proceeds like this:
4-4
www.MatlabSite.com
Sliding N eighborhood O perations
1 Select a single pixel.
2 Determine the pixel’s neighborhood.
3 Apply a function to the values of the pixels in the neighborhood. This
function must return a scalar.
4 Find the pixel in the output image whose position corresponds to that of the
center pixel in the input image. Set this output pixel to the value returned
by the function.
5 Repeat steps 1 through 4 for each pixel in the input image.
For example, suppose the figure above represents an averaging operation. The
function might sum the values of the six neighborhood pixels and then divide
by 6. The result is the value of the output pixel.
Pa dding of Borders
As the figure on page 4-4 shows, some of the pixels in a neighborhood may be
missing, especially if the center pixel is on the border of the image. Notice that
in the figure, the upper left and bottom right neighborhoods include “pixels”
that are not part of the image.
To process these neighborhoods, sliding neighborhood operations pad the
borders of the image, usually with 0’s. In other words, these functions process
the border pixels by assuming that the image is surrounded by additional rows
and columns of 0’s. These rows and columns do not become part of the output
image and are used only as parts of the neighborhoods of the actual pixels in
the image.
Linea r a nd N onlinea r Filtering
You can use sliding neighborhood operations to implement many kinds of
filtering operations. One example of a sliding neighbor operation is
convolution, which is used to implement linear filtering. MATLAB provides the
conv2 and filter2 functions for performing convolution. See Chapter 5 for
more information about these functions.
In addition to convolution, there are many other filtering operations you can
implement through sliding neighborhoods. Many of these operations are
nonlinear in nature. For example, you can implement a sliding neighborhood
www.MatlabSite.com
4-5
4
N eighborhood and Block O perations
operation where the value of an output pixel is equal to the standard deviation
of the values of the pixels in the input pixel’s neighborhood.
You can use the nlfilter function to implement a variety of sliding
neighborhood operations. nlfilter takes as input arguments an image, a
neighborhood size, and a function that returns a scalar, and returns an image
of the same size as the input image. The value of each pixel in the output image
is computed by passing the corresponding input pixel’s neighborhood to the
function. For example, this call computes each output pixel by taking the
standard deviation of the values of the input pixel’s 3-by-3 neighborhood (that
is, the pixel itself and its eight contiguous neighbors):
I2 = nlfilter(I,[3 3],'std2');
You can write an M-file to implement a specific function, and then use this
function with nlfilter. For example, this command processes the matrix I in
2-by-3 neighborhoods with a function called myfun.m:
nlfilter(I,[2 3],'myfun');
You can also use an inline function; in this case, the function name appears in
the nlfilter call without quotation marks. For example:
f = inline('sqrt(min(x(:)))');
I2 = nlfilter(I,[2 2],f);
4-6
www.MatlabSite.com
Sliding N eighborhood O perations
The example below uses nlfilter to set each pixel to the maximum value in
its 3-by-3 neighborhood:
I = imread('tire.tif');
f = inline('max(x(:))');
I2 = nlfilter(I,[3 3],f);
imshow(I)
figure, imshow(I2)
Many operations that nlfilter can implement run much faster if the
computations are performed on matrix columns rather than rectangular
neighborhoods. For information about this approach, see the discussion of the
colfilt function on page 4-11.
www.MatlabSite.com
4-7
4
N eighborhood and Block O perations
Distinct Block O pera tions
Distinct blocks are rectangular partitions that divide a matrix into m-by-n
sections. Distinct blocks overlay the image matrix starting in the upper-left
corner, with no overlap. If the blocks don’t fit exactly over the image, the
toolbox adds zero padding so that they do.
The figure below shows a 15-by-30 matrix divided into 4-by-8 blocks.
The zero padding process adds 0’s to the bottom and right of the image matrix,
as needed. After zero padding, the matrix is size 16-by-32.
The function blkproc performs distinct block operations. blkproc extracts
each distinct block from an image and passes it to a function you specify.
blkproc assembles the returned blocks to create an output image.
For example, the command below processes the matrix I in 4-by-6 blocks with
the function myfun.
I2 = blkproc(I,[4 6],'myfun');
You can specify the function as an inline function; in this case, the function
name appears in the blkproc call without quotation marks. For example:
f = inline('mean2(x)*ones(size(x))');
I2 = blkproc(I,[4 6],f);
4-8
www.MatlabSite.com
Distinct Block O perations
The example below uses blkproc to set every pixel in each 8-by-8 block of an
image matrix to the average of the elements in that block.
I = imread('tire.tif');
f = inline('uint8(round(mean2(x)*ones(size(x))))');
I2 = blkproc(I,[8 8],f);
imshow(I)
figure, imshow(I2);
Notice that the inline function computes the mean of the block and then
multiplies the result by a matrix of ones, so that the output block is the same
size as the input block. As a result, the output image is the same size as the
input image. blkproc does not require that the images be the same size;
however, if this is the result you want, you must make sure that the function
you specify returns blocks of the appropriate size.
O verla p
When you call blkproc, you can specify an overlap to the distinct blocks; that
is, extra rows and columns of pixels outside the block whose values are taken
into account when processing the block. When there is an overlap, blkproc
passes the expanded block (including the overlap) to the specified function.
www.MatlabSite.com
4-9
4
N eighborhood and Block O perations
The figure below shows two 4-by-8 blocks with a 1-by-2 overlap. Notice that
there is a 1-row overlap on each side of the block, and a 2-row overlap above
and below the block.
To specify the overlap, you provide an additional input argument to blkproc.
To process the blocks in the figure above with the function myfun, the call is:
B = blkproc(A,[4 8],[1 2],'myfun')
Overlap often increases the amount of zero padding needed. For example, in
the figure on page 4-8, the original 15-by-30 matrix becomes 16-by-32 with zero
padding. If a 1-by-2 overlap is used, the padded matrix is 18-by-36.
4-10
www.MatlabSite.com
C olumn Processing
Column Processing
The toolbox provides functions that you can use to process sliding
neighborhoods or distinct blocks as columns. This approach is useful for
operations that MATLAB performs columnwise; in many cases, column
processing can reduce the execution time required to process an image.
For example, suppose the operation you are performing involves computing the
mean of each block. This computation is much faster if you first rearrange the
blocks into columns, because you can compute the mean of every column with
a single call to the mean function, rather than calling mean for each block
individually.
You can use the colfilt function to implement column processing. This
function:
1 Reshapes each sliding or distinct block of an image matrix into a column in
a temporary matrix
2 Passes the temporary matrix to a function you specify
3 Rearranges the resulting matrix back into the original shape
Sliding N eighborhoods
For a sliding neighborhood operation, colfilt creates a temporary matrix that
has a separate column for each pixel in the original image. The column
corresponding to a given pixel contains the values of that pixel’s neighborhood
from the original image.
The figure below illustrates this process. In this figure, a 6-by-5 image matrix
is processed in 2-by-3 neighborhoods. colfilt creates one column for each
pixel in the image, so there are a total of 30 columns in the temporary matrix.
Each pixel’s column contains the value of the pixels in its neighborhood, so
there are six rows. colfilt zero pads the input image as necessary. For
www.MatlabSite.com
4-11
4
N eighborhood and Block O perations
example, the neighborhood of the upper left pixel in the figure has two
zero-valued neighbors, due to zero padding.
The temporary matrix is passed to a function, which must return a single value
for each column. (Many MATLAB functions work this way; for example, mean,
median, std, sum, etc.) The resulting values are then assigned to the
appropriate pixels in the output image.
colfilt can produce the same results as nlfilter with faster execution time;
however, it may use more memory. The example below sets each output pixel
to the maximum value in the input pixel’s neighborhood, producing the same
result as the nlfilter example on page 4-7. Notice that the function is max(x)
rather than max(x(:)), because each neighborhood in the original image is a
separate column in the temporary matrix.
f = inline('max(x)');
I2 = colfilt(I,[3 3],'sliding',f);
Distinct Block s
For a distinct block operation, colfilt creates a temporary matrix by
rearranging each block in the image into a column. colfilt pads the original
image with 0’s, if necessary, before creating the temporary matrix.
The figure below illustrates this process. In this figure, a 6-by-16 image matrix
is processed in 4-by-6 blocks. colfilt first zero pads the image to make the size
4-12
www.MatlabSite.com
C olumn Processing
8-by-18 (six 4-by-6 blocks), and then rearranges the blocks into 6 columns of 24
elements each.
After rearranging the image into a temporary matrix, colfilt passes this
matrix to the function. The function must return a matrix of the same size as
the temporary matrix. If the block size is m-by-n, and the image is mm-by-nn, the
size of the temporary matrix is (m*n)-by-(ceil(mm/m)*ceil(nn/n)). After the
function processes the temporary matrix, the output is rearranged back into
the shape of the original image matrix.
This example sets all the pixels in each 8-by-8 block of an image to the mean
pixel value for the block, producing the same result as the blkproc example on
page 4-9:
f = inline('ones(64,1)*mean(x)');
I2 = colfilt(I,[8 8],'distinct',f);
www.MatlabSite.com
4-13
4
N eighborhood and Block O perations
Notice that the inline function computes the mean of the block and then
multiplies the result by a vector of ones, so that the output block is the same
size as the input block. As a result, the output image is the same size as the
input image.
Restrictions
You can use colfilt to implement many of the same distinct block operations
that blkproc performs. However, colfilt has certain restrictions that
blkproc does not:
• The output image must be the same size as the input image.
• The blocks cannot overlap.
For situations that do not satisfy these constraints, use blkproc.
4-14
www.MatlabSite.com
5
Linear Filtering and Filter
Design
Overview
. . . . . . . . . . . . . . . . . . . . . 5-2
Linear Filtering . . . . . .
Convolution . . . . . . . . .
Padding of Borders . . . . . .
The filter2 Function . . . . .
Separability . . . . . . . . .
Higher-Dimensional Convolution
Using Predefined Filter Types .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
5-3
5-3
5-5
5-7
5-8
5-9
5-9
Filter Design . . . . . . . . . . . . . . .
FIR Filters . . . . . . . . . . . . . . . .
Frequency Transformation Method . . . . . .
Frequency Sampling Method . . . . . . . . .
Windowing Method . . . . . . . . . . . . .
Creating the Desired Frequency Response Matrix
Computing the Frequency Response of a Filter .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
5-13
5-13
5-14
5-15
5-16
5-18
5-19
www.MatlabSite.com
5
Linear Filtering and Filter Design
O verview
The Image Processing Toolbox provides a number of functions for designing
and implementing two-dimensional linear filters for image data. This chapter
describes these functions and how to use them effectively.
The material in this chapter is divided into two parts:
• The first part is an explanation of linear filtering and how it is implemented
in the toolbox. This topic describes filtering in terms of the spatial domain,
and is accessible to anyone doing image processing.
• The second part is a discussion about designing two-dimensional Finite
Infinite Response (FIR) filters. This section assumes you are familiar with
working in the frequency domain.
5-2
www.MatlabSite.com
Linear Filtering
Linea r Filtering
Filtering is a technique for modifying or enhancing an image. For example, you
can filter an image to emphasize certain features or remove other features.
Filtering is a neighborhood operation, in which the value of any given pixel in
the output image is determined by applying some algorithm to the values of the
pixels in the neighborhood of the corresponding input pixel. A pixel’s
neighborhood is some set of pixels, defined by their locations relative to that
pixel. (For a general discussion of neighborhood operations, see Chapter 4.)
Linear filtering is filtering in which the value of an output pixel is a linear
combination of the values of the pixels in the input pixel’s neighborhood. For
example, an algorithm that computes a weighted average of the neighborhood
pixels is one type of linear filtering operation.
This section discusses linear filtering in MATLAB and the Image Processing
Toolbox. It includes:
• A description of how MATLAB performs linear filtering, using convolution
• A discussion about using predefined filter types
For information about how to design filters, see page 5-13.
Convolution
In MATLAB, linear filtering of images is implemented through
two-dimensional convolution. In convolution, the value of an output pixel is
computed by multiplying elements of two matrices and summing the results.
One of these matrices represents the image itself, while the other matrix is the
filter. For example, a filter might be:
k = [4 –3
4 6
1
2]
This filter representation is known as a convolution kernel. The MATLAB
function conv2 implements image filtering by applying your convolution kernel
to an image matrix. conv2 takes as arguments an input image and a filter, and
returns an output image. For example, in this call, k is the convolution kernel,
A is the input image, and B is the output image:
B = conv2(A,k);
www.MatlabSite.com
5-3
5
Linear Filtering and Filter Design
conv2 produces the output image by performing these steps:
1 Rotate the convolution kernel 180 degrees to produce a computational
molecule.
2 Determine the center pixel of the computational molecule.
3 Apply the computational molecule to each pixel in the input image.
Each of these steps is explained below.
Rotating the Convolution Kernel
In two-dimensional convolution, the computations are performed using a
computational molecule. This is simply the convolution kernel rotated 180
degrees, as in this call:
h = rot90(k,2);
h =
2 6
1 –3
4
4
Determining the Center Pixel
To apply the computational molecule, you must first determine the center pixel.
The center pixel is defined as floor((size(h)+1)/2). For example, in a 5-by-5
molecule, the center pixel is (3,3). The molecule h shown above is 2-by-3, so the
center pixel is (1,2).
Applying the Computational M olecule
The value of any given pixel in B is determined by applying the computational
molecule h to the corresponding pixel in A. You can visualize this by overlaying
h on A, with the center pixel of h over the pixel of interest in A. You then
multiply each element of h by the corresponding pixel in A, and sum the results.
5-4
www.MatlabSite.com
Linear Filtering
For example, to determine the value of the pixel (4,6) in B, overlay h on A, with
the center pixel of h covering the pixel (4,6) in A. The center pixel is circled in
this figure:
A
–2
4
–4
–4
–4
–2
4
–1
1
–4
–4
0
2
3
5
–2
–3
1
2
–4
2
0
–1
3
0
0
–1
2
1
1
3
2
4
5
2
6
3
1
h
4
3
–3
4
5
2
5
5
3
2
0
5
0
–1
–4
4
3
5
–4
–2
–4
–2
1
–1
1
–2
–1
2
–2
5
–4
Now, look at the six pixels covered by h. For each of these pixels, multiply the
value of the pixel by the value in h. Sum the results, and place this sum in
B(4,6):
B(4,6) = 2*2 + 3*6 + 3*4 + 3*1 + 2*–3 + 0*4 = 31
Perform this procedure for each pixel in A to determine the value of each
corresponding pixel in B.
Pa dding of Borders
When you apply a filter to pixels on the borders of an image, some of the
elements of the computational molecule may not overlap actual image pixels.
For example, if the molecule is 3-by-3 and you are computing the result for a
pixel on the top row of the image, some of the elements of the molecule are
outside the border of the image.
www.MatlabSite.com
5-5
5
Linear Filtering and Filter Design
This figure illustrates a 3-by-3 computational molecule being applied to the
pixel (1,3) of a 5-by-5 matrix. The center pixel is indicate by a filled circle:
In order to compute output values for the border pixels, conv2 pads the image
matrix with zeroes. In other words, the output values are computed by
assuming that the input image is surrounded by additional rows and columns
of zeroes. In the figure shown above, the elements in the top row of the
computational molecule are assumed to overlap zeroes.
Depending on what you are trying to accomplish, you may want to discard
output pixels whose values depend on zero padding. To indicate what portion
of the convolution to return, conv2 takes a third input argument, called the
shape parameter, whose value is one of these three strings:
• 'valid' – returns only the pixels whose values can be computed without
using zero padding of the input image. The resulting output image is smaller
than the input image. In this example, the output image is 3-by-3.
• 'same' – returns the set of pixels that can be computed by applying the filter
to all pixels that are actually part of the input image. Border pixels are
computed using zero padding, but the center pixel of the computational
kernel is applied only to pixels in the image. This results in an output image
that is the same size as the input image.
• 'full' – returns the full convolution. This means conv2 returns all pixels for
which any of the pixels in the computational molecule overlap pixels in the
image, even when the center pixel is outside the input image. The resulting
output image is larger than the input image. In this example, the output
image is 7-by-7.
conv2 returns the full convolution by default.
5-6
www.MatlabSite.com
Linear Filtering
The figure below illustrates applying a computational molecule to three
different places in an image matrix:
The com putational m olecule over-
The com putational m olecule over-
The com putational m olecule over-
laps only pixels that are in
laps pixels outside the original
laps pixels at the edges only. The
the original im age. The result is
im age, but the center pixel overlaps
center pixel is outside the im age.
included in the output m atrix,
a pixel in the im age. The result is
The result is included in the output
regardless of the shape param eter.
included in the output m atrix if the
m atrix if the shape param eter is
shape param eter is
same or
full.
full.
If you use the full option, then the order of the first two input arguments is
interchangeable, because full convolution is commutative. In other words, it
does not matter which matrix is considered the convolution kernel, because the
result is the same in either case. If you use the valid or same option, the
operation is not commutative, so the convolution kernel must be the second
argument.
The filter2 Function
In addition to the conv2 function, MATLAB also provides the filter2 function
for two-dimensional linear filtering. filter2 can produce the same results as
conv2, and differs primarily in that it takes a computational molecule as an
input argument, rather than a convolution kernel. (filter2 operates by
forming the convolution kernel from the computational molecule and then
calling conv2.) The operation that filter2 performs is called correlation.
www.MatlabSite.com
5-7
5
Linear Filtering and Filter Design
If k is a convolution kernel, h is the corresponding computational molecule, and
A is an image matrix, these calls produce identical results:
B = conv2(A,k,'same');
and:
B = filter2(h,A,'same');
The functions in the Image Processing Toolbox that produce filters (fspecial,
fsample, etc.) all return computational molecules. You can use these filters
directly with filter2, or you can rotate them 180 degrees and call conv2.
Sepa ra bility
Before calling conv2 to perform two-dimensional convolution, filter2 first
checks whether the filter is separable into two one-dimensional filters (one
column vector and one row vector). If the filter is separable, filter2 uses
singular value decomposition to find the two vectors. filter2 then calls conv2
with this syntax:
conv2(A,kcol,krow);
kcol and krow are the column and row vectors that the two-dimensional
convolution kernel k separates into (that is, k = kcol*krow).
conv2 filters the columns with the column vector, and then, using the output of
this operation, filters the rows using the row vector. The result is equivalent to
two-dimensional convolution but is faster because it requires fewer
computations.
5-8
www.MatlabSite.com
Linear Filtering
Determining Separability
A filter is separable if its rank is 1. For example, this filter is separable:
k =
1
2
4
2
4
8
3
6
12
rank(k)
ans =
1
H igher-Dim ensiona l Convolution
To perform two-dimensional convolution, you use conv2 or filter2. To perform
higher-dimensional convolution, you use the convn function. convn takes as
arguments a data array and a convolution kernel, both of which can be of any
dimension, and returns an array whose dimension is the higher of the two
input arrays’ dimensions. convn also takes a shape parameter argument that
accepts the same values as in conv2 and filter2, and which has analogous
effects in higher dimensions.
One important application for the convn function is to filter image arrays that
have multiple planes or frames. For example, suppose you have an array A
containing five RGB images that you want to filter using a two-dimensional
convolution kernel k. The image array is a four-dimensional array of size
m-by-n-by-3-by-5. To filter this array with conv2, you would need to call the
function 15 times, once for each combination of planes and frames, and
assemble the results into a four-dimensional array. Using convn, you can filter
the array in a single call:
B = convn(A,k);
For more information, see the reference entry for convn in Chapter 11.
Using Predefined Filter Ty pes
The function fspecial produces several kinds of predefined filters, in the form
of computational molecules. After creating a filter with fspecial, you can
www.MatlabSite.com
5-9
5
Linear Filtering and Filter Design
apply it directly to your image data using filter2, or you can rotate it 180
degrees and use conv2 or convn.
One simple filter fspecial can produce is an averaging filter. This type of filter
computes the value of an output pixel by simply averaging the values of its
neighboring pixels.
The default size of the averaging filter fspecial creates is 3-by-3, but you can
specify a different size. The value of each element is 1/length(h(:)). For
example, a 5-by-5 averaging filter would be:
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
0.0400
Applying this filter to a pixel is equivalent to adding up the values of that
pixel’s 5-by-5 neighborhood and dividing by 25. This has the effect of smoothing
out local highlights and blurring edges in an image.
This example illustrates applying a 5-by-5 averaging filter to an intensity
image:
I = imread('blood1.tif');
h = fspecial('average',5);
I2 = uint8(round(filter2(h,I)));
imshow(I)
figure, imshow(I2)
5-10
www.MatlabSite.com
Linear Filtering
Note that the output from filter2 (and conv2 and convn) is always of class
double. In the example above, the input image is of class uint8, so the output
from filter2 consists of double-precision values in the range [0,255]. The call
to the uint8 function converts the output to uint8; the data is not in the proper
range for an image of class double.
Another relatively simple filter fspecial can produce is a 3-by-3 Sobel filter,
which is effective at detecting the horizontal edges of objects in an image:
h = fspecial('sobel')
h =
1
0
–1
2
0
–2
1
0
–1
Unlike an averaging filter, the Sobel filter produces values outside the range of
the input data. If the input image is of class double, the output array may
include values outside the range [0,1]; if the input image is of class uint8, the
output array may include values outside the range [0,255]. To display the
output as an image, you can use imshow and specify the data range, or you can
use the mat2gray function to convert the values to the range [0,1].
Note that if the input image is of class uint8, you should not simply convert the
output to uint8; if the output contains values outside the range [0,255], these
values cannot be represent as 8-bit integers, so the result of the conversion may
be unpredictable. You can, however, rescale the output and then convert it. For
example:
h = fspecial('sobel');
I2 = filter2(h,I);
J = uint8(round(mat2gray(I2)*255));
The following example creates a Sobel filter and uses filter2 to apply the
filter to the blood1 image. Notice that in the call to imshow, the intensity range
is specified as an empty matrix ([]). This instructs imshow to display the
minimum value in I2 as black, the maximum value as white, and values in
www.MatlabSite.com
5-11
5
Linear Filtering and Filter Design
between as intermediate shades of gray, thus enabling you to display the
filter2 output without converting or rescaling it.
I = imread('blood1.tif');
h = fspecial('sobel');
I2 = filter2(h,I);
imshow(I2,[])
For a description of all the filter types fspecial provides, see the reference
entry for fspecial in Chapter 11.
5-12
www.MatlabSite.com
Filter Design
Filter Design
This section describes working in the frequency domain to design filters. Topics
discussed include:
• Finite Impulse Response (FIR) filters, the class of linear filter that the
toolbox supports
• The frequency transformation method, which transforms a one-dimensional
FIR filter into a two-dimensional FIR filter
• The frequency sampling method, which creates a filter based on a desired
frequency response
• The windowing method, which multiplies the ideal impulse response with a
window function to generate the filter
• Creating the desired frequency response matrix
• Computing the frequency response of a filter
This section assumes you are familiar with working in the frequency domain.
This topic is discussed in many signal processing and image processing
textbooks.
N O TE Most of the design methods described in this section work by creating a
two-dimensional filter from a one-dimensional filter or window created using
functions from the Signal Processing Toolbox. Although this toolbox is not
required, you may find it difficult to design filters in the Image Processing
Toolbox if you do not have the Signal Processing Toolbox as well.
FIR Filters
The Image Processing Toolbox supports one class of linear filter, the
two-dimensional Finite Impulse Response (FIR) filter. FIR filters have several
characteristics that make them ideal for image processing in the MATLAB
environment:
• FIR filters are easy to represent as matrices of coefficients.
• Two-dimensional FIR filters are natural extensions of one-dimensional FIR
filters.
www.MatlabSite.com
5-13
5
Linear Filtering and Filter Design
• There are several well-known, reliable methods for FIR filter design.
• FIR filters are easy to implement.
• FIR filters can be designed to have linear phase, which helps prevent
distortion.
Another class of filter, the Infinite Impulse Response (IIR) filter, is not as
suitable for image processing applications. It lacks the inherent stability and
ease of design and implementation of the FIR filter. Therefore, this toolbox
does not provide IIR filter support.
Frequency Tra nsform a tion M ethod
The frequency transformation method transforms a one-dimensional FIR filter
into a two-dimensional FIR filter. The frequency transformation method
preserves most of the characteristics of the one-dimensional filter, particularly
the transition bandwidth and ripple characteristics. This method uses a
transformation matrix, a set of elements that defines the frequency
transformation.
The toolbox function ftrans2 implements the frequency transformation
method. This function’s default transformation matrix produces filters with
nearly circular symmetry. By defining your own transformation matrix, you
can obtain different symmetries. (See Jae S. Lim, Two-Dimensional Signal and
Image Processing, 1990, for details.)
The frequency transformation method generally produces very good results, as
it is easier to design a one-dimensional filter with particular characteristics
than a corresponding two-dimensional filter. For instance, the next example
designs an optimal equiripple one-dimensional FIR filter and uses it to create
a two-dimensional filter with similar characteristics. The shape of the
5-14
www.MatlabSite.com
Filter Design
one-dimensional frequency response is clearly evident in the two-dimensional
response.
b = remez(10,[0 0.4 0.6 1],[1 1 0 0]);
h = ftrans2(b);
[H,w] = freqz(b,1,64,'whole');
colormap(jet(64))
plot(w/pi–1,fftshift(abs(H)))
figure, freqz2(h,[32 32])
Frequency Sa m pling M ethod
The frequency sampling method creates a filter based on a desired frequency
response. Given a matrix of points that defines the shape of the frequency
response, this method creates a filter whose frequency response passes through
those points. Frequency sampling places no constraints on the behavior of the
frequency response between the given points; usually, the response ripples in
these areas.
The toolbox function fsamp2 implements frequency sampling design for
two-dimensional FIR filters. fsamp2 returns a filter h with a frequency
response that passes through the points in the input matrix Hd. The example
below creates an 11-by-11 filter using fsamp2, and plots the frequency response
of the resulting filter. (The freqz2 function in this example calculates the
www.MatlabSite.com
5-15
5
Linear Filtering and Filter Design
two-dimensional frequency response of a filter. For more information, see page
5-19.)
Hd = zeros(11,11); Hd(4:8,4:8) = 1;
[f1,f2] = freqspace(11,'meshgrid');
mesh(f1,f2,Hd), axis([–1 1 –1 1 0 1.2]), colormap(jet(64))
h = fsamp2(Hd);
figure, freqz2(h,[32 32]), axis([–1 1 –1 1 0 1.2])
Notice the ripples in the actual frequency response, compared to the desired
frequency response. These ripples are a fundamental problem with the
frequency sampling design method. They occur wherever there are sharp
transitions in the desired response.
You can reduce the spatial extent of the ripples by using a larger filter.
However, a larger filter does not reduce the height of the ripples, and requires
more computation time for filtering. To achieve a smoother approximation to
the desired frequency response, consider using the frequency transformation
method or the windowing method.
W indow ing M ethod
The windowing method involves multiplying the ideal impulse response with a
window function to generate a corresponding filter. Like the frequency
sampling method, the windowing method produces a filter whose frequency
response approximates a desired frequency response. The windowing method,
however, tends to produce better results than the frequency sampling method.
5-16
www.MatlabSite.com
Filter Design
The toolbox provides two functions for window-based filter design, fwind1 and
fwind2. fwind1 designs a two-dimensional filter by using a two-dimensional
window that it creates from one or two one-dimensional windows that you
specify. fwind2 designs a two-dimensional filter by using a specified
two-dimensional window directly.
fwind1 supports two different methods for making the two-dimensional
windows it uses:
• Transforming a single one-dimensional window to create a two-dimensional
window that is nearly circularly symmetric, by using a process similar to
rotation
• Creating a rectangular, separable window from two one-dimensional
windows, by computing their outer product
The example below uses fwind1 to create an 11-by-11 filter from the desired
frequency response Hd. Here, the hamming function from the Signal Processing
Toolbox is used to create a one-dimensional window, which fwind1 then
extends to a two-dimensional window.
Hd = zeros(11,11); Hd(4:8,4:8) = 1;
[f1,f2] = freqspace(11,'meshgrid');
mesh(f1,f2,Hd), axis([–1 1 –1 1 0 1.2]), colormap(jet(64))
h = fwind1(Hd,hamming(11));
figure, freqz2(h,[32 32]), axis([–1 1 –1 1 0 1.2])
www.MatlabSite.com
5-17
5
Linear Filtering and Filter Design
Crea ting the Desired Frequency Response M a trix
The filter design functions fsamp2, fwind1, and fwind2 all create filters based
on a desired frequency response magnitude matrix. You can create an
appropriate desired frequency response matrix using the freqspace function.
freqspace returns correct, evenly spaced frequency values for any size
response. If you create a desired frequency response matrix using frequency
points other than those returned by freqspace, you may get unexpected
results, such as nonlinear phase.
For example, to create a circular ideal lowpass frequency response with cutoff
at 0.5 use:
[f1,f2] = freqspace(25,'meshgrid');
Hd = zeros(25,25); d = sqrt(f1.^2 + f2.^2) < 0.5;
Hd(d) = 1;
mesh(f1,f2,Hd)
Note that for this frequency response, filters produced by fsamp2, fwind1, and
fwind2 are real. This result is desirable for most image processing applications.
To achieve this in general, the desired frequency response should be symmetric
about the frequency origin (f1 = 0, f2 = 0).
5-18
www.MatlabSite.com
Filter Design
Com puting the Frequency Response of a Filter
The freqz2 function computes the frequency response for a two-dimensional
filter. With no output arguments, freqz2 creates a mesh plot of the frequency
response. For example, consider this FIR filter:
h =[0.1667
0.6667
0.1667
0.6667
–3.3333
0.6667
0.1667
0.6667
0.1667];
This command computes and displays the 64-by-64 point frequency response of
h:
freqz2(h)
To obtain the frequency response matrix H and the frequency point vectors f1
and f2, use output arguments:
[H,f1,f2] = freqz2(h);
freqz2 normalizes the frequencies f1 and f2 so that the value 1.0 corresponds
to half the sampling frequency, or π radians.
For a simple m-by-n response, as shown above, freqz2 uses the
two-dimensional fast Fourier transform function fft2. You can also specify
vectors of arbitrary frequency points, but in this case freqz2 uses a slower
algorithm.
For more information about the fast Fourier transform and its application to
linear filtering and filter design, see Chapter 6.
www.MatlabSite.com
5-19
5
Linear Filtering and Filter Design
5-20
www.MatlabSite.com
6
Transforms
Overview
. . . . . . . . . . . . . . . . . . . . . 6-2
Fourier Transform . . . . .
Definition . . . . . . . . . .
The Discrete Fourier Transform
Applications . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
6-3
6-3
6-8
6-11
Discrete Cosine Transform . . . . . . . . . . . . . 6-15
The DCT Transform Matrix . . . . . . . . . . . . . . 6-16
The DCT and Image Compression . . . . . . . . . . . . 6-17
Radon Transform . . . . . . . . . . . . . . . . . 6-19
Using the Radon Transform to Detect Lines . . . . . . . . 6-22
The Inverse Radon Transform . . . . . . . . . . . . . 6-25
www.MatlabSite.com
6
Transforms
O verview
The usual mathematical representation of an image is a function of two spatial
variables: f ( x, y ) . The value of the function at a particular location ( x, y )
represents the intensity of the image at that point. The term transform refers
to an alternative mathematical representation of an image.
For example, the Fourier transform is a representation of an image as a sum of
complex exponentials of varying magnitudes, frequencies, and phases. This
representation is useful in a broad range of applications, including (but not
limited to) image analysis, restoration, and filtering.
The discrete cosine transform (DCT) also represents an image as a sum of
sinusoids of varying magnitudes and frequencies. The DCT is extremely useful
for image compression; it is the basis of the widely used JPEG image
compression algorithm.
The Radon transform represents an image as a collection of projections along
various directions. It is used in areas ranging from seismology to computer
vision.
This chapter defines each of these transforms, describes related toolbox
functions, and shows examples of related image processing applications.
6-2
www.MatlabSite.com
Fourier Transform
Fourier Tra nsform
The Fourier transform plays a critical role in a broad range of image processing
applications, including enhancement, analysis, restoration, and compression.
This section defines the Fourier transform and the related discrete Fourier
transform, discusses the fast Fourier transform, and presents some sample
applications.
Definition
If f ( m, n ) is a function of two discrete spatial variables m and n, then we define
the two-dimensional Fourier transform of f ( m, n ) by the relationship:
∞
F ( ω 1, ω 2 ) =
∞
∑
∑
f ( m, n )e – jω 1 m e – jω 2 n
m = –∞ n = –∞
The variables ω1 and ω2 are frequency variables; their units are radians per
sample. F ( ω 1, ω 2 ) is often called the frequency-domain representation of
f ( m, n ) . F ( ω 1, ω 2 ) is a complex-valued function that is periodic both in ω 1 and
ω 2 , with period 2π . Because of the periodicity, usually only the range
– π ≤ ω 1, ω 2 ≤ π is displayed. Note that F ( 0, 0 ) is the sum of all the values of
f ( m, n ) . For this reason, F ( 0, 0 ) is often called the constant component or DC
component of the Fourier transform. (DC stands for direct current; it is an
electrical engineering term that refers to a constant-voltage power source, as
opposed to a power source whose voltage varies sinusoidally.)
The inverse two-dimensional Fourier transform is given by:
1
f ( m, n ) = -----2π
π
π
∫ω
1
= –π
∫ω
2
= –π
F ( ω 1, ω 2 )e
jω 1 m jω 2 n
e
dω 1 dω 2
Roughly speaking, this equation means that f ( m, n ) can be represented as a
sum of an infinite number of complex exponentials (sinusoids) with different
frequencies. The magnitude and phase of the contribution at the frequencies
( ω 1, ω 2 ) are given by F ( ω 1, ω 2 ) .
www.MatlabSite.com
6-3
6
Transforms
Example
Consider a function f ( m, n ) that equals 1 within a rectangular region and 0
everywhere else.
n
f(m,n)
m
To simplify the diagram, f ( m, n ) is shown as a continuous function, even
though the variables m and n are discrete.
6-4
www.MatlabSite.com
Fourier Transform
The magnitude of the Fourier transform, F ( ω 1, ω 2 ) , is shown here as a mesh
plot:
ω
2
(ve
rti
cal
fre
y)
qu
uenc
enc
y)
freq
ntal
orizo
ω 1 (h
The peak at the center of the plot is F ( 0, 0 ) , which is the sum of all the values
in f ( m, n ) . The plot also shows that F ( ω 1, ω 2 ) has more energy at high
horizontal frequencies than at high vertical frequencies. This reflects the fact
that horizontal cross sections of f ( m, n ) are narrow pulses, while vertical cross
sections are broad pulses. Narrow pulses have more high-frequency content
than broad pulses.
www.MatlabSite.com
6-5
6
Transforms
ω2
Another common way to visualize the Fourier transform is to display
log F ( ω 1, ω 2 ) as an image, as in:
ω1
Using the logarithm helps to bring out details of the Fourier transform in
regions where F ( ω 1, ω 2 ) is very close to 0.
6-6
www.MatlabSite.com
Fourier Transform
Examples of the Fourier transform for other simple shapes are shown below.
www.MatlabSite.com
6-7
6
Transforms
The Discrete Fourier Tra nsform
Working with the Fourier transform on a computer usually involves a form of
the transform known as the discrete Fourier transform (DFT). There are two
principal reasons for using this form:
• The input and output of the DFT are both discrete, which makes it
convenient for computer manipulations.
• There is a fast algorithm for computing the DFT known as the fast Fourier
transform (FFT).
The DFT is usually defined for a discrete function f ( m, n ) that is nonzero only
over the finite region 0 ≤ m ≤ M – 1 and 0 ≤ n ≤ N – 1 . The two-dimensional
M-by-N DFT and inverse M-by-N DFT relationships are given by:
M–1 N–1
F ( p, q ) =
∑
∑
f ( m, n )e
– j ( 2π ⁄ M ) pm – j ( 2π ⁄ N )qn
e
m=0 n=0
1
f ( m, n ) = ----------MN
M–1 N–1
∑ ∑
p=0
F ( p, q )e
j ( 2π ⁄ M ) pm j ( 2π ⁄ N )qn
q=0
e
p = 0, 1, …, M – 1
q = 0, 1, … , N – 1
m = 0, 1, … , M – 1
n = 0, 1, …, N – 1
The values F ( p, q ) are called the DFT coefficients of f ( m, n ) . In particular,
the value F ( 0, 0 ) is called the DC coefficient. (Note that matrix indices in
MATLAB always start at 1 rather than 0; therefore, the matrix elements
f(1,1) and F(1,1) correspond to the mathematical quantities f ( 0, 0 ) and
F ( 0, 0 ) , respectively.)
The MATLAB functions fft, fft2, and fftn implement the fast Fourier
transform algorithm for computing the one-dimensional DFT, two-dimensional
DFT, and N-dimensional DFT, respectively. The functions ifft, ifft2, and
ifftn compute the inverse DFT.
Relationship to the Fourier Transform
The DFT coefficients F ( p, q ) are samples of the Fourier transform F ( ω 1, ω 2 ) :
6-8
www.MatlabSite.com
Fourier Transform
F ( p, q ) = F ( ω 1, ω 2 )
ω 1 = 2πp ⁄ M
ω 2 = 2πq ⁄ N
p = 0, 1, …, M – 1
q = 0, 1, …, N – 1
Example
Let’s construct a matrix f that is similar to the function f(m,n) in the example
on page 6-4.
f = zeros(30,30);
f(5:24,13:17) = 1;
imshow(f,'notruesize')
www.MatlabSite.com
6-9
6
Transforms
Compute and visualize the 30-by-30 DFT of f with these commands:
F = fft2(f);
F2 = log(abs(F));
imshow(F2,[–1 5],'notruesize'); colormap(jet); colorbar
This plot differs from the Fourier transform displayed on page 6-6. First, the
resolution is much lower. Second, the DC coefficient is displayed in the
upper-left corner instead of the traditional location in the center.
The resolution can be increased by zero-padding f when computing its DFT.
The zero-padding and DFT computation can be performed in a single step with
this command:
F = fft2(f,256,256);
6-10
www.MatlabSite.com
Fourier Transform
This command zero-pads f to be 256-by-256 before computing the DFT. The
result is that the DCT coefficients F sample the Fourier transform much more
finely:
imshow(log(abs(F)),[–1 5]); colormap(jet); colorbar
The DC coefficient, however, is still displayed in the upper-left corner rather
than the center. You can fix this problem by using the function fftshift,
which swaps the quadrants of F so that the DC coefficient is in the center.
F = fft2(f,256,256);
F2 = fftshift(F);
imshow(log(abs(F2)),[–1 5]); colormap(jet); colorbar
The resulting plot is identical to the one on page 6-6.
Applica tions
This section presents a few of the many image processing-related applications
of the Fourier transform.
Frequency Response of Linear Filters
The Fourier transform of the impulse response of a linear filter gives the
frequency response of the filter. The function freqz2 computes and displays a
filter’s frequency response. The frequency response of the Gaussian
www.MatlabSite.com
6-11
6
Transforms
convolution kernel shows that this filter passes low frequencies and attenuates
high frequencies.
h = fspecial('gaussian');
freqz2(h)
See Chapter 5 for more information about linear filtering, filter design, and
frequency responses.
Fast Convolution
A key property of the Fourier transform is that the multiplication of two
Fourier transforms corresponds to the convolution of the associated spatial
functions. This property, together with the fast Fourier transform, forms the
basis for a fast convolution algorithm.
Suppose that A is an M-by-N matrix and B is a P-by-Q matrix. The convolution
of A and B can be computed using the following steps:
1 Zero-pad A and B so that they are at least (M+P–1)-by-(N+Q–1). (Often A and
B are zero-padded to a size that is a power of 2 because fft2 is fastest for
these sizes.)
2 Compute the two-dimensional DFT of A and B using fft2.
6-12
www.MatlabSite.com
Fourier Transform
3 Multiply the two DFTs together.
4 Using ifft2, compute the inverse two-dimensional DFT of the result from
step 3.
For example:
A = magic(3);
B = ones(3);
A(8,8) = 0;
B(8,8) = 0;
C = ifft2(fft2(A).*fft2(B));
C = C(1:5,1:5);
C = real(C)
% remove imaginary
% zero–pad A to be 8–by–8
% zero–pad B to be 8–by–8
% extract the nonzero portion
part caused by roundoff error
C =
8.0000
11.0000
15.0000
7.0000
4.0000
9.0000
17.0000
30.0000
21.0000
13.0000
15.0000
30.0000
45.0000
30.0000
15.0000
7.0000
19.0000
30.0000
23.0000
11.0000
6.0000
13.0000
15.0000
9.0000
2.0000
The FFT-based convolution method is most often used for large inputs. For
small inputs it is generally faster to use filter2 or conv2.
Locating Image Features
The Fourier transform can also be used to perform correlation, which is closely
related to convolution. Correlation can be used to locate features within an
image; in this context correlation is often called template matching. For
instance, suppose you want to locate occurrences of the letter “a” in the image
www.MatlabSite.com
6-13
6
Transforms
text.tif. The figure below shows the image and the template you want to
match:
The correlation of the image of the letter “a” with the larger image can be
computed by first rotating the image of “a” by 180o and then using the
FFT-based convolution technique described above. The left image below is the
result of the correlation; bright peaks correspond to occurrences of the letter.
The locations of these peaks are indicated by the white spots in the thresholded
correlation image shown on the right.
6-14
www.MatlabSite.com
Discrete C osine Transform
Discrete Cosine Tra nsform
The dct2 function in the Image Processing Toolbox computes the
two-dimensional discrete cosine transform (DCT) of an image. The DCT has
the property that, for a typical image, most of the visually significant
information about the image is concentrated in just a few coefficients of the
DCT. For this reason, the DCT is often used in image compression applications.
For example, the DCT is at the heart of the the international standard lossy
image compression algorithm known as JPEG. (The name comes from the
working group that developed the standard: the Joint Photographic Experts
Group.)
The two-dimensional DCT of an M-by-N matrix A is defined as follows:
M–1 N–1
B pq = α p α q
∑ ∑
m=0 n=0
π ( 2m + 1 ) p
π ( 2n + 1 )q
A mn cos ------------------------------- cos ----------------------------- ,
2M
2N
1 ⁄ M, p = 0
αp =
2 ⁄ M, 1 ≤ p ≤ M – 1
0≤ p≤M–1
0≤q≤N–1
1 ⁄ N , q = 0
αq =
2 ⁄ N, 1 ≤ q ≤ N – 1
The values B pq are called the DCT coefficients of A. (Note that matrix indices
in MATLAB always start at 1 rather than 0; therefore, the MATLAB matrix
elements A(1,1) and B(1,1) correspond to the mathematical quantities A 00
and B 00 , respectively.)
The DCT is an invertible transform, and its inverse is given by:
M–1 N–1
A mn =
∑ ∑
p=0 q=0
π ( 2m + 1 ) p
π ( 2n + 1 )q
α p α q B pq cos ------------------------------- cos ----------------------------- ,
2M
2N
1 ⁄ M, p = 0
αp =
2 ⁄ M, 1 ≤ p ≤ M – 1
0≤m≤M–1
0≤n≤N–1
1 ⁄ N , q = 0
αq =
2 ⁄ N, 1 ≤ q ≤ N – 1
The inverse DCT equation can be interpreted as meaning that any M-by-N
matrix A can be written as a sum of MN functions of the form:
www.MatlabSite.com
6-15
6
Transforms
π ( 2m + 1 ) p
π ( 2n + 1 )q
α p α q cos ------------------------------- cos ----------------------------- ,
2M
2N
0≤ p≤M–1
0≤q≤N–1
These functions are called the basis functions of the DCT. The DCT coefficients
B pq , then, can be regarded as the weights applied to each basis function. For
8-by-8 matrices, the 64 basis functions are illustrated by this image:
Horizontal frequencies increase from left to right, and vertical frequencies
increase from top to bottom. The constant-valued basis function at the upper
left is often called the DC basis function, and the corresponding DCT coefficient
B00 is often called the DC coefficient.
The DCT Tra nsform M a trix
The Image Processing Toolbox offers two different ways to compute the DCT.
The first method is to use the function dct2. dct2 uses an FFT-based algorithm
for speedy computation with large inputs.
For small square inputs, such as 8-by-8 or 16-by-16, it may be more efficient to
use the DCT transform matrix, which is returned by the function dctmtx. The
M-by-M transform matrix T is given by:
6-16
www.MatlabSite.com
Discrete C osine Transform
T pq
1
---------
= M
2
π ( 2q + 1 ) p
------ cos ---------------------------2M
M
p = 0, 0 ≤ q ≤ M – 1
1 ≤ p ≤ M – 1, 0 ≤ q ≤ M – 1
For an M-by-M matrix A, T*A is an M-by-M matrix whose columns contain the
one-dimensional DCT of the columns of A. The two-dimensional DCT of A can
be computed as B=T*A*T'. Since T is a real orthonormal matrix, its inverse is
the same as its transpose. Therefore, the inverse two-dimensional DCT of B is
given by T'*B*T.
The DCT a nd Im a ge Com pression
In the JPEG image compression algorithm, the input image is divided into
8-by-8 or 16-by-16 blocks, and the two-dimensional DCT is computed for each
block. The DCT coefficients are then quantized, coded, and transmitted. The
JPEG receiver (or JPEG file reader) decodes the quantized DCT coefficients,
computes the inverse two-dimensional DCT of each block, and then puts the
blocks back together into a single image. For typical images, many of the DCT
coefficients have values close to zero; these coefficients can be discarded
without seriously affecting the quality of the reconstructed image.
The example code below computes the two-dimensional DCT of 8-by-8 blocks in
the input image; discards (sets to zero) all but 10 of the 64 DCT coefficients in
www.MatlabSite.com
6-17
6
Transforms
each block; and then reconstructs the image using the two-dimensional inverse
DCT of each block. The transform matrix computation method is used.
I = imread('cameraman.tif');
I = double(I)/255;
T = dctmtx(8);
B = blkproc(I,[8 8],'P1*x*P2',T,T');
mask = [1
1
1
1
0
0
0
0
1
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
1
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];
B2 = blkproc(B,[8 8],'P1.*x',mask);
I2 = blkproc(B2,[8 8],'P1*x*P2',T',T);
imshow(I), figure, imshow(I2)
Although there is some loss of quality in the reconstructed image, it is clearly
recognizable, even though almost 85% of the DCT coefficients were discarded.
To experiment with discarding more or fewer coefficients, and to apply this
technique to other images, try running the demo function dctdemo.
6-18
www.MatlabSite.com
Radon Transform
Ra don Tra nsform
The radon function in the Image Processing Toolbox computes projections of an
image matrix along specified directions. A projection of a two-dimensional
function f(x,y) is a line integral in a certain direction. For example, the line
integral of f(x,y) in the vertical direction is the projection of f(x,y) onto the
x-axis; the line integral in the horizontal direction is the projection of f(x,y) onto
the y-axis. This figure shows horizontal and vertical projections for a simple
two-dimensional function.
f(x,y)
x
Projection onto the y-axis
y
Projection onto the x-axis
Projections can be computed along any angle θ. In general, the Radon
transform of f(x,y) is the line integral of f parallel to the y′ axis:
R θ ( x′ ) =
∞
∫–∞ f (x′ cos θ – y′ sin θ, x′ sin θ + y′ cos θ) d y′
where
x′ =
cos θ sin θ x
y′
– sin θ cos θ y
www.MatlabSite.com
6-19
6
Transforms
This figure illustrates the geometry of the Radon transform.
y′
y
x′
f(x,y)
θ
x
x′
Rθ(x′)
This command computes the Radon transform of I for the angles specified in
the vector theta:
[R,xp] = radon(I,theta);
The columns of R contain the Radon transform for each angle in theta. xp
contains the corresponding coordinates along the x′-axis. The “center pixel” of
I is defined to be floor((size(I)+1)/2); this is the pixel on the x′-axis
corresponding to x′ = 0 .
6-20
www.MatlabSite.com
Radon Transform
The commands below compute and plot the Radon transform at 0˚ and 45˚ of
an image containing a single square object.
I = zeros(100,100);
I(25:75, 25:75) = 1;
imshow(I)
[R,xp] = radon(I,[0 45]);
figure; plot(xp,R(:,1)); title('R_{0^o} (x\prime)')
figure; plot(xp,R(:,2)); title('R_{45^o} (x\prime)')
R 0° ( x′ )
www.MatlabSite.com
R 45° ( x′ )
6-21
6
Transforms
The Radon transform for a large number of angles is often displayed as an
image. In this example, the Radon transform for the square image is computed
at angles from 0˚ to 180˚, in 1˚ increments:
theta = 0:180;
[R,xp] = radon(I,theta);
imagesc(theta,xp,R);
xlabel('\theta (degrees)');
ylabel('x''');
colormap(hot);
colorbar
R θ ( x′ )
Using the Ra don Tra nsform to Detect Lines
The Radon transform is closely related to a common computer vision operation
known as the Hough transform. You can use the radon function to implement
a form of the Hough transform used to detect straight lines. The steps are:
6-22
www.MatlabSite.com
Radon Transform
1 Compute a binary edge image using the edge function.
I = imread('ic.tif');
BW = edge(I);
imshow(I)
figure, imshow(BW)
2 Compute the Radon transform of the edge image.
www.MatlabSite.com
6-23
6
Transforms
theta = 0:179;
[R,xp] = radon(BW,theta);
imagesc(theta, xp, R); colormap(hot);
xlabel('\theta (degrees)'); ylabel('x''');
colorbar
R θ ( x′ )
3 Find the locations of strong peaks in the Radon transform matrix. The
locations of these peaks correspond to the location of straight lines in the
original image.
In this example, the strongest peak in R corresponds to θ = 94° and
x′ = – 101 . The line perpendicular to that angle and located at x′ = – 101 is
6-24
www.MatlabSite.com
Radon Transform
shown below, superimposed in red on the original image. The Radon transform
geometry is shown in black.
x′
θ = 94˚
x
x′ = –101
Notice that the other strong lines parallel to the red line also appear as peaks
at θ = 94° in the transform. Also, the lines perpendicular to this line appear
as peaks at θ = 4° .
The Inverse Ra don Tra nsform
The iradon function in the toolbox uses the inverse Radon transform to
reconstruct images from projection data, such as the output from the radon
function. The inverse Radon transform is commonly used in tomography
applications.
For more information about iradon, see the reference entry for this function in
Chapter 11. Also, see the entry for the phantom function, which you can use to
generate images for testing the Radon and inverse Radon transforms.
www.MatlabSite.com
6-25
6
Transforms
6-26
www.MatlabSite.com
7
Analyzing and Enhancing
Images
Overview
. . . . . . . . . . . . . . . . . . . . . 7-2
Pixel Values and Statistics
Pixel Selection . . . . . . .
Intensity Profile . . . . . .
Image Contours . . . . . .
Image Histogram . . . . .
Summary Statistics . . . . .
Feature Measurement . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
7-3
7-3
7-4
7-7
7-8
7-9
7-9
Image Analysis . . . . . . . . . . . . . . . . . . . 7-10
Edge Detection . . . . . . . . . . . . . . . . . . . 7-10
Quadtree Decomposition . . . . . . . . . . . . . . . . 7-11
Image Enhancement . . . . . . . . . . . . . . . . 7-14
Intensity Adjustment . . . . . . . . . . . . . . . . . 7-14
Noise Removal . . . . . . . . . . . . . . . . . . . . 7-20
www.MatlabSite.com
7
Analyzing and Enhancing Images
O verview
The Image Processing Toolbox supports a range of standard image processing
operations for analyzing and enhancing images. Its functions simplify several
categories of tasks, including:
• Obtaining pixel values and statistics, which are numerical summaries of
data in an image
• Analyzing images to extract information about their essential structure
• Enhancing images to make certain features easier to see or to reduce noise
This section describes specific operations within each category, and shows how
to implement each kind of operation using toolbox functions.
7-2
www.MatlabSite.com
Pixel Values and Statistics
Pix el Va lues a nd Sta tistics
The Image Processing Toolbox provides several functions that return
information about the data values that make up an image. These functions
return information about image data in various forms, including:
• The data values for selected pixels (impixel, pixval)
• The data values along a path in an image (improfile)
• A contour plot of the image data (imcontour)
• A histogram of the image data (imhist)
• Summary statistics for the image data (mean2, std2, corr2)
• Feature measurements for image regions (imfeature)
Pix el Selection
The impixel function returns the data values for a selected pixel or set of
pixels. You can supply the coordinates of the pixels as input arguments, or you
can select pixels using a mouse.
If you call impixel with no input arguments, the cursor changes to a cross hair
when it is over the image. You can then click on the pixels of interest; impixel
displays a small star over each pixel you select. When you are done selecting
pixels, press Return. impixel returns the color values for the selected pixels,
and removes the stars.
impixel works with indexed, intensity, and RGB images. impixel always
returns pixel values as RGB triplets, regardless of the image type:
• For an RGB image, impixel returns the actual data for the pixel. The values
are either uint8 integers or double floating-point numbers, depending on
the class of the image array.
• For an indexed image, impixel returns the RGB triplet stored in the row of
the colormap that the pixel value points to. The values are double
floating-point numbers.
• For an intensity image, impixel returns the intensity value as an RGB
triplet, where R=G=B. The values are either uint8 integers or double
floating-point numbers, depending on the class of the image array.
www.MatlabSite.com
7-3
7
Analyzing and Enhancing Images
In this example, you call impixel and click on three points in the displayed
image, and then press Return.
imshow canoe.tif
impixel
*
*
*
ans =
0.1294
0.5176
0.7765
0.1294
0
0.6118
0.1294
0
0.4196
Notice that the second pixel, which is part of the canoe, is pure red; its green
and blue values are both 0.
The toolbox also provides the pixval function, which interactively displays the
data values for pixels as you move the cursor over the image. pixval can also
display the Euclidean distance between two pixels. For more information about
pixval, see the reference entry for this function in Chapter 11.
Intensity Profile
The improfile function calculates and plots the intensity values along a line
segment or a multiline path in an image. You can supply the coordinates of the
line segments as input arguments, or you can define the desired path using a
mouse. In either case, improfile uses interpolation to determine the values of
equally spaced points along the path. (By default, improfile uses nearest
neighbor interpolation, but you can specify a different method. See Chapter 3
7-4
www.MatlabSite.com
Pixel Values and Statistics
for a discussion of interpolation.) improfile works best with intensity and
RGB images. (For indexed images, it displays the index values from the image
matrix, not the intensity values from the colormap.)
For a single line segment, improfile plots the intensity values in a
two-dimensional view. For a multiline path, improfile plots the intensity
values in a three-dimensional view.
If you call improfile with no arguments, the cursor changes to a cross hair
when it is over the image. You can then specify line segments by clicking on the
endpoints; improfile draws a line between each two consecutive points you
select. When you finish specifying the path, press Return. improfile displays
the plot in a new figure.
In this example, you call improfile and specify a single line with the mouse.
The line is shown in red, and is drawn from left to right.
imshow debye1.tif
improfile
www.MatlabSite.com
7-5
7
Analyzing and Enhancing Images
improfile displays a plot of the data along the line:
Notice the peaks and valleys and how they correspond to the light and dark
bands in the image.
The example below shows how improfile works with an RGB image. The red
line is drawn from top to bottom.
imshow flowers.tif
improfile
7-6
www.MatlabSite.com
Pixel Values and Statistics
improfile displays a plot with separate lines for the red, green, and blue
intensities:
Notice how the lines correspond to the colors in the image. For example, the
central region of the plot shows high intensities of green and red, while the blue
intensity is 0. These are the values for the yellow flower.
Im a ge Contours
You can use the toolbox function imcontour to display a contour plot of the data
in an intensity image. This function is similar to the contour function in
MATLAB, but it automatically sets up the axes so their orientation and aspect
ratio match the image.
www.MatlabSite.com
7-7
7
Analyzing and Enhancing Images
This example displays a grayscale image of grains of rice and a contour plot of
the image data.
I = imread('rice.tif');
imshow(I)
figure, imcontour(I)
You can use the clabel function to label the levels of the contours. See the
description of clabel in the online MATLAB Function Reference for details.
Im a ge H istogra m
An image histogram is a chart that shows the distribution of intensities in an
indexed or intensity image. The image histogram function imhist creates this
plot by making n equally spaced bins, each representing a range of data values.
It then calculates the number of pixels within each range. For example, the
7-8
www.MatlabSite.com
Pixel Values and Statistics
commands below display an image of grains of rice, and a histogram based on
64 bins.
I = imread('rice.tif');
imshow(I)
figure, imhist(I,64)
The histogram shows a peak at around 100, due to the dark background in the
image.
For information about how to modify an image by changing the distribution of
its histogram, see “Intensity Adjustment” on page 7-14.
Sum m a r y Sta tistics
You can compute standard image statistics using the mean2, std2, and corr2
functions. mean2 and std2 compute the mean and standard deviation of the
elements of a matrix. corr2 computes the correlation coefficient between two
matrices of the same size.
These functions are two-dimensional versions of the mean, std, and corrcoef
functions described in the online MATLAB Function Reference.
Fea ture M ea surem ent
You can use the imfeature function to compute feature measurements for
image regions. For example, imfeature can measure such features as the area,
center of mass, and bounding box for a region you specify. See the reference
entry for imfeature in Chapter 11 for more information.
www.MatlabSite.com
7-9
7
Analyzing and Enhancing Images
Ima ge Ana lysis
Image analysis techniques return information about the structure of an image.
This section describes toolbox functions that you can use for these image
analysis techniques:
• Edge detection
• Quadtree decomposition
The functions described in this section work only with grayscale intensity
images.
Edge Detection
You can use the edge function to detect edges, which are those places in an
image that correspond to object boundaries. To find edges, this function looks
for places in the image where the intensity changes rapidly, using one of these
two criteria:
• Places where the first derivative of the intensity is larger in magnitude than
some threshold
• Places where the second derivative of the intensity has a zero crossing
edge provides a number of derivative estimators, each of which implements one
of the definitions above. For some of these estimators, you can specify whether
the operation should be sensitive to horizontal or vertical edges, or both. edge
returns a binary image containing 1’s where edges are found and 0’s elsewhere.
7-10
www.MatlabSite.com
Image Analysis
The example below uses the Sobel method to detect the edges in an image of
blood cells. By default, the operation is sensitive to both horizontal and vertical
edges.
I = imread('blood1.tif');
BW = edge(I,'sobel');
imshow(I)
figure, imshow(BW)
For an interactive demonstration of edge detection, try running edgedemo.
Q ua dtree Decom position
Quadtree decomposition is an analysis technique that involves subdividing an
image into blocks that are more homogeneous than the image itself. This
technique reveals information about the structure of the image. It is also useful
as the first step in adaptive compression algorithms.
You can perform quadtree decomposition using the qtdecomp function. This
function works by dividing a square image into four equal-sized square blocks,
and then testing each block to see if it meets some criterion of homogeneity
(e.g., if all of the pixels in the block are within a specific dynamic range). If a
block meets the criterion, it is not divided any further. If it does not meet the
criterion, it is subdivided again into four blocks, and the test criterion is
applied to those blocks. This process is repeated iteratively until each block
meets the criterion. The result may have blocks of several different sizes.
For example, suppose you want to perform quadtree decomposition on a
128-by-128 grayscale image. The first step is to divide the image into four
www.MatlabSite.com
7-11
7
Analyzing and Enhancing Images
64-by-64 blocks. You then apply the test criterion to each block; for example,
the criterion might be:
max(block(:)) – min(block(:)) <= 0.2
If one of the blocks meets this criterion, it is not divided any further; it is
64-by-64 in the final decomposition. If a block does not meet the criterion, it is
then divided into four 32-by-32 blocks, and the test is then applied to each of
these blocks. The blocks that fail to meet the criterion are then divided into four
16-by-16 blocks, and so on, until all blocks “pass.” Some of the blocks may be as
small as 1-by-1, unless you specify otherwise.
The call to qtdecomp for this example would be:
S = qtdecomp(I,0.2)
S is returned as a sparse matrix whose nonzero elements represent the
upper-left corners of the blocks; the value of each nonzero element indicates the
block size. S is the same size as I.
Note that the threshold value is specified as a value between 0 and 1, even if I
is of class uint8. If I is uint8, the threshold value you supply is multiplied by
255 to determine the actual threshold to use.
The example below shows an image and a representation of its quadtree
decomposition. Each black square represents a homogeneous block, and the
white lines represent the boundaries between blocks. Notice how the blocks are
smaller in areas corresponding to large changes in intensity in the image.
You can also supply qtdecomp with a function (rather than a threshold value)
for deciding whether to split blocks; for example, you might base the decision
7-12
www.MatlabSite.com
Image Analysis
on the variance of the block. See the reference entry for qtdecomp in Chapter
11 for more information.
For an interactive demonstration of quadtree decomposition, try running
qtdemo.
www.MatlabSite.com
7-13
7
Analyzing and Enhancing Images
Ima ge Enha ncement
Image enhancement techniques are used to improve an image, where
“improve” is sometimes defined objectively (e.g., increase the signal-to-noise
ratio), and sometimes subjectively (e.g., make certain features easier to see by
modifying the colors or intensities).
This section discusses these image enhancement techniques:
• Intensity adjustment
• Noise removal
The functions described in this section apply primarily to grayscale intensity
images. However, some of these functions can be applied to color images as
well. For information about how these functions work with color images, see
the reference entries for the individual functions in Chapter 11.
Intensity Adjustm ent
Intensity adjustment is a technique for mapping an image’s intensity values to
a new range. For example, look at the rice image and its histogram on page 7-9.
Notice that the image has rather low contrast, and that the histogram indicates
no values below 40 or above 255. If you remap the data values to fill the entire
intensity range [0,255], you can increase the contrast of the image.
You can do this kind of adjustment with the imadjust function. For example,
this code performs the adjustment described above:
I = imread('rice.tif');
J = imadjust(I,[0.15 0.9],[0 1]);
Notice that the intensities are specified as values between 0 and 1, even if I is
of class uint8. If I is uint8, the values you supply are multiplied by 255 to
determine the actual values to use.
7-14
www.MatlabSite.com
Image Enhancement
Now display the adjusted image and its histogram:
imshow(J)
figure, imhist(J,64)
Notice the increased contrast in the image, and that the histogram now fills the
entire range.
Similarly, you can decrease the contrast of an image by narrowing the range of
the data, as in this call:
J = imadjust(I,[0 1],[0.3 0.8]);
The general syntax is:
J = imadjust(I,[low high],[bottom top])
where low and high are the intensities in the input image, which are mapped
to bottom and top in the output image.
In addition to increasing or decreasing contrast, you can perform a wide variety
of other image enhancements with imadjust. In the example below, the man’s
coat is too dark to reveal any detail. The call to imadjust maps the range [0,51]
in the original image to [128,255] in the output image. This brightens the
www.MatlabSite.com
7-15
7
Analyzing and Enhancing Images
image considerably, and also widens the dynamic range of the dark portions of
the original image, making it much easier to see the details in the coat.
I = imread('cameraman.tif');
J = imadjust(I,[0 0.2],[0.5 1]);
imshow(I)
figure, imshow(J)
Notice that this operation results in much of the image being washed out. This
is because all values above 51 in the original image get mapped to 255 in the
adjusted image.
Gamma Correction
imadjust maps low to bottom, and high to top. By default, the values between
low and high are mapped linearly to values between bottom and top. For
example, the value halfway between low and high corresponds to the value
halfway between bottom and top.
imadjust can accept an additional argument which specifies the gamma
correction factor. Depending on the value of gamma, the mapping between
values in the input and output images may be nonlinear. For example, the
value halfway between low and high may map to a value either greater than
or less than the value halfway between bottom and top.
Gamma can be any value between 0 and infinity. If gamma is 1 (the default),
the mapping is linear. If gamma is less than 1, the mapping is weighted toward
higher (brighter) output values. If gamma is greater than than 1, the mapping
is weighted toward lower (darker) output values.
7-16
www.MatlabSite.com
Image Enhancement
The figure below illustrates this relationship. The three transformation curves
show how values are mapped when gamma is less than, equal to, and greater
than 1. (In each graph, the x-axis represents the intensity values in the input
image, and the y-axis represents the intensity values in the output image.)
γ<1
γ=1
γ>1
top
top
top
bottom
bottom
bottom
low
high
low
high
low
high
The example below illustrates gamma correction. Notice that in the call to
imadjust, the data ranges of the input and output images are specified as
empty matrices. When you specify an empty matrix, imadjust uses the default
range of [0,1]. In the example, both ranges are left empty; this means that
gamma correction is applied without any other adjustment of the data.
[X,map] = imread('forest.tif')
I = ind2gray(X,map);
J = imadjust(I,[],[],0.5);
imshow(I)
figure, imshow(J)
www.MatlabSite.com
7-17
7
Analyzing and Enhancing Images
Histogram Equalization
The process of adjusting intensity values can be done automatically by the
histeq function. histeq performs histogram equalization, which involves
transforming the intensity values so that the histogram of the output image
approximately matches a specified histogram. (By default, histeq tries to
match a flat histogram with 64 bins, but you can specify a different histogram
instead; see the reference entry for histeq in Chapter 11.)
This example illustrates using histeq to adjust an intensity image. The
original image has low contrast, with most values in the middle of the intensity
range. histeq produces an output image having values evenly distributed
throughout the range.
I = imread('pout.tif');
J = histeq(I);
imshow(I)
figure, imshow(J)
7-18
www.MatlabSite.com
Image Enhancement
The example below shows the histograms for the two images:
imhist(I)
figure, imhist(J)
histeq can return an additional 1-by-256 vector that shows, for each possible
input value, the resulting output value. (The values in this vector are in the
www.MatlabSite.com
7-19
7
Analyzing and Enhancing Images
range [0,1], even if the image is of class uint8.) You can plot this data to get the
tranformation curve. For example:
I = imread('pout.tif');
[J,T] = histeq(I);
plot((0:255)/255,T);
Notice how this curve reflects the histograms in the previous figure, with the
input values being mostly between 0.3 and 0.6, while the output values are
distributed evenly between 0 and 1.
For an interactive demonstration of intensity adjustment, try running
imadjdemo.
N oise Rem ova l
Digital images are prone to a variety of types of noise. There are several ways
that noise can be introduced into an image, depending on how the image is
created. For example:
• If the image is scanned from a photograph made on film, the film grain is a
source of noise. Noise can also be the result of damage to the film, or be
introduced by the scanner itself.
• If the image is acquired directly in a digital format, the mechanism for
gathering the data (such as a CCD detector) can introduce noise.
• Electronic transmission of image data can introduce noise.
7-20
www.MatlabSite.com
Image Enhancement
The toolbox provides a number of different ways to remove or reduce noise in
an image. Different methods are better for different kinds of noise. The
methods available include:
• Linear filtering
• Median filtering
• Adaptive filtering
Also, in order to simulate the effects of some of the problems listed above, the
toolbox provides the imnoise function, which you can use to add various types
of noise to an image. The examples in this section use this function.
Linear Filtering
You can use linear filtering to remove certain types of noise. Certain filters,
such as averaging or Gaussian filters, are appropriate for this purpose. For
example, an averaging filter is useful for removing grain noise from a
photograph. Because each pixel gets set to the average of the pixels in its
neighborhood, local variations caused by grain are reduced.
For more information about linear filtering, see Chapter 5.
M edian Filtering
Median filtering is similar to using an averaging filter, in that each output
pixel is set to an “average” of the pixel values in the neighborhood of the
corresponding input pixel. However, with median filtering, the value of an
output pixel is determined by the median of the neighborhood pixels, rather
than the mean. The median is much less sensitive than the mean to extreme
values (called outliers). Median filtering is therefore better able to remove
these outliers without reducing the sharpness of the image.
The medfilt2 function implements median filtering. The example below
compares using an averaging filter and medfilt2 to remove salt and pepper
noise. This type of noise consists of random pixels being set to black or white
(the extremes of the data range). In both cases the size of the neighborhood
used for filtering is 3-by-3.
www.MatlabSite.com
7-21
7
Analyzing and Enhancing Images
First, read in the image and add noise to it.
I = imread('eight.tif');
J = imnoise(I,'salt & pepper',0.02);
imshow(I)
figure, imshow(J)
Now filter the noisy image and display the results. Notice that medfilt2 does
a better job of removing noise, with less blurring of edges.
K = filter2(fspecial('average',3),J)/255;
L = medfilt2(J,[3 3]);
imshow(K)
figure, imshow(L)
Median filtering is a specific case of order-statistic filtering. For information
about order-statistic filtering, see the reference entry for the ordfilt2 function
in Chapter 11.
7-22
www.MatlabSite.com
Image Enhancement
Adaptive Filtering
The wiener2 function applies a Wiener filter (a type of linear filter) to an image
adaptively, tailoring itself to the local image variance. Where the variance is
large, wiener2 performs little smoothing. Where the variance is small, wiener2
performs more smoothing.
This approach often produces better results than linear filtering. The adaptive
filter is more selective than a comparable linear filter, preserving edges and
other high frequency parts of an image. In addition, there are no design tasks;
the wiener2 function handles all preliminary computations, and implements
the filter for an input image. wiener2, however, does require more computation
time than linear filtering.
wiener2 work best when the noise is constant-power (“white”) additive noise,
such as Gaussian noise. This example applies wiener2 to an image of Saturn
that has had Gaussian noise added:
I = imread('saturn.tif');
J = imnoise(I,'gaussian',0,0.005);
K = wiener2(J,[5 5]);
imshow(J)
figure, imshow(K)
For an interactive demonstration of filtering to remove noise, try running
nrfiltdemo.
www.MatlabSite.com
7-23
7
Analyzing and Enhancing Images
7-24
www.MatlabSite.com
8
Binary Image Operations
Overview . . . . . .
Neighborhoods . . . . .
Padding of Borders . . .
Displaying Binary Images
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
8-2
8-2
8-2
8-3
Morphological Operations . . . . . . . . . . . . . . 8-4
Dilation and Erosion . . . . . . . . . . . . . . . . . 8-4
Related Operations . . . . . . . . . . . . . . . . . . 8-7
Object-Based Operations . . .
4- and 8-Connected Neighborhoods
Perimeter Determination . . . .
Flood Fill . . . . . . . . . . .
Connected-Components Labeling .
Object Selection . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
8-10
8-10
8-12
8-13
8-15
8-16
Feature Measurement . . . . . . . . . . . . . . . 8-18
Image Area . . . . . . . . . . . . . . . . . . . . . 8-18
Euler Number . . . . . . . . . . . . . . . . . . . . 8-19
Lookup-Table Operations . . . . . . . . . . . . . . 8-20
www.MatlabSite.com
8
Binary Image O perations
O verview
A binary image is an image in which each pixel assumes one of only two
discrete values. Essentially, these two values correspond to on and off.
Looking at an image in this way makes it easier to distinguish structural
features. For example, in a binary image, it is easy to distinguish objects from
the background.
In the Image Processing Toolbox, a binary image is stored as a two-dimensional
matrix of 0’s (which represent off pixels) and 1’s (which represent on pixels).
The on pixels are the foreground of the image, and the off pixels are the
background.
Binary image operations return information about the form or structure of
binary images only. To perform these operations on another type of image, you
must first convert it to binary (using, for example, the im2bw function).
N eighborhoods
Most binary image algorithms work with groups of pixels called neighborhoods.
A pixel’s neighborhood is some set of pixels, defined by their locations relative
to that pixel. The neighborhood can include or omit the pixel itself, and the
pixels included in the neighborhood are not necessarily adjacent to the pixel of
interest. Different types of neighborhoods are used for different binary
operations.
Pa dding of Borders
If a pixel is near the border of an image, some of the pixels in its neighborhood
may be missing. For example, if the neighborhood is defined to include the pixel
directly above the pixel of interest, then a pixel in the top row of an image will
be missing this neighbor.
In order to determine how to process these pixels, the binary image functions
pad the borders of the image, usually with 0’s. In other words, these functions
process the border pixels by assuming that the image is surrounded by
additional rows and columns of 0’s. These rows and columns do not become part
of the output image and are used only as parts of the neighborhoods of the
actual pixels in the image. However, the padding can in some cases produce
border effects, in which the regions near the borders of the output image do not
appear to be homogeneous with the rest of the image.
8-2
www.MatlabSite.com
O verview
Displa y ing Bina r y Im a ges
When you display a binary image with imshow, by default the foreground (i.e.,
the on pixels) is white and the background is black. You may prefer to invert
these images when you display or print them, or else display them using a
colormap. See Chapter 2 for more information about displaying binary images.
The remainder of this chapter describes the functions in the Image Processing
Toolbox that perform various types of binary image operations. These
operations include:
• Morphological operations
• Object-based operations
• Feature measurement
• Lookup table operations
www.MatlabSite.com
8-3
8
Binary Image O perations
M orphologica l O pera tions
Morphological operations are methods for processing binary images based on
shapes. These operations take a binary image as input, and return a binary
image as output. The value of each pixel in the output image is based on the
corresponding input pixel and its neighbors. By choosing the neighborhood
shape appropriately, you can construct a morphological operation that is
sensitive to specific shapes in the input image.
Dila tion a nd Erosion
The main morphological operations are dilation and erosion. Dilation and
erosion are related operations, although they produce very different results.
Dilation adds pixels to the boundaries of objects (i.e., changes them from off to
on), while erosion removes pixels on object boundaries (changes them from on
to off).
Each dilation or erosion operation uses a specified neighborhood. The state of
any given pixel in the output image is determined by applying a rule to the
neighborhood of the corresponding pixel in the input image. The rule used
defines the operation as a dilation or an erosion:
• For dilation, if any pixel in the input pixel’s neighborhood is on, the output
pixel is on. Otherwise, the output pixel is off.
• For erosion, if every pixel in the input pixel’s neighborhood is on, the output
pixel is on. Otherwise, the output pixel is off.
The neighborhood for a dilation or erosion operation can be of arbitrary shape
and size. The neighborhood is represented by a structuring element, which is a
matrix consisting of only 0’s and 1’s. The center pixel in the structuring element
represents the pixel of interest, while the elements in the matrix that are on
(i.e., = 1) define the neighborhood.
The center pixel is defined as floor((size(SE)+1)/2), where SE is the
structuring element. For example, in a 4-by-7 structuring element, the center
pixel is (2,4). When you construct the structuring element, you should make
sure that the pixel of interest is actually the center pixel. You can do this by
adding rows or columns of 0’s, if necessary. For example, suppose you want the
neighborhood to consist of a 3-by-3 block of pixels, with the pixel of interest in
the upper-left corner of the block. The structuring element would not be
8-4
www.MatlabSite.com
M orphological O perations
ones(3), because this matrix has the wrong center pixel. Rather, you could use
this matrix as the structuring element:
0
0
0
0
0
1
1
1
0
1
1
1
0
1
1
1
For erosion, the neighborhood consists of the on pixels in the structuring
element. For dilation, the neighborhood consists of the on pixels in the
structuring element rotated 180 degrees. (The center pixel is still selected
before the rotation.)
Suppose you want to perform an erosion operation. The figure below shows a
sample neighborhood you might use. Each neighborhood pixel is indicated by
an x, and the center pixel is the one with a circle:
x
x
x
x
x
The structuring element is therefore:
1
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
1
The state (i.e., on or off) of any given pixel in the output image is determined
by applying the erosion rule to the neighborhood pixels for the corresponding
pixel in the input image. For example, to determine the state of the pixel (4,6)
in the output image:
www.MatlabSite.com
8-5
8
Binary Image O perations
• Overlay the structuring element on the input image, with the center pixel of
the structuring element covering the pixel (4,6).
• Look at the pixels in the neighborhood of the input pixel. These are the five
pixels covered by 1’s in the structuring element. In this case the pixels are:
(2,4), (3,5), (4,6), (5,7), (6,8). If all of these pixels are on, then set the pixel in
the output image (4,6) to on. If any of these pixels is off, then set the pixel
(4,6) in the output image to off.
You perform this procedure for each pixel in the input image to determine the
state of each corresponding pixel in the output image.
Note that for pixels on borders of the image, some of the 1’s in the structuring
element are actually outside the image. These elements are assumed to cover
off pixels. As a result, the output image will usually have a black border, as in
the example below.
The Image Processing Toolbox performs dilation through the dilate function,
and erosion through the erode function. Each of these functions takes an input
image and a structuring element as input, and returns an output image.
This example illustrates the erosion operation described above:
BW1 = imread('circbw.tif');
SE = eye(5);
BW2 = erode(BW1,SE);
imshow(BW1)
figure, imshow(BW2)
Notice the diagonal streaks in the output image (on the right). These are due
to the shape of the structuring element.
8-6
www.MatlabSite.com
M orphological O perations
Rela ted O pera tions
There are many other types of morphological operations in addition to dilation
and erosion. However, many of these operations are just modified dilations or
erosions, or combinations of dilation and erosion. For example, closure consists
of a dilation operation followed by erosion with the same structuring element.
A related operation, opening, is the reverse of closure; it consists of erosion
followed by dilation.
For example, suppose you want to remove all the circuit lines from the original
circuit image, leaving only the rectangular outlines of microchips. You can
accomplish this through opening.
To perform the opening, you begin by choosing a structuring element. This
structuring element should be large enough to remove the lines when you erode
the image, but not large enough to remove the rectangles. It should consist of
all 1’s, so it removes everything but large continuous patches of foreground
pixels. Therefore, you create the structuring element like this:
SE = ones(40,30);
Next, you perform the erosion. This removes all of the lines, but also shrinks
the rectangles:
BW2 = erode(BW1,SE);
imshow(BW2)
www.MatlabSite.com
8-7
8
Binary Image O perations
Finally, you perform dilation, using the same structuring element, to restore
the rectangles to their original sizes:
BW3 = dilate(BW2,SE);
imshow(BW3)
Predefined O perations
You can use dilate and erode to implement any morphological operation that
can be defined as a set of dilations and erosions. However, there are certain
operations that are so common that the toolbox provides them as predefined
procedures. These operations are available through the bwmorph function.
bwmorph provides eighteen predefined operations, including opening and
closure.
8-8
www.MatlabSite.com
M orphological O perations
For example, suppose you want to reduce all objects in the circuit image to
lines, without changing the essential structure (topology) of the image. This
process is known as skeletonization. You can use bwmorph to do this:
BW1 = imread('circbw.tif');
BW2 = bwmorph(BW1,'skel',Inf);
imshow(BW1)
figure, imshow(BW2)
The third argument to bwmorph indicates the number of times to perform the
operation. For example, if this value is 2, the operation is performed twice, with
the result of the first operation being used as the input for the second
operation. In the example above, the value is Inf. In this case bwmorph
performs the operation repeatedly until it no longer changes.
For more information about the predefined operations available, see the
reference entry for bwmorph in Chapter 11.
www.MatlabSite.com
8-9
8
Binary Image O perations
O bject-Ba sed O pera tions
In a binary image, an object is any set of connected on pixels. For example, this
matrix represents a binary image containing a single object, a 3-by-3 square.
The rest of the image is background:
0
0
0
0
0
0
0
0
1
1
1
0
0
0
1
1
1
0
0
0
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
This section discusses the types of neighborhoods used for object-based
operations, and describes how to use toolbox functions to perform:
• Perimeter determination
• Binary flood fill
• Connected-components labeling
• Object selection
4 - a nd 8 -Connected N eighborhoods
For many operations, distinguishing objects depends on the convention used to
decide whether pixels are connected. There are two different conventions
typically used: 4-connected or 8-connected neighborhoods.
In an 8-connected neighborhood, all of the pixels that touch the pixel of interest
are considered, including those on the diagonals. This means that if two
adjoining pixels are on, they are part of the same object, regardless of whether
they are connected along the horizontal, vertical, or diagonal direction.
8-10
www.MatlabSite.com
O bject-Based O perations
This figure illustrates an 8-connected neighborhood:
r–1, c–1
r–1, c
r–1, c+1
r, c–1
r, c
r, c+1
r+1, c–1
r+1, c
r+1, c+1
In a 4-connected neighborhood, the pixels along the diagonals are not
considered. This means that two adjoining pixels are part of the same object
only if they are both on and are connected along the horizontal or vertical
direction.
This figure illustrates a 4-connected neighborhood:
r–1, c
r, c–1
r, c
r, c+1
r+1, c
www.MatlabSite.com
8-11
8
Binary Image O perations
The type of neighborhood you choose affects the number of objects there are in
an image and the boundaries of those objects. Therefore, the results of the
object-based operations often differ for the two types of neighborhoods.
For example, this matrix represents a binary image that has one 8-connected
object or two 4-connected objects:
0
0
0
0
0
0
0
1
1
0
0
0
0
1
1
0
0
0
0
0
0
1
1
0
0
0
0
1
1
0
0
0
0
0
0
0
Perim eter Determ ina tion
The bwperim function determines the perimeter pixels of the objects in a binary
image. You can use either a 4- or 8-connected neighborhood for perimeter
determination. A pixel is considered a perimeter pixel if it satisfies both of
these criteria:
• It is an on pixel.
• One (or more) of the pixels in its neighborhood is off.
This example finds the perimeter pixels in the circuit image:
BW1 = imread('circbw.tif');
BW2 = bwperim(BW1);
imshow(BW1)
figure, imshow(BW2)
8-12
www.MatlabSite.com
O bject-Based O perations
Flood Fill
The bwfill function performs a flood-fill operation on a binary image. You
specify a background pixel as a starting point, and bwfill changes connected
background pixels (0’s) to foreground pixels (1’s), stopping when it reaches
object boundaries. The boundaries are determined based on the type of
neighborhood you specify.
This operation can be useful in removing irrelevant artifacts from images. For
example, suppose you have a binary image, derived from a photograph, in
which the foreground objects represent spheres. In the binary image, these
objects should appear as circles, but instead are donut shaped because of
reflections in the original photograph. Before doing any further processing of
the image, you may want to first fill in the “donut holes” using bwfill.
bwfill differs from the other object-based operations in that it operates on
background pixels, rather than the foreground. If the foreground is
8-connected, the background is 4-connected, and vice versa. Note, however,
that as with the other object-based functions, you specify the connectedness of
the foreground when you call bwfill.
The implications of 4- vs. 8-connected foreground can be illustrated with this
matrix:
BW1 =
0
0
0
0
0
0
0
0
0
1
1
1
1
1
0
0
0
1
0
0
0
1
0
0
0
1
0
0
0
1
0
0
0
1
0
0
0
1
0
0
0
1
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
Regardless of whether the foreground is 4-connected or 8-connected, this image
contains a single object. However, the topology of the object differs depending
on the type of neighborhood. If the foreground is 8-connected, the object is a
closed contour, and there are two separate background elements (the part
inside the loop and the part outside). If the foreground is 4-connected, the
contour is open, and there is only one background element.
www.MatlabSite.com
8-13
8
Binary Image O perations
Suppose you call bwfill, specifying the pixel BW1(4,3) as the starting point:
bwfill(BW1,4,3)
ans =
0
0
0
0
0
0
0
0
0
1
1
1
1
1
0
0
0
1
1
1
1
1
0
0
0
1
1
1
1
1
0
0
0
1
1
1
1
1
0
0
0
1
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
bwfill fills in just the inside of the loop, because bwfill uses an 8-connected
foreground by default. If you specify a 4-connected foreground instead, bwfill
fills in the entire image, because the entire background is a single 8-connected
element:
bwfill(BW1,4,3,4)
ans =
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
Note that unlike other binary image operations, bwfill pads with 1’s rather
than 0’s along the image border. This prevents the fill operation from wrapping
around the border.
You can also use bwfill interactively, selecting starting pixels with a mouse.
See the reference entry for bwfill in Chapter 11 for more information about
this function.
8-14
www.MatlabSite.com
O bject-Based O perations
Connected-Com ponents La beling
You can use the bwlabel function to perform connected-components labeling,
which is a method for indicating each discrete object in a binary image. You
specify the input binary image and the type of neighborhood, and bwlabel
returns a matrix of the same size as the input image. The different objects in
the input image are distinguished by different integer values in the output
matrix.
For example, suppose you have this binary image:
BW1 =
0
0
0
0
0
0
0
0
0
1
1
1
0
0
0
0
0
1
1
1
0
0
0
0
0
0
0
0
1
1
1
0
0
0
0
0
1
1
1
0
0
1
0
0
0
0
0
0
0
1
1
0
0
0
0
0
0
1
1
0
0
0
0
0
You call bwlabel, specifying 4-connected neighborhoods:
bwlabel(BW1,4)
ans =
0
0
0
0
0
0
0
0
0
1
1
1
0
0
0
0
0
1
1
1
0
0
0
0
0
0
0
0
2
2
2
0
0
0
0
0
2
2
2
0
0
3
0
0
0
0
0
0
0
3
3
0
0
0
0
0
0
3
3
0
0
0
0
0
In the output matrix, the 1’s represent one object, the 2’s a second object, and
the 3’s a third. Notice that if you had used 8-connected neighborhoods (the
default), there would be only two objects, because the first and second objects
would be a single object, connected along the diagonal.
www.MatlabSite.com
8-15
8
Binary Image O perations
The output matrix is not a binary image, and its class is double. A useful
approach to viewing it is to display it as an pseudocolor indexed image, first
adding 1 to each element, so that the data is in the proper range. Each object
displays in a different color, so the objects are easier to distinguish than in the
original image.
The example below illustrates this technique. Notice that this example uses a
colormap in which the first color (the background) is black and the other colors
are easily distinguished:
X = bwlabel(BW1,4);
map = [0 0 0;jet(3)];
imshow(X+1,map,'notruesize')
O bject Selection
You can use the bwselect function to select individual objects in a binary
image. You specify pixels in the input image, and bwselect returns a binary
image that includes only those objects from the input image that contain one of
the specified pixels.
You can specify the pixels either noninteractively or with a mouse. For
example, suppose you want to select 8-connected objects in the image displayed
in the current axes. You type:
BW2 = bwselect(8);
The cursor changes to a cross-hair when it is over the image. Click on the
objects you want to select; bwselect displays a small star over each pixel you
click on. When you are done, press Return. bwselect returns a binary image
consisting of the objects you selected, and removes the stars.
8-16
www.MatlabSite.com
O bject-Based O perations
See the reference entry for bwselect in Chapter 11 for more information about
this function.
www.MatlabSite.com
8-17
8
Binary Image O perations
Fea ture M ea surement
When you process an image, you may want to obtain information about how
certain features of the image change. For example, when you perform dilation,
you may want to determine how many pixels are changed from off to on by the
operation, or to see if the number of objects in the image changes. This section
describes two functions, bwarea and bweuler, that return two common
measures of binary images: the image area and the Euler number.
In addition, you can use the imfeature function, in combination with bwlabel,
to compute measurements of various features in a binary image. See the
reference entry for imfeature in Chapter 11 for more information.
Im a ge Area
The bwarea function returns the area of a binary image. The area is a measure
of the size of the foreground of the image. Roughly speaking, the area is the
number of on pixels in the image.
bwarea does not simply count the number of on pixels, however. Rather, bwarea
weights different pixel patterns unequally when computing the area. This
weighting compensates for the distortion that is inherent in representing a
continuous image with discrete pixels. For example, a diagonal line of 50 pixels
is longer than a horizontal line of 50 pixels. As a result of the weighting bwarea
uses, the horizontal line has area of 50, but the diagonal line has area of 62.5.
This example uses bwarea to determine how much the area of the circuit image
increases after a dilation operation:
BW1 = imread('circbw.tif');
SE = ones(5);
BW2 = dilate(BW1,SE);
increase = (bwarea(BW2) – bwarea(BW1))/bwarea(BW1);
increase =
0.3456
The dilation increases the area by about 35 percent.
For more information about the weighting pattern used by bwarea, see the
reference entry for bwarea in Chapter 11.
8-18
www.MatlabSite.com
Feature M easurement
Euler N um ber
The bweuler function returns the Euler number for a binary image. The Euler
number is a measure of the topology of an image. It is defined as the total
number of objects in the image minus the number of holes in those objects. You
can use either 4- or 8-connected neighborhoods.
This example computes the Euler number for the circuit image, using
8-connected neighborhoods:
BW1 = imread('circbw.tif');
eul = bweuler(BW1,8)
eul =
–85
In this example, the Euler number is negative, indicating that the number of
holes is greater than the number of objects.
www.MatlabSite.com
8-19
8
Binary Image O perations
Look up-Ta ble O pera tions
Certain binary image operations can be implemented most easily through
lookup tables. A lookup table is a column vector in which each element
represents the value to return for one possible combination of pixels in a
neighborhood.
You can use the makelut function to create lookup tables for various
operations. makelut creates lookup tables for 2-by-2 and 3-by-3 neighborhoods.
This figure illustrates these types of neighborhoods. Each neighborhood pixel
is indicated by an x, and the center pixel is the one with a circle:
x
x
x
x
x
x
x
x
x
x
x
x
x
2 -by-2 neighborhood
3 -by-3 neighborhood
For a 2-by-2 neighborhood, there are 16 possible permutations of the pixels in
the neighborhood. Therefore, the lookup table for this operation is a 16-element
vector. For a 3-by-3 neighborhood, there are 512 permutations, so the lookup
table is a 512-element vector.
Once you create a lookup table, you can use it to perform the desired operation
by using the applylut function.
The example below illustrates using lookup-table operations to modify an
image containing text. You begin by writing a function that returns 1 if three
or more pixels in the 3-by-3 neighborhood are 1, and 0 otherwise. You then call
makelut, passing in this function as the first argument, and using the second
argument to specify a 3-by-3 lookup table:
f = inline('sum(x(:)) >= 3');
lut = makelut(f,3);
lut is returned as a 512-element vector of 1’s and 0’s. Each value is the output
from the function for one of the 512 possible permutations.
8-20
www.MatlabSite.com
Lookup-Table O perations
You then perform the operation using applylut:
BW1 = imread('text.tif');
BW2 = applylut(BW1,lut);
imshow(BW1)
figure, imshow(BW2)
For information about how applylut maps pixel combinations in the image to
entries in the lookup table, see the reference entry for applylut in Chapter 11.
Note that you cannot use makelut and applylut for neighborhoods of sizes
other than 2-by-2 or 3-by-3. These functions support only 2-by-2 and 3-by-3
neighborhoods, because lookup tables are not practical for neighborhoods
larger than 3-by-3. For example, a lookup table for a 4-by-4 neighborhood
would have 65,536 entries.
www.MatlabSite.com
8-21
8
Binary Image O perations
8-22
www.MatlabSite.com
9
Region-Based Processing
Overview
. . . . . . . . . . . . . . . . . . . . . 9-2
Specifying a Region of Interest . . . . . . . . . . . 9-3
Selecting a Polygon . . . . . . . . . . . . . . . . . . 9-3
Other Selection Methods . . . . . . . . . . . . . . . 9-5
Filtering a Region
Filling a Region
. . . . . . . . . . . . . . . . . 9-6
. . . . . . . . . . . . . . . . . . 9-8
www.MatlabSite.com
9
Region-Based Processing
O verview
This chapter describes operations that you can perform on a selected region of
an image. It discusses these topics:
• Specifying a region
• Filtering a region
• Filling a region
For an interactive demonstration of region-based processing, try running
roidemo.
9-2
www.MatlabSite.com
Specifying a Region of Interest
Specifying a Region of Interest
A region of interest is a portion of an image that you want to filter or perform
some other operation on. You define a region of interest by creating a binary
mask, which is a binary image of the same size as the image you want to
process. The mask contains 1’s for all pixels that are part of the region of
interest, and 0’s everywhere else.
This section discusses methods for creating binary masks.
Selecting a Poly gon
You can use the roipoly function to specify a polygonal region of interest. If
you call roipoly with no input arguments, the cursor changes to a cross hair
when it is over the image displayed in the current axes. You can then specify
the vertices of the polygon by clicking on points in the image with the mouse.
When you are done selecting vertices, press Return; roipoly returns a binary
image, of the same size as the input image, containing 1’s inside the specified
polygon, and 0’s everywhere else.
www.MatlabSite.com
9-3
9
Region-Based Processing
The example below illustrates using roipoly to create a binary mask. The
border of the selected region is shown in red on the original image.
I = imread('pout.tif');
imshow(I)
BW = roipoly;
imshow(BW)
You can also use roipoly noninteractively. See the reference entry for roipoly
in Chapter 11 for more information.
9-4
www.MatlabSite.com
Specifying a Region of Interest
O ther Selection M ethods
roipoly provides an easy way to create a binary mask. However, you can use
any binary image as a mask, provided that the binary image is the same size
as the image being filtered.
For example, suppose you want to filter the intensity image I, but only filter
those pixels whose values are greater than 0.5. You could create the
appropriate mask with this command:
BW = (I > 0.5);
You can also use the roicolor function to define the region of interest based
on a color or intensity range. For more information, see the reference entry for
this function in Chapter 11.
www.MatlabSite.com
9-5
9
Region-Based Processing
Filtering a Region
You can use the roifilt2 function to process a region of interest. When you
call roifilt2, you specify an intensity image, a binary mask, and a filter.
roifilt2 filters the input image, and returns an image that consists of filtered
values for pixels where the binary mask contains 1’s, and unfiltered values for
pixels where the binary mask contains 0’s. This type of operation is called
masked filtering.
This example uses the mask created on page 9-4 to increase the contrast of the
logo on the girl’s coat.
h = fspecial('unsharp');
I2 = roifilt2(h,I,BW);
imshow(I)
figure, imshow(I2)
roifilt2 also has a form that you can use to specify a function to operate on
the region of interest. In the example below, the imadjust function is used to
9-6
www.MatlabSite.com
Filtering a Region
lighten parts of an image. The mask in the example is a binary image
containing text. The resulting image has the text imprinted on it.
BW = imread('text.tif');
I = imread('cameraman.tif');
f = inline('imadjust(x,[],[],0.3)');
I2 = roifilt2(I,BW,f);
imshow(I2)
Note that roifilt2 is best suited to operations that return data in the same
range as in the original image, because the output image takes some of its data
directly from the input image. Certain filtering operations can result in values
outside the normal image data range (i.e., [0,1] for images of class double,
[0,255] for images of class uint8). For more information about roifilt2, see
the reference entry in Chapter 11.
www.MatlabSite.com
9-7
9
Region-Based Processing
Filling a Region
You can use the roifill function to fill a region of interest, interpolating from
the borders of the region. This function is useful for image editing, to remove
extraneous details or artifacts.
roifill performs the fill using an interpolation method based on Laplace’s
equation. This method results in the smoothest possible fill, given the values
on the boundary of the region.
As with roipoly, you select the region of interest with the mouse. When you
complete the selection, roifill returns an image with the selected region filled
in.
9-8
www.MatlabSite.com
Filling a Region
This example uses roifill to modify the trees image. The border of the
selected region is shown in red on the original image.
load trees
I = ind2gray(X,map);
imshow(I)
I2 = roifill;
imshow(I2)
www.MatlabSite.com
9-9
9
Region-Based Processing
9-10
www.MatlabSite.com
10
Color
Overview
. . . . . . . . . . . . . . . . . . . . . 10-2
. . . . . . . . 10-3
Working with Different Color Depths
Reducing the Number of Colors in an Image
Using rgb2ind . . . . . . . . . . . . . . .
Using imapprox . . . . . . . . . . . . . .
Dithering . . . . . . . . . . . . . . . . .
Converting to Other Color Spaces
NTSC Format . . . . . . . . . .
YCbCr Format . . . . . . . . . .
HSV Format . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 10-9
. 10-9
10-10
10-10
www.MatlabSite.com
10-5
10-5
10-7
10-8
10
C olor
O verview
This chapter describes toolbox functions that help you work with color image
data. It discusses these topics:
• Working on systems with different color depths
• Reducing the number of colors in an image
• Converting an image to a different color space
Note that “color” includes shades of gray, so much of the discussion in this
chapter applies to grayscale images as well as color images.
For additional information about how MATLAB handles color, see the Using
MATLAB Graphics manual.
10-2
www.MatlabSite.com
W orking w ith Different C olor Depths
W ork ing w ith Different Color Depths
Most computer displays use either 8, 16, or 24 bits per screen pixel. The
number of bits per pixel determines how many different colors can be
displayed.
24-bit displays provide optimal color resolution. A 24-bit display uses 8 bits for
each of the three color components; therefore there are 256 levels each of red,
green, and blue. This makes it possible to support 16,777,216 (i.e., 224) distinct
colors. Of these colors, 256 are shades of gray. (These are the colors where
R=G=B.)
16-bit displays also provide a large number of colors. A 16-bit display uses 5
bits for each color component, resulting in 32 shades each of red, green, and
blue. (Some 16-bit displays use the remaining bit to increase the number of
shades of green to 64.) 16-bit displays support 32,768 (i.e., 215) distinct colors
(or twice this number if all 16 bits are used). Of these colors, 32 are shades of
gray.
8-bit displays support a much more limited number of colors. An 8-bit display
can produce any of the colors available on a 24-bit display, but only 256 distinct
colors can appear at one time. There are 256 shades of gray available, but using
all of them takes up all of the available color slots.
To determine your system’s color depth, enter this MATLAB command:
get(0,'ScreenDepth')
MATLAB returns an integer representing the number of bits per pixel. Note
that on some systems, MATLAB may return 32. These systems produce 24-bit
color; the remaining 8 bits are for an alpha (transparency) channel that
MATLAB does not currently use.
Depending on your system, you may be able to choose the color depth you want
to use. (There may be tradeoffs between color depth and screen resolution.) In
general, 24-bit display mode produces the best results. If you need to use a
lower color depth, 16-bit is generally preferable to 8-bit. However, keep in mind
that 16-bit color has certain limitations:
www.MatlabSite.com
10-3
10
C olor
• An image may have finer gradations of color than a 16-bit display can
represent. If a color is unavailable, MATLAB uses the closest approximation.
• There are only 32 shades of gray available. If you are working primarily with
grayscale images, you may get better display results using 8-bit display
mode.
Regardless of the number of colors your system can display, MATLAB can store
and process images with up to 224 colors (or even more, if the image data is of
class double). These images display best on systems with 24-bit color, and
usually look fine on 16-bit systems as well. (On a 16-bit system, if an image
uses colors that the system is not capable of displaying, MATLAB uses color
approximation to display the image.)
If your display supports only 8-bit color, you may run into problems due to the
limited number of color slots. See Chapter 2 for information about working
around these problem. Also, see the next section for information about reducing
the number of colors used by an image.
10-4
www.MatlabSite.com
Reducing the N umber of C olors in an Image
Reducing the N umber of Colors in a n Ima ge
On systems with 24-bit color, RGB (truecolor) images can display up to 224 (i.e.,
16,777,216) colors. On systems with lower color depths, RGB images display
reasonably well, because MATLAB automatically uses color approximation
and dithering if needed. MATLAB can also read and write these images using
imread and imwrite, without any loss of color resolution.
Indexed images, however, may cause problems if they have a large number of
colors. In general, you should limit indexed images to 256 colors, because:
• On systems with 8-bit color, indexed images with more than 256 colors do not
display properly.
• On some platforms, colormaps cannot exceed 256 entries.
• If an indexed image has more than 256 colors, MATLAB cannot store the
image data in a uint8 array, and must use an array of class double instead.
• Most image file formats limit indexed images to 256 colors. imwrite produces
an error if you try to write an indexed image with more colors than this to
one of these formats.
This section describes how to reduce the number of colors in an indexed or RGB
image:
• The rgb2ind function converts an RGB image to an indexed image, and
provides a number of methods for approximating the original image with
fewer colors.
• The imapprox function takes an indexed image and returns a new indexed
image that uses fewer colors, using the same color-approximation methods
that rgb2ind uses.
In addition, this section includes a discussion of dithering, which is used by
these functions to increase the apparent color resolution of an image.
Using r gb2 ind
rgb2ind converts an RGB image to an indexed image, reducing the number of
colors in the process. This function provides these methods for approximating
the colors in the original image:
www.MatlabSite.com
10-5
10
C olor
• Quantization
• Colormap mapping
The quality of the resulting image depends on the approximation method you
use, the range of colors in the input image, and whether or not you use
dithering. Note that different methods work better for different images. See
page 10-8 for information about dithering.
Q uantization
In general, the most effective approach to reducing the number of colors in an
image is quantization. This approach involves cutting the RGB color cube into
a number of smaller regions, and then mapping all colors that fall within a
given region to the value at the center of that region. Quantization ensures that
the colors in the output image do not deviate too much from those in the input
image, and also enables you to control the maximum number of output colors.
rgb2ind supports two quantization methods: uniform quantization and
minimum variance quantization. These methods differ in the approach used to
divide up the RGB cube. With uniform quantization, the color cube is cut up
into equal-sized cubes. With minimum variance quantization, the color cube is
cut up into smaller boxes (not necessarily cubes) of different sizes; the sizes of
the boxes depend on how the colors are distributed in the image.
For a given number of colors, minimum variance quantization produces better
results than uniform quantization, because it takes into account the actual
data. Minimum variance quantization allocates more of the colormap entries
to colors that appear frequently in the input image, and fewer to colors that
appear infrequently. For example, if the input image has many shades of green
and few shades of red, there will be many more greens than reds in the output
colormap. The resulting color resolution is higher than with uniform
quantization. The computation takes longer, however.
To perform uniform quantization, you call rgb2ind and specify a tolerance. The
tolerance determines the size of the cubes that the RGB color cube is cut into.
For example, if you specify a tolerance of 0.1, the edges of the cubes are
one-tenth the length of the RGB cube. The total number of small cubes is:
n = (floor(1/tol)+1)^3
Each cube represents a single color in the output image. Therefore, the
maximum length of the colormap is n. rgb2ind removes any colors that do not
appear in the input image, so the actual colormap may be much smaller than n.
10-6
www.MatlabSite.com
Reducing the N umber of C olors in an Image
To perform minimum variance quantization, you call rgb2ind and specify the
maximum number of colors in the output image’s colormap. The number you
specify determines how many cubes the RGB color cube is divided into. The
resulting colormap usually has the number of entries you specify, because the
color cube is divided so that each region contains at least one color that appears
in the input image. If the input image actually uses fewer colors than the
number you specify, the output colormap is also smaller. In this case, the
output image has all of the colors of the input image, and there is no loss of color
resolution in the conversion.
These commands use minimum variance quantization to create an indexed
image with 185 colors:
RGB = imread('flowers.tif');
[X,map] = rgb2ind(RGB,185);
Colormap M apping
If you specify the actual colormap to use, rgb2ind uses colormap mapping to
find the colors in the specified colormap that best match the colors in the RGB
image. This method is useful if you need to create images that use a fixed
colormap. For example, if you want to display multiple indexed images on an
8-bit display, you can avoid color problems by having them all use the same
colormap. Colormap mapping produces a good approximation if the specified
colormap has similar colors to those in the RGB image. If the colormap does not
have similar colors to those in the RGB image, this method produces poor
results.
This example illustrates mapping two images to the same colormap. The
colormap specified includes colors all throughout the RGB cube, so the output
images are able to reasonably approximate the input images.
RGB1
RGB2
X1 =
X2 =
= imread('autumn.tif');
= imread('flowers.tif');
rgb2ind(RGB1,colorcube(128));
rgb2ind(RGB2,colorcube(128));
Using im a pprox
imapprox is based on rgb2ind, and provides the same approximation methods.
Use imapprox when you need to reduce the number of colors in an indexed
image. Essentially, imapprox first calls ind2rgb to convert the image to RGB
www.MatlabSite.com
10-7
10
C olor
format, and then calls rgb2ind to return a new indexed image with fewer
colors.
For example, these commands create a version of the trees image with 64
colors, rather than the original 128:
load trees
[Y,newmap] = imapprox(X,map,64);
Dithering
When you use rgb2ind or imapprox to reduce the number of colors in an image,
the resulting image may look inferior to the original, because some of the colors
are lost. rgb2ind and imapprox both perform dithering to increase the
apparent color resolution of the output image. Dithering changes the colors of
pixels in a neighborhood, so that the average color around each pixel
approximates the original RGB color. Dithering provides this extra color
resolution at the expense of spatial resolution, and it adds high frequency
noise, but it typically results in a more visually pleasing approximation.
If you do not want the output image to be dithered, you can specify this when
you call rgb2ind or imapprox. For example:
[X,map] = rgb2ind(RGB,128,'nodither');
10-8
www.MatlabSite.com
C onverting to O ther C olor Spaces
Converting to O ther Color Spa ces
The Image Processing Toolbox represents colors as RGB values, either directly
(in an RGB image) or indirectly (in an indexed image). However, there are
other models besides RGB for representing colors numerically. For example, a
color can be represented by its hue, saturation, and value components (HSV)
instead. The various models for color data are called color spaces.
The functions in the Image Processing Toolbox that work with color assume
that images use the RGB color space. The toolbox provides support for other
color spaces though a set of conversion functions. You can use these functions
to convert between RGB and these color spaces:
• National Television Systems Committee (NTSC) format
• YCbCr format
• Hue, saturation, value (HSV) format
This section describes these color spaces and the conversion routines for
working with them.
N TSC Form a t
The NTSC format is used in televisions in the United States. One of the main
advantages of this format is that grayscale information is separated from color
data, so the same signal can be used for both color and black and white sets. In
this NTSC format, image data consists of three components: luminance (Y),
hue (I), and saturation (Q). The first component, luminance, represents
grayscale information, while the last two components make up chrominance
(color information).
The function rgb2ntsc converts colormaps or RGB images to the NTSC color
space. ntsc2rgb performs the reverse operation.
For example, these commands convert the flowers image to NTSC format:
RGB = imread('flowers.tif');
YIQ = rgb2ntsc(RGB);
Because luminance is one of the components of the NTSC format, the RGB to
NTSC conversion is also useful for isolating the gray level information in an
image. The toolbox functions rgb2gray and ind2gray use the rgb2ntsc
function to extract the grayscale information from a color image.
www.MatlabSite.com
10-9
10
C olor
For example, these commands are equivalent to calling rgb2gray:
YIQ = rgb2ntsc(RGB);
I = YIQ(:,:,1);
YCbCr Form a t
The YCbCr format is widely used for digital video. In this format, luminance
information is stored as a single component (Y), and chrominance information
is stored as two color difference components (Cb and Cr). Cb represents the
difference between the blue component and a reference value, and Cr
represents the difference between the red component and a reference value.
YCbCr data can be double precision, but the color space is particularly well
suited to uint8 data. For uint8 images, the data range for Y is [16,235], and
the range for Cb and Cr is [16,240]. YCbCr leaves room at the top and bottom
of the full uint8 range so that additional (non-image) information can be
included in a video stream.
The function rgb2ycbcr converts colormaps or RGB images to the YCbCr color
space. ycbcr2rgb performs the reverse operation.
For example, these commands convert the flowers image to YCbCr format:
RGB = imread('flowers.tif');
YCBCR = rgb2ycbcr(RGB);
H SV Form a t
The functions rgb2hsv and hsv2rgb convert images between the RGB and hue,
saturation, value (HSV) color spaces. The HSV color space is often used for
picking colors (e.g., of paints or inks) from a color wheel or palette, because it
corresponds better to how people experience color than the RGB color space
does.
As hue varies from 0 to 1.0, the corresponding colors vary from red, through
yellow, green, cyan, blue, and magenta, back to red. As saturation varies from
0 to 1.0, the corresponding colors vary from unsaturated (shades of gray) to
fully saturated (no white component). As value, or brightness, varies from 0 to
1.0, the corresponding colors become increasingly brighter.
10-10
www.MatlabSite.com
C onverting to O ther C olor Spaces
The figure below illustrates the HSV color space:
Hue
Hue
1
0
1
Saturation
Value
0
1
.5
0.5
0
0
These commands convert an RGB image to HSV color space:
RGB = imread('flowers.tif');
HSV = rgb2hsv(RGB);
www.MatlabSite.com
10-11
10
C olor
10-12
www.MatlabSite.com
11
Reference
www.MatlabSite.com
11
Reference
This chapter provides detailed descriptions of the functions in the Image
Processing Toolbox. It begins with a list of functions grouped by subject area
and continues with the reference entries in alphabetical order.
The list of functions includes all functions in the Image Processing Toolbox
itself, plus a few functions in MATLAB that are especially useful for image
processing. All of the functions listed have reference entries, with these
exceptions:
• The MATLAB functions image, imagesc, and interp2. For information about
these functions, see the online MATLAB Function Reference.
• The Image Processing Toolbox demo functions and slideshow functions. For
information about any of these functions, run the demo or slideshow and
click the Info button.
Im a ge Displa y
11-2
colorbar
Display colorbar (MATLAB)
getimage
Get image data from axes
image
Create and display image object (MATLAB)
imagesc
Scale data and display as image (MATLAB)
immovie
Make movie from multiframe indexed image
imshow
Display image
montage
Display multiple image frames as rectangular montage
subimage
Display multiple images in single figure
truesize
Adjust display size of image
warp
Display image as texture-mapped surface
zoom
Zoom in and out of image or 2-D plot (MATLAB)
www.MatlabSite.com
Im a ge File I/ O
imfinfo
Return information about image file (MATLAB)
imread
Read image file (MATLAB)
imwrite
Write image file (MATLAB)
Geom etric O pera tions
imcrop
Crop image
imresize
Resize image
imrotate
Rotate image
interp2
2-D data interpolation (MATLAB)
Pix el Va lues a nd Sta tistics
corr2
Compute 2-D correlation coefficient
imcontour
Create contour plot of image data
imfeature
Compute feature measurements for image regions
imhist
Display histogram of image data
impixel
Determine pixel color values
improfile
Compute pixel-value cross-sections along line segments
mean2
Compute mean of matrix elements
pixval
Display information about image pixels
std2
Compute standard deviation of matrix elements
www.MatlabSite.com
11-3
11
Reference
Im a ge Ana lysis
edge
Find edges in intensity image
qtdecomp
Perform quadtree decomposition
qtgetblk
Get block values in quadtree decomposition
qtsetblk
Set block values in quadtree decomposition
Im a ge Enha ncement
histeq
Enhance contrast using histogram equalization
imadjust
Adjust image intensity values or colormap
imnoise
Add noise to an image
medfilt2
Perform 2-D median filtering
ordfilt2
Perform 2-D order-statistic filtering
wiener2
Perform 2-D adaptive noise-removal filtering
Linea r Filtering
11-4
conv2
Perform 2-D convolution (MATLAB)
convmtx2
Compute 2-D convolution matrix
convn
Perform N-D convolution (MATLAB)
filter2
Perform 2-D filtering (MATLAB)
fspecial
Create predefined filters
www.MatlabSite.com
Linea r 2 -D Filter Design
freqspace
Determine 2-D frequency response spacing (MATLAB)
freqz2
Compute 2-D frequency response
fsamp2
Design 2-D FIR filter using frequency sampling
ftrans2
Design 2-D FIR filter using frequency transformation
fwind1
Design 2-D FIR filter using 1-D window method
fwind2
Design 2-D FIR filter using 2-D window method
Im a ge Tra nsforms
dct2
Compute 2-D discrete cosine transform
dctmtx
Compute discrete cosine transform matrix
fft2
Compute 2-D fast Fourier transform (MATLAB)
fftn
Compute N-D fast Fourier transform (MATLAB)
fftshift
Reverse quadrants of output of FFT (MATLAB)
idct2
Compute 2-D inverse discrete cosine transform
ifft2
Compute 2-D inverse fast Fourier transform (MATLAB)
ifftn
Compute N-D inverse fast Fourier transform (MATLAB)
iradon
Compute inverse Radon transform
phantom
Generate a head phantom image
radon
Compute Radon transform
www.MatlabSite.com
11-5
11
Reference
N eighborhood a nd Block Processing
bestblk
Choose block size for block processing
blkproc
Implement distinct block processing for image
col2im
Rearrange matrix columns into blocks
colfilt
Perform neighborhood operations using columnwise
functions
im2col
Rearrange image blocks into columns
nlfilter
Perform general sliding-neighborhood operations
Bina ry Im a ge O pera tions
11-6
applylut
Perform neighborhood operations using lookup tables
bwarea
Compute area of objects in binary image
bweuler
Compute Euler number of binary image
bwfill
Fill background regions in binary image
bwlabel
Label connected components in binary image
bwmorph
Perform morphological operations on binary image
bwperim
Determine perimeter of objects in binary image
bwselect
Select objects in binary image
dilate
Perform dilation on binary image
erode
Perform erosion on binary image
makelut
Construct lookup table for use with applylut
www.MatlabSite.com
Region-Ba sed Processing
roicolor
Select region of interest, based on color
roifill
Smoothly interpolate within arbitrary region
roifilt2
Filter a region of interest
roipoly
Select polygonal region of interest
Colorm a p M a nipula tion
brighten
Brighten or darken colormap (MATLAB)
cmpermute
Rearrange colors in colormap
cmunique
Find unique colormap colors and corresponding image
colormap
Set or get color lookup table (MATLAB)
imapprox
Approximate indexed image by one with fewer colors
rgbplot
Plot RGB colormap components (MATLAB)
Color Spa ce Conversions
hsv2rgb
Convert HSV values to RGB color space (MATLAB)
ntsc2rgb
Convert NTSC values to RGB color space
rgb2hsv
Convert RGB values to HSV color space (MATLAB)
rgb2ntsc
Convert RGB values to NTSC color space
rgb2ycbcr
Convert RGB values to YCbCr color space
ycbcr2rgb
Convert YCbCr values to RGB color space
www.MatlabSite.com
11-7
11
Reference
Im a ge Types a nd Type Conversions
dither
Convert image using dithering
gray2ind
Convert intensity image to indexed image
grayslice
Create indexed image from intensity image by thresholding
im2bw
Convert image to binary image by thresholding
im2double
Convert image array to double precision
im2uint8
Convert image array to 8-bit unsigned integers
ind2gray
Convert indexed image to intensity image
ind2rgb
Convert indexed image to RGB image
isbw
Return true for binary image
isgray
Return true for intensity image
isind
Return true for indexed image
isrgb
Return true for RGB image
mat2gray
Convert matrix to intensity image
rgb2gray
Convert RGB image or colormap to grayscale
rgb2ind
Convert RGB image to indexed image
Toolbox Preferences
11-8
iptgetpref
Get value of Image Processing Toolbox preference
iptsetpref
Set value of Image Processing Toolbox preference
www.MatlabSite.com
Dem os
dctdemo
2-D DCT image compression demo
edgedemo
Edge detection demo
firdemo
2-D FIR filtering and filter design demo
imadjdemo
Intensity adjustment and histogram equalization demo
nrfiltdemo
Noise reduction filtering demo
qtdemo
Quadtree decomposition demo
roidemo
Region-of-interest processing demo
Slide Show s
ipss001
Region labeling of steel grains
ipss002
Feature-based logic
ipss003
Correction of nonuniform illumination
www.MatlabSite.com
11-9
a pplylut
Purpose
11applylut
Perform neighborhood operations on binary images, using lookup tables
Synta x
A = applylut(BW,lut)
Description
A = applylut(BW,lut) performs a 2-by-2 or 3-by-3 neighborhood operation on
binary image BW by using a lookup table (lut). lut is either a 16-element or
512-element vector returned by makelut. The vector consists of the output
values for all possible 2-by-2 or 3-by-3 neighborhoods.
The values returned in A depend on the values in lut. For example, if lut
consists of all 1’s and 0’s, A will be a binary image.
Cla ss Support
BW and lut can be of class uint8 or double. If the class of lut is uint8, or if the
elements of lut are all integers between 0 and 255, then the class of A is uint8;
otherwise, the class of A is double.
Algorithm
applylut performs a neighborhood operation on a binary image by producing
a matrix of indices into lut, and then replacing the indices with the actual
values in lut. The specific algorithm used depends on whether you use 2-by-2
or 3-by-3 neighborhoods.
2-by-2 neighborhoods
For 2-by-2 neighborhoods, length(lut) is 16. There are 4 pixels in each
neighborhood, and 2 possible states for each pixel, so the total number of
permutations is 24 = 16.
To produce the matrix of indices, applylut convolves the binary image BW with
this matrix:
8
4
2
1
The resulting convolution contains integer values in the range [0,15]. applylut
uses the central part of the convolution, of the same size as BW, and adds 1 to
each value to shift the range to [1,16]. It then constructs A by replacing the
values in the cells of the index matrix with the values in lut that the indices
point to.
11
11-10
www.MatlabSite.com
a pplylut
3-by-3 neighborhoods
For 3-by-3 neighborhoods, length(lut) is 512. There are 9 pixels in each
neighborhood, and 2 possible states for each pixel, so the total number of
permutations is 29 = 512.
To produce the matrix of indices, applylut convolves the binary image BW with
this matrix:
256
128
64
32
16
8
4
2
1
The resulting convolution contains integer values in the range [0,511].
applylut uses the central part of the convolution, of the same size as BW, and
adds 1 to each value to shift the range to [1,512]. It then constructs A by
replacing the values in the cells of the index matrix with the values in lut that
the indices point to.
Ex a mple
In this example, you perform erosion using a 2-by-2 neighborhood. An output
pixel is on only if all four of the input pixel’s neighborhood pixels are on.
lut = makelut('sum(x(:)) == 4',2);
BW1 = imread('text.tif');
BW2 = applylut(BW1,lut);
imshow(BW1)
figure, imshow(BW2)
See Also
makelut
www.MatlabSite.com
11-11
bestblk
Purpose
11bestblk
Determine block size for block processing
Synta x
siz = bestblk([m n],k)
[mb,nb] = bestblk([m n],k)
Description
siz = bestblk([m n],k) returns, for an m-by-n image, the optimal block size
for block processing. k is a scalar specifying the maximum row and column
dimensions for the block; if the argument is omitted, it defaults to 100. siz is a
1-by-2 vector containing the row and column dimensions for the block.
[mb,nb] = bestblk([m n],k) returns the row and column dimensions for the
block in mb and nb, respectively.
Algorithm
bestblk returns the optimal block size given m, n, and k. The algorithm for
determining siz is:
• If m is less than or equal to k, return m.
• If m is greater than k, consider all values between min(m/10,k/2) and k.
Return the value that minimizes the padding required.
The same algorithm is then repeated for n.
Ex a mple
siz = bestblk([640 800],72)
siz =
64
See Also
11-12
50
blkproc
www.MatlabSite.com
blk proc
Purpose
11blkproc
Implement distinct block processing for an image
Synta x
B
B
B
B
Description
B = blkproc(A,[m n],fun) processes the image A by applying the function fun
to each distinct m-by-n block of A, padding A with zeros if necessary. fun can be
an inline function, a text string containing the name of a function, or a string
containing an expression. fun should operate on an m-by-n block, x, and return
a matrix, vector, or scalar y:
=
=
=
=
blkproc(A,[m n],fun)
blkproc(A,[m n],fun,P1,P2,...)
blkproc(A,[m n],[mborder nborder],fun,...)
blkproc(A,'indexed',...)
y = fun(x)
blkproc does not require that y be the same size as x. However, B is the same
size as A only if y is the same size as x.
B = blkproc(A,[m n],fun,P1,P2,...) passes the additional parameters
P1,P2,..., to fun.
B = blkproc(A,[m n],[mborder nborder],fun,...) defines an overlapping
border around the blocks. blkproc extends the original m-by-n blocks by
mborder on the top and bottom, and nborder on the left and right, resulting in
blocks of size (m+2*mborder)-by-(n+2*nborder). blkproc pads the border with
zeros, if necessary, on the edges of A. fun should operate on the extended block.
The line below processes an image matrix as 4-by-6 blocks, each having a row
border of 2 and a column border of 3. Because each 4-by-6 block has this 2-by-3
border, fun actually operates on blocks of size 8-by-12.
B = blkproc(A,[4 6],[2 3],fun,...)
B = blkproc(A,'indexed',...) processes A as an indexed image, padding
with zeros if the class of A is uint8, or ones if the class of A is double.
Cla ss Support
The input image A can be of any class supported by fun. The class of B depends
on the class of the output from fun.
www.MatlabSite.com
11-13
blk proc
Ex a mple
This example uses blkproc to set the pixels in each 8-by-8 block to the standard
deviation of the elements in that block.
I = imread('alumgrns.tif');
I2 = blkproc(I,[8 8],'std2(x)*ones(size(x))');
imshow(I)
figure, imshow(I2,[]);
See Also
11-14
colfilt, nlfilter
www.MatlabSite.com
brighten
Purpose
11brighten
Brighten or darken a colormap
Synta x
brighten(beta)
newmap = brighten(beta)
newmap = brighten(map,beta)
brighten(fig,beta)
Description
brighten(beta) replaces the current colormap with a brighter or darker map
that has essentially the same colors. The map is brighter if 0 < beta ≤ 1 and
darker if –1 ≤ beta < 0.
brighten(beta) followed by brighten(–beta) restores the original map.
newmap = brighten(beta) returns a brighter or darker version of the current
colormap without changing the display.
newmap = brighten(map,beta) returns a brighter or darker version of the
specified colormap without changing the display.
brighten(fig,beta) brightens all of the objects in the figure fig.
Rema rk s
brighten is a function in MATLAB.
See Also
imadjust, rgbplot
colormap in the online MATLAB Function Reference
www.MatlabSite.com
11-15
bw a rea
Purpose
11bwarea
Compute the area of the objects in a binary image
Synta x
total = bwarea(BW)
Description
total = bwarea(BW) estimates the area of the objects in binary image BW.
total is a scalar whose value corresponds roughly to the total number of on
pixels in the image, but may not be exactly the same because different patterns
of pixels are weighted differently.
Cla ss Support
BW can be of class uint8 or double. total is of class double.
Algorithm
bwarea estimates the area of all of the on pixels in an image by summing the
areas of each pixel in the image. The area of an individual pixel is determined
by looking at its 2-by-2 neighborhood. There are six different patterns
distinguished, each representing a different area:
• Patterns with zero on pixels (area = 0)
• Patterns with one on pixel (area = 1/4)
• Patterns with two adjacent on pixels (area = 1/2)
• Patterns with two diagonal on pixels (area = 3/4)
• Patterns with three on pixels (area = 7/8)
• Patterns with all four on pixels (area = 1)
Keep in mind that each pixel is part of four different 2-by-2 neighborhoods.
This means, for example, that a single on pixel surrounded by off pixels has a
total area of 1.
11-16
www.MatlabSite.com
bw a rea
Ex a mple
This example computes the area in the objects of a 256-by-256 binary image.
BW = imread('circles.tif');
imshow(BW);
bwarea(BW)
ans =
15799
See Also
bweuler, bwperim
References
Pratt, William K. Digital Image Processing. New York: John Wiley & Sons,
Inc., 1991. p. 634.
www.MatlabSite.com
11-17
bw euler
Purpose
11bweuler
Compute the Euler number of a binary image
Synta x
eul = bweuler(BW,n)
Description
eul = bweuler(BW,n) returns the Euler number for the binary image BW. eul
is a scalar whose value is the total number of objects in the image minus the
total number of holes in those objects. n can have a value of either 4 or 8, where
4 specifies 4-connected objects and 8 specifies 8-connected objects; if the
argument is omitted, it defaults to 8.
Cla ss Support
Ex a mple
BW can be of class uint8 or double. eul is of class double.
BW = imread('circles.tif');
imshow(BW);
bweuler(BW)
ans =
–2
Algorithm
bweuler computes the Euler number by considering patterns of convexity and
concavity in local 2-by-2 neighborhoods. See Pratt, p. 633, for a discussion of
the algorithm used.
See Also
11-18
bwmorph, bwperim
www.MatlabSite.com
bw euler
References
Pratt, William K. Digital Image Processing. New York: John Wiley & Sons,
Inc., 1991. p. 633.
Horn, Berthold P. K., Robot Vision. New York: McGraw-Hill, 1986. pp. 73-77.
www.MatlabSite.com
11-19
bw fill
Purpose
Synta x
11bwfill
Fill background regions in a binary image
BW2 = bwfill(BW1,c,r,n)
BW2 = bwfill(BW1,n)
[BW2,idx] = bwfill(...)
BW2 = bwfill(x,y,BW1,xi,yi,n)
[x,y,BW2,idx,xi,yi] = bwfill(...)
BW2 = bwfill(BW1,'holes',n)
[BW2,idx] = bwfill(BW1,'holes',n)
Description
BW2 = bwfill(BW1,c,r,n) performs a flood-fill operation on the input binary
image BW1, starting from the pixel (r,c). If r and c are equal-length vectors, the
fill is performed in parallel from the starting pixels (r(k),c(k)). n can have a
value of either 4 or 8 (the default), where 4 specifies 4-connected foreground
and 8 specifies 8-connected foreground. The foreground of BW1 comprises the on
pixels (i.e., having value of 1).
BW2 = bwfill(BW1,n) displays the image BW1 on the screen and lets you select
the starting points using the mouse. If you omit BW1, bwfill operates on the
image in the current axes. Use normal button clicks to add points. Press
Backspace or Delete to remove the previously selected point. A shift-click,
right-click, or double-click selects a final point and then starts the fill; pressing
Return finishes the selection without adding a point.
[BW2,idx] = bwfill(...) returns the linear indices of all pixels filled by
bwfill.
BW2 = bwfill(x,y,BW1,xi,yi,n) uses the vectors x and y to establish a
nondefault spatial coordinate system for BW1. xi and yi are scalars or
equal-length vectors that specify locations in this coordinate system.
[x,y,BW2,idx,xi,yi] = bwfill(...) returns the XData and YData in x and y;
the output image in BW2; linear indices of all filled pixels in idx; and the fill
starting points in xi and yi.
BW2 = bwfill(BW1,'holes',n) fills the holes in the binary image BW1. bwfill
automatically determines which pixels are in object holes, and then changes
the value of those pixels from 0 to 1. n defaults to 8 if you omit the argument.
11-20
www.MatlabSite.com
bw fill
[BW2,idx] = bwfill(BW1,'holes',n) returns the linear indices of all pixels
filled in by bwfill.
If bwfill is used with no output arguments, the resulting image is displayed
in a new figure.
Rema rk s
bwfill differs from many other binary image operations in that it operates on
background pixels, rather than foreground pixels. If the foreground is
8-connected, the background is 4-connected, and vice versa. Note, however,
that you specify the connectedness of the foreground when you call bwfill.
Cla ss Support
The input image BW1 can be of class double or uint8. The output image BW2 is
of class uint8.
www.MatlabSite.com
11-21
bw fill
Ex a mples
BW1 = [1
1
1
1
1
1
1
1
0
1
0
0
1
0
0
0
0
1
0
0
1
0
0
0
0
1
0
0
1
1
0
0
0
1
1
1
0
1
1
1
0
0
0
1
1
0
0
1
0
0
1
1
1
1
1
1
0
0
0
0
1
0
0
0]
BW2 = bwfill(BW1,3,3,8)
BW2 =
1
1
1
1
1
1
1
1
0
1
1
1
1
0
0
0
0
1
1
1
1
0
0
0
0
1
1
1
1
1
0
0
0
1
1
1
0
1
1
1
I = imread('blood1.tif');
BW3 = ~im2bw(I);
BW4 = bwfill(BW3,'holes');
imshow(BW3)
figure, imshow(BW4)
See Also
11-22
bwselect, roifill
www.MatlabSite.com
0
0
0
1
1
0
0
1
0
0
1
1
1
1
1
1
0
0
0
0
1
0
0
0
bw la bel
Purpose
11bwlabel
Label connected components in a binary image
Synta x
L = bwlabel(BW,n)
[L,num] = bwlabel(BW,n)
Description
L = bwlabel(BW,n) returns a matrix L, of the same size as BW, containing labels
for the connected objects in BW. n can have a value of either 4 or 8, where 4
specifies 4-connected objects and 8 specifies 8-connected objects; if the
argument is omitted, it defaults to 8.
The elements of L are integer values greater than or equal to 0. The pixels
labeled 0 are the background. The pixels labeled 1 make up one object, the
pixels labeled 2 make up a second object, and so on.
[L,num] = bwlabel(BW,n) returns in num the number of connected objects
found in BW.
Cla ss Support
The input image BW can be of class double or uint8. The output matrix L is of
class double.
Rema rk s
You can use the MATLAB find function in conjunction with bwlabel to return
vectors of indices for the pixels that make up a specific object. For example, to
return the coordinates for the pixels in object 2:
[r,c] = find(bwlabel(BW)==2)
You can display the output matrix as a pseudocolor indexed image. Each object
appears in a different color, so the objects are easier to distinguish than in the
original image. To do this, you must first add 1 to each element in the output
matrix, so that the data is in the proper range. Also, it is good idea to use a
colormap in which the first few colors are very distinct.
www.MatlabSite.com
11-23
bw la bel
Ex a mple
This example illustrates using 4-connected objects. Notice objects 2 and 3; with
8-connected labeling, bwlabel would consider these a single object rather than
two separate objects.
BW = [1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
0
0
0
0
1
1
0
0
0
0
0
0
1
1
0
0
0
1
0
0
0
0
1
1
1
1
0
0
0
0
0
0
0
0
0]
L = bwlabel(BW,4)
L =
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
0
0
0
0
0
0
0
0
0
2
2
0
0
0
0
0
0
2
2
0
0
0
3
0
0
0
0
3
3
3
3
0
0
0
0
0
0
0
0
0
[r,c] = find(L==2);
rc = [r c]
rc =
2
3
2
3
5
5
6
6
See Also
bweuler, bwselect
Reference
Haralick, Robert M., and Linda G. Shapiro. Computer and Robot Vision,
Volume I. Addison-Wesley, 1992. pp. 28-48.
11-24
www.MatlabSite.com
bw m orph
Purpose
11bwmorph
Perform morphological operations on binary images
Synta x
BW2 = bwmorph(BW1,operation)
BW2 = bwmorph(BW1,operation,n)
Description
BW2 = bwmorph(BW1,operation) applies a specific morphological operation to
the binary image BW1.
BW2 = bwmorph(BW1,operation,n) applies the operation n times. n can be Inf,
in which case the operation is repeated until the image no longer changes.
operation is a string that can have one of these values:
'bothat'
'erode'
'shrink'
'bridge'
'fill'
'skel'
'clean'
'hbreak'
'spur'
'close'
'majority'
'thicken'
'diag'
'open'
'thin'
'dilate'
'remove'
'tophat'
'bothat' (“bottom hat”) performs binary closure (dilation followed by erosion)
and subtracts the original image.
'bridge' bridges previously unconnected pixels. For example:
1
1
0
0
0
0
0
1
1
becomes
1
1
0
0
1
0
0
1
1
'clean' removes isolated pixels (individual 1’s that are surrounded by 0’s),
such as the center pixel in this pattern:
0
0
0
0
1
0
0
0
0
'close' performs binary closure (dilation followed by erosion).
www.MatlabSite.com
11-25
bw morph
'diag' uses diagonal fill to eliminate 8-connectivity of the background. For
example:
0
1
0
1
0
0
0
0
0
becomes
0
1
0
1
1
0
0
0
0
'dilate' performs dilation using the structuring element ones(3).
'erode' performs dilation using the structuring element ones(3).
'fill' fills isolated interior pixels (individual 0’s that are surrounded by 1’s),
such as the center pixel in this pattern:
1
1
1
1
0
1
1
1
1
'hbreak' removes H-connected pixels. For example:
1
0
1
1
1
1
1
0
1
becomes
1
0
1
1
0
1
1
0
1
'majority' sets a pixel to 1 if five or more pixels in its 3-by-3 neighborhood are
1’s; otherwise, it sets the pixel to 0.
'open' implements binary opening (erosion followed by dilation).
'remove' removes interior pixels. This option sets a pixel to 0 if all of its
4-connected neighbors are 1, thus leaving only the boundary pixels on.
'shrink', with n = Inf, shrinks objects to points. It removes pixels so that
objects without holes shrink to a point, and objects with holes shrink to a
connected ring halfway between each hole and the outer boundary. This option
preserves the Euler number.
'skel', with n = Inf, removes pixels on the boundaries of objects but does not
allow objects to break apart. The pixels remaining make up the image skeleton.
This option preserves the Euler number.
11-26
www.MatlabSite.com
bw m orph
'spur' removes spur pixels. For example:
0
0
0
0
1
0
0
0
1
1
0
0
1
0
0
0
0
0
0
0
becomes
0
0
0
0
1
0
0
0
1
1
0
0
0
0
0
0
0
0
0
0
'thicken', with n = Inf, thickens objects by adding pixels to the exterior of
objects until doing so would result in previously unconnected objects being
8-connected. This option preserves the Euler number.
'thin', with n = Inf, thins objects to lines. It removes pixels so that an object
without holes shrinks to a minimally connected stroke, and an object with holes
shrinks to a connected ring halfway between each hole and the outer boundary.
This option preserves the Euler number.
'tophat' (“top hat”) returns the image minus the binary opening of the image.
Cla ss Support
The input image BW1 can be of class double or uint8. The output image BW2 is
of class uint8.
www.MatlabSite.com
11-27
bw morph
Ex a mples
BW1 = imread('circles.tif');
imshow(BW1);
BW2 = bwmorph(BW1,'remove');
BW3 = bwmorph(BW1,'skel',Inf);
imshow(BW2)
figure, imshow(BW3)
See Also
bweuler, bwperim, dilate, erode
References
Haralick, Robert M., and Linda G. Shapiro. Computer and Robot Vision,
Volume I. Addison-Wesley, 1992.
Pratt, William K. Digital Image Processing. John Wiley & Sons, Inc., 1991.
11-28
www.MatlabSite.com
bw perim
Purpose
11bwperim
Determine the perimeter of the objects in a binary image
Synta x
BW2 = bwperim(BW1,n)
Description
BW2 = bwperim(BW1,n) returns a binary image containing only the perimeter
pixels of objects in the input image BW1. A pixel is part of the perimeter if its
value is 1 and there is at least one zero-valued pixel in its neighborhood. n can
have a value of either 4 or 8, where 4 specifies 4-connected neighborhoods and
8 specifies 8-connected neighborhoods; if the argument is omitted, it defaults
to 8.
Cla ss Support
The input image BW1 can be of class double or uint8. The output image BW2 is
of class uint8.
Ex a mple
See Also
BW1 = imread('circbw.tif');
BW2 = bwperim(BW1,8);
imshow(BW1)
figure, imshow(BW2)
bwarea, bweuler, bwfill
www.MatlabSite.com
11-29
bw select
Purpose
Synta x
11bwselect
Select objects in a binary image
BW2 = bwselect(BW1,c,r,n)
BW2 = bwselect(BW1,n)
[BW2,idx] = bwselect(...)
BW2 = bwselect(x,y,BW1,xi,yi,n)
[x,y,BW2,idx,xi,yi] = bwselect(...)
Description
BW2 = bwselect(BW1,c,r,n) returns a binary image containing the objects
that overlap the pixel (r,c). r and c can be scalars or equal-length vectors. If r
and c are vectors, BW2 contains the sets of objects overlapping with any of the
pixels (r(k),c(k)). n can have a value of either 4 or 8 (the default), where 4
specifies 4-connected objects and 8 specifies 8-connected objects. Objects are
connected sets of on pixels (i.e., pixels having a value of 1).
BW2 = bwselect(BW1,n) displays the image BW1 on the screen and lets you
select the (r,c) coordinates using the mouse. If you omit BW1, bwselect
operates on the image in the current axes. Use normal button clicks to add
points. Pressing Backspace or Delete removes the previously selected point.
A shift-click, right-click, or double-click selects the final point; pressing
Return finishes the selection without adding a point.
[BW2,idx] = bwselect(...) returns the linear indices of the pixels belonging
to the selected objects.
BW2 = bwselect(x,y,BW1,xi,yi,n) uses the vectors x and y to establish a
nondefault spatial coordinate system for BW1. xi and yi are scalars or
equal-length vectors that specify locations in this coordinate system.
[x,y,BW2,idx,xi,yi] = bwselect(...) returns the XData and YData in x and
y; the output image in BW2; linear indices of all the pixels belonging to the
selected objects in idx; and the specified spatial coordinates in xi and yi.
If bwselect is called with no output arguments, the resulting image is
displayed in a new figure.
11-30
www.MatlabSite.com
bw select
Ex a mple
BW1 = imread('text.tif');
c = [16 90 144];
r = [85 197 247];
BW2 = bwselect(BW1,c,r,4);
imshow(BW1)
figure, imshow(BW2)
Cla ss Support
The input image BW1 can be of class double or uint8. The output image BW2 is
of class uint8.
See Also
bwfill, bwlabel, impixel, roipoly, roifill
www.MatlabSite.com
11-31
cmpermute
Purpose
11cmpermute
Rearrange the colors in a colormap
Synta x
[Y,newmap] = cmpermute(X,map)
[Y,newmap] = cmpermute(X,map,index)
Description
[Y,newmap] = cmpermute(X,map) randomly reorders the colors in map to
produce a new colormap newmap. cmpermute also modifies the values in X to
maintain correspondence between the indices and the colormap, and returns
the result in Y. The image Y and associated colormap newmap produce the same
image as X and map.
[Y,newmap] = cmpermute(X,map,index) uses an ordering matrix (such as the
second output of sort) to define the order of colors in the new colormap.
Cla ss Support
The input image X can be of class uint8 or double. Y is returned as an array of
the same class as X.
Ex a mple
To order a colormap by luminance, use:
ntsc = rgb2ntsc(map);
[dum,index] = sort(ntsc(:,1));
[Y,newmap] = cmpermute(X,map,index);
See Also
11-32
randperm, sort in the online MATLAB Function Reference
www.MatlabSite.com
cm unique
Purpose
11cmunique
Find unique colormap colors and the corresponding image
Synta x
[Y,newmap] = cmunique(X,map)
[Y,newmap] = cmunique(RGB)
[Y,newmap] = cmunique(I)
Description
[Y,newmap] = cmunique(X,map) returns the indexed image Y and associated
colormap newmap that produce the same image as (X,map) but with the
smallest possible colormap. cmunique removes duplicate rows from the
colormap and adjusts the indices in the image matrix accordingly.
[Y,newmap] = cmunique(RGB) converts the truecolor image RGB to the indexed
image Y and its associated colormap newmap. newmap is the smallest possible
colormap for the image, containing one entry for each unique color in RGB. (Note
that newmap may be very large, because the number of entries can be as many
as the number of pixels in RGB.)
[Y,newmap] = cmunique(I) converts the intensity image I to an indexed image
Y and its associated colormap newmap. newmap is the smallest possible colormap
for the image, containing one entry for each unique intensity level in I.
Cla ss Support
The input image can be of class uint8 or double. The class of the output image
Y is uint8 if the length of newmap is less than or equal to 256. If the length of
newmap is greater than 256, Y is of class double.
See Also
gray2ind, rgb2ind
www.MatlabSite.com
11-33
col2 im
Purpose
11col2im
Rearrange matrix columns into blocks
Synta x
A = col2im(B,[m n],[mm nn],block_type)
A = col2im(B,[m n],[mm nn])
Description
col2im rearranges matrix columns into blocks. block_type is a string with one
of these values:
• 'distinct' for m-by-n distinct blocks
• 'sliding' for m-by-n sliding blocks (default)
A = col2im(B,[m n],[mm nn],'distinct') rearranges each column of B
into a distinct m-by-n block to create the matrix A of size mm-by-nn. If
B = [A11(:) A12(:) A21(:) A22(:)], where each column has length m*n,
then A = [A11 A12;A21 A22] where each Aij is m-by-n.
A = col2im(B,[m n],[mm nn],'sliding') rearranges the row vector B
into a matrix of size (mm–m+1)-by-(nn–n+1). B must be a vector of size
1-by-(mm–m+1)*(nn–n+1). B is usually the result of processing the output of
im2col(...,'sliding') using a column compression function (such as sum).
A = col2im(B,[m n],[mm nn]) uses the default block_type of 'sliding'.
Cla ss Support
B can be of class uint8 or double. A is of the same class as B.
See Also
blkproc, colfilt, im2col, nlfilter
11-34
www.MatlabSite.com
colfilt
Purpose
11colfilt
Perform neighborhood operations using columnwise functions
Synta x
B
B
B
B
Description
colfilt processes distinct or sliding blocks as columns. colfilt can perform
similar operations to blkproc and nlfilter, but often executes much faster.
=
=
=
=
colfilt(A,[m n],block_type,fun)
colfilt(A,[m n],block_type,fun,P1,P2,...)
colfilt(A,[m n],[mblock nblock],block_type,fun,...)
colfilt(A,'indexed',...)
B = colfilt(A,[m n],block_type,fun) processes the image A by rearranging
each m-by-n block of A into a column of a temporary matrix, and then applying
the function fun to this matrix. fun can be an inline function, a text string
containing the name of a function, or a string containing an expression.
colfilt zero pads A, if necessary.
Before calling fun, colfilt calls im2col to create the temporary matrix. After
calling fun, colfilt rearranges the columns of the matrix back into m-by-n
blocks using col2im.
block_type is a string with one of these values:
• 'distinct' for m-by-n distinct blocks
• 'sliding' for m-by-n sliding neighborhoods
B = colfilt(A,[m n],'distinct',fun) rearranges each m-by-n distinct block
of A into a column in a temporary matrix, and then applies the function fun to
this matrix. fun must return a matrix of the same size as the temporary
matrix. colfilt then rearranges the columns of the matrix returned by fun
into m-by-n distinct blocks.
B = colfilt(A,[m n],'sliding',fun) rearranges each m-by-n sliding
neighborhood of A into a column in a temporary matrix, and then applies the
function fun to this matrix. fun must return a row vector containing a single
value for each column in the temporary matrix. (Column compression functions
such as sum return the appropriate type of output.) colfilt then rearranges
the vector returned by fun into a matrix of the same size as A.
www.MatlabSite.com
11-35
colfilt
B = colfilt(A,[m n],block_type,fun,P1,P2,...) passes the additional
parameters P1,P2,..., to fun. colfilt calls fun using:
y = fun(x,P1,P2,...)
where x is the temporary matrix before processing, and y is the temporary
matrix after processing.
B = colfilt(A,[m n],[mblock nblock],block_type,fun,...) processes the
matrix A as above, but in blocks of size mblock-by-nblock to save memory. Note
that using the [mblock nblock] argument does not change the result of the
operation.
B = colfilt(A,'indexed',...) processes A as an indexed image, padding
with zeros if the class of A is uint8, or ones if the class of A is double.
Cla ss Support
The input image A can be of any class supported by fun. The class of B depends
on the class of the output from fun.
Ex a mple
This example sets each output pixel to the mean value of the input pixel’s
5-by-5 neighborhood:
I2 = colfilt(I,[5 5],'sliding','mean');
See Also
11-36
blkproc, col2im, im2col, nlfilter
www.MatlabSite.com
colorba r
Purpose
11colorbar
Display a colorbar
Synta x
colorbar('vert')
colorbar('horiz')
colorbar(h)
colorbar
h = colorbar(...)
Description
colorbar('vert') appends a vertical colorbar to the current axes, resizing the
axes to make room for the colorbar. colorbar works with both two-dimensional
and three-dimensional plots.
colorbar('horiz') appends a horizontal colorbar to the current axes.
colorbar(h) places the colorbar in the axes h. The colorbar is horizontal if the
width of the axes is greater than its height.
colorbar with no arguments adds a new vertical colorbar or updates an
existing one.
h = colorbar(...) returns a handle to the colorbar axes.
Rema rk s
colorbar is a function in MATLAB.
www.MatlabSite.com
11-37
colorba r
Ex a mples
Display a colorbar to view values for a filtered image.
I = imread('blood1.tif');
h = fspecial('log');
I2 = filter2(h,I);
imshow(I2,[]), colormap(jet(64)), colorbar
11-38
www.MatlabSite.com
conv2
Purpose
11conv2
Perform two-dimensional convolution
Synta x
C = conv2(A,B)
C = conv2(hcol,hrow,A)
C = conv2(...,shape)
Description
C = conv2(A,B) performs the two-dimensional convolution of matrices A and
B, returning the result in the output matrix C. The size in each dimension of C
is equal to the sum of the corresponding dimensions of the input matrices
minus one. That is, if the size of A is [ma,mb] and the size of B is [mb,nb], then
the size of C is [ma+mb–1,na+nb–1].
C = conv2(hcol,hrow,A) convolves A separably with hcol in the column
direction and hrow in the row direction. hcol and hrow are both vectors.
C = conv2(...,shape) returns a subsection of the two-dimensional
convolution, as specified by the shape parameter. shape is a string with one of
these values:
• 'full' (the default) returns the full two-dimensional convolution.
• 'same' returns the central part of the convolution of the same size as A.
• 'valid' returns only those parts of the convolution that are computed
without the zero-padded edges. Using this option, size(C) = [ma–mb+1,
na–nb+1] when size(A) > size(B).
For image filtering, A should be the image matrix and B should be the filter
(convolution kernel) if the shape parameter is 'same' or 'valid'. If the shape
parameter is 'full', the order does not matter, because full convolution is
commutative.
Cla ss Support
All vector and matrix inputs to conv2 can be of class uint8 or double. The
output matrix C is of class double.
Rema rk s
conv2 is a function in MATLAB.
www.MatlabSite.com
11-39
conv2
Ex a mple
A = magic(5)
A =
17
23
4
10
11
24
5
6
12
18
1
7
13
19
25
8
14
20
21
2
15
16
22
3
9
B = [1 2 1;0 2 0;3 1 3]
B =
1
0
3
2
2
1
1
0
3
C = conv2(A,B)
C =
17
23
55
79
23
30
33
See Also
58
85
149
78
82
68
65
66
88
117
160
153
135
126
34
35
163
161
199
168
85
32
67
159
187
205
91
104
38
76
135
129
108
84
15
15
16
67
51
75
9
27
filter2
xcorr, xcorr2 in the Signal Processing Toolbox User’s Guide
conv, deconv in the online MATLAB Function Reference
11-40
www.MatlabSite.com
convmtx 2
Purpose
11convmtx2
Compute two-dimensional convolution matrix
Synta x
T = convmtx2(H,m,n)
T = convmtx2(H,[m n])
Description
T = convmtx2(H,m,n) or T = convmtx2(H,[m n]) returns the
convolution matrix T for the matrix H. If X is an m-by-n matrix, then
reshape(T*X(:),size(H)+[m n]–1) is the same as conv2(X,H).
T is returned as a sparse matrix. The number of nonzero elements in T
is no larger than prod(size(H))*m*n.
See Also
conv2
convmtx in the Signal Processing Toolbox User’s Guide
www.MatlabSite.com
11-41
convn
Purpose
11convn
Perform N-dimensional convolution
Synta x
C = convn(A,B)
C = convn(A,B,shape)
Description
C = convn(A,B) computes the N-dimensional convolution of matrices A and B.
C = convn(A,B,shape) returns a subsection of the N-dimensional convolution,
as specified by the shape parameter. shape is a string with one of these values:
• 'full' (the default) returns the full convolution.
• 'same' returns the central part of the convolution of the same size as A.
• 'valid' returns only those parts of the convolution that are computed
without zero-padded edges.
Cla ss Support
The input matrices A and B can be of class uint8 or double. The output matrix
C is of class double.
Rema rk s
convn is a function in MATLAB.
See Also
conv2
11-42
www.MatlabSite.com
corr2
Purpose
11corr2
Compute the two-dimensional correlation coefficient between two matrices
Synta x
r = corr2(A,B)
Description
r = corr2(A,B) computes the correlation coefficient between A and B, where A
and B are matrices or vectors of the same size.
Cla ss Support
A and B can be of class uint8 or double. r is a scalar of class double.
Algorithm
corr2 computes the correlation coefficient using
∑ ∑ ( Amn – A ) ( Bmn – B )
m n
r = -----------------------------------------------------------------------------------------------------2
2
( B mn – B )
( A mn – A )
∑∑
m n
∑∑
m n
where A = mean2(A), and B = mean2(B).
See Also
std2
corrcoef in the online MATLAB Function Reference
www.MatlabSite.com
11-43
dct2
Purpose
11dct2
Compute two-dimensional discrete cosine transform
Synta x
B = dct2(A)
B = dct2(A,m,n)
B = dct2(A,[m n])
Description
B = dct2(A) returns the two-dimensional discrete cosine transform of A. The
matrix B is the same size as A and contains the discrete cosine transform
coefficients B(k1,k2).
B = dct2(A,m,n) or B = dct2(A,[m n]) pads the matrix A with zeros to size
m-by-n before transforming. If m or n is smaller than the corresponding
dimension of A, dct2 truncates A.
Cla ss Support
A can be of class uint8 or double. The returned matrix B is of class double.
Algorithm
The discrete cosine transform (DCT) is closely related to the discrete Fourier
transform. It is a separable, linear transformation; that is, the
two-dimensional transform is equivalent to a one-dimensional DCT performed
along a single dimension followed by a one-dimensional DCT in the other
dimension. The definition of the two-dimensional DCT for an input image A and
output image B is
M–1 N–1
B pq = α p α q
∑ ∑
m=0 n=0
π ( 2m + 1 ) p
π ( 2n + 1 )q
A mn cos ------------------------------- cos ----------------------------- ,
2M
2N
1 ⁄ M, p = 0
αp =
2 ⁄ M, 1 ≤ p ≤ M – 1
0≤ p≤M–1
0≤q≤N–1
1 ⁄ N , q = 0
αq =
2 ⁄ N, 1 ≤ q ≤ N – 1
where M and N are the row and column size of A, respectively. If you apply the
DCT to real data, the result is also real. The DCT tends to concentrate
information, making it useful for image compression applications.
This transform can be inverted using idct2.
11-44
www.MatlabSite.com
dct2
Ex a mple
The commands below compute the discrete cosine transform for the autumn
image. Notice that most of the energy is in the upper-left corner.
RGB = imread('autumn.tif');
I = rgb2gray(RGB);
J = dct2(I);
imshow(log(abs(J)),[]), colormap(jet(64)), colorbar
Now set values less than magnitude 10 in the DCT matrix to zero, and then
reconstruct the image using the inverse DCT function idct2.
J(abs(J) < 10) = 0;
K = idct2(J)/255;
imshow(K)
See Also
fft2, idct2, ifft2
References
Jain, Anil K. Fundamentals of Digital Image Processing. Englewood Cliffs, NJ:
Prentice Hall, 1989. pp. 150-153.
Pennebaker, William B., and Joan L. Mitchell. JPEG: Still Image Data
Compression Standard. Van Nostrand Reinhold, 1993.
www.MatlabSite.com
11-45
dctmtx
Purpose
11dctmtx
Compute discrete cosine transform matrix
Synta x
D = dctmtx(n)
Description
D = dctmtx(n) returns the n-by-n DCT transform matrix. D*A is the DCT of the
columns of A and D'*A is the inverse DCT of the columns of A (when A is n-by-n).
Cla ss Support
n is a scalar of class double. D is returned as a matrix of class double.
Rema rk s
If A is square, the two-dimensional DCT of A can be computed as D*A*D'. This
computation is sometimes faster than using dct2, especially if you are
computing a large number of small DCTs, because D needs to be determined
only once.
For example, in JPEG compression, the DCT of each 8-by-8 block is computed.
To perform this computation, use dctmtx to determine D, and then calculate
each DCT using D*A*D' (where A is each 8-by-8 block). This is faster than
calling dct2 for each individual block.
See Also
11-46
dct2
www.MatlabSite.com
dila te
Purpose
11dilate
Perform dilation on a binary image
Synta x
BW2 = dilate(BW1,SE)
BW2 = dilate(BW1,SE,alg)
BW2 = dilate(BW1,SE,...,n)
Description
BW2 = dilate(BW1,SE) performs dilation on the binary image BW1, using the
binary structuring element SE. SE is a matrix containing only 1’s and 0’s.
BW2 = dilate(BW1,SE,alg) performs dilation using the specified algorithm.
alg is a string that can have one of these values:
• 'spatial' (default) – processes the image in the spatial domain.
• 'frequency' – processes the image in the frequency domain.
Both algorithms produce the same result, but they make different tradeoffs
between speed and memory use. The frequency algorithm is faster for large
images and structuring elements than the spatial algorithm, but uses much
more memory.
BW2 = dilate(BW1,SE,...,n) performs the dilation operation n times.
Cla ss Support
The input image BW1 can be of class double or uint8. The output image BW2 is
of class uint8.
Rema rk s
You should use the frequency algorithm only if you have a large amount of
memory on your system. If you use this algorithm with insufficient memory, it
may actually be slower than the spatial algorithm, due to virtual memory
paging. If the frequency algorithm slows down your system excessively, or if
you receive “out of memory” messages, use the spatial algorithm instead.
www.MatlabSite.com
11-47
dila te
Ex a mple
BW1 = imread('text.tif');
SE = ones(6,2);
BW2 = dilate(BW1,SE);
imshow(BW1)
figure, imshow(BW2)
See Also
bwmorph, erode
References
Haralick, Robert M., and Linda G. Shapiro. Computer and Robot Vision,
Volume I. Addison-Wesley, 1992. p. 158.
Gonzalez, Rafael C., and Richard E. Woods. Digital Image Processing.
Addison-Wesley, 1992. p. 518.
11-48
www.MatlabSite.com
dither
Purpose
11dither
Convert an image, increasing apparent color resolution by dithering
Synta x
X = dither(RGB,map)
BW = dither(I)
Description
X = dither(RGB,map) creates an indexed image approximation of the RGB
image in the array RGB by dithering the colors in colormap map.
X = dither(RGB,map,Qm,Qe) creates an indexed image from RGB, specifying
the parameters Qm and Qe. Qm specifies the number of quantization bits to use
along each color axis for the inverse color map, and Qe specifies the number of
quantization bits to use for the color space error calculations. If Qe < Qm,
dithering cannot be performed and an undithered indexed image is returned in
X. If you omit these parameters, dither uses the default values Qm = 5, Qe = 8.
BW = dither(I) converts the intensity image in the matrix I to the binary
(black and white) image BW by dithering.
Cla ss Support
The input image (RGB or I) can be of class double or uint8. All other input
arguments must be of class double. The output image (X or BW) is of class uint8
if it is a binary image or if it is an indexed image with 256 or fewer colors;
otherwise its class is double.
Algorithm
dither increases the apparent color resolution of an image by applying
Floyd-Steinberg’s error diffusion dither algorithm.
Reference
Floyd, R. W. and L. Steinberg. “An Adaptive Algorithm for Spatial Gray Scale.”
International Symposium Digest of Technical Papers. Society for Information
Displays, 1975. p. 36.
Lim, Jae S. Two-Dimensional Signal and Image Processing. Englewood Cliffs,
NJ: Prentice Hall, 1990. pp. 469-476.
See Also
rgb2ind
www.MatlabSite.com
11-49
double
Purpose
11double
Convert data to double precision
Synta x
B = double(A)
Description
B = double(A) creates a double-precision array B from the array A. If A is a
double array, B is identical to A.
double is useful if you have a uint8 image array that you want to perform
arithmetic operations on, because MATLAB does not support these operations
on uint8 data.
Rema rk s
Ex a mple
See Also
11-50
double is a MATLAB built-in function.
A = imread('saturn.tif');
B = sqrt(double(A));
im2double, im2uint, uint8
www.MatlabSite.com
edge
Purpose
Synta x
11edge
Find edges in an intensity image
BW = edge(I,'sobel')
BW = edge(I,'sobel',thresh)
BW = edge(I,'sobel',thresh,direction)
[BW,thresh] = edge(I,'sobel',...)
BW = edge(I,'prewitt')
BW = edge(I,'prewitt',thresh)
BW = edge(I,'prewitt',thresh,direction)
[BW,thresh] = edge(I,'prewitt',...)
BW = edge(I,'roberts')
BW = edge(I,'roberts',thresh)
[BW,thresh] = edge(I,'roberts',...)
BW = edge(I,'log')
BW = edge(I,'log',thresh)
BW = edge(I,'log',thresh,sigma)
[BW,threshold] = edge(I,'log',...)
BW = edge(I,'zerocross',thresh,h)
[BW,thresh] = edge(I,'zerocross',...)
BW = edge(I,'canny')
BW = edge(I,'canny',thresh)
BW = edge(I,'canny',thresh,sigma)
[BW,threshold] = edge(I,'canny',...)
Description
edge takes an intensity image I as its input, and returns a binary image BW of
the same size as I, with 1’s where the function finds edges in I and 0’s
elsewhere.
11
www.MatlabSite.com
11-51
edge
edge supports six different edge-finding methods:
• The Sobel method finds edges using the Sobel approximation to the
derivative. It returns edges at those points where the gradient of I is
maximum.
• The Prewitt method finds edges using the Prewitt approximation to the
derivative. It returns edges at those points where the gradient of I is
maximum.
• The Roberts method finds edges using the Roberts approximation to the
derivative. It returns edges at those points where the gradient of I is
maximum.
• The Laplacian of Gaussian method finds edges by looking for zero crossings
after filtering I with a Laplacian of Gaussian filter.
• The zero-cross method finds edges by looking for zero crossings after filtering
I with a filter you specify.
• The Canny method finds edges by looking for local maxima of the gradient of
I. The gradient is calculated using the derivative of a Gaussian filter. The
method uses two thresholds, to detect strong and weak edges, and includes
the weak edges in the output only if they are connected to strong edges. This
method is therefore less likely than the others to be “fooled” by noise, and
more likely to detect true weak edges.
The parameters you can supply differ depending on the method you specify. If
you do not specify a method, edge uses the Sobel method.
Sobel Method
BW = edge(I,'sobel') specifies the Sobel method.
BW = edge(I,'sobel',thresh) specifies the sensitivity threshold for the Sobel
method. edge ignores all edges that are not stronger than thresh. If you do not
specify thresh, or if thresh is empty ([]), edge chooses the value
automatically.
BW = edge(I,'sobel',thresh,direction) specifies directionality for the
Sobel method. direction is a string specifying whether to look for
'horizontal' or 'vertical' edges, or 'both' (the default).
[BW,thresh] = edge(I,'sobel',...) returns the threshold value.
11-52
www.MatlabSite.com
edge
Prewitt Method
BW = edge(I,'prewitt') specifies the Prewitt method.
BW = edge(I,'prewitt',thresh) specifies the sensitivity threshold for the
Prewitt method. edge ignores all edges that are not stronger than thresh. If
you do not specify thresh, or if thresh is empty ([]), edge chooses the value
automatically.
BW = edge(I,'prewitt',thresh,direction) specifies directionality for the
Prewitt method. direction is a string specifying whether to look for
'horizontal' or 'vertical' edges, or 'both' (the default).
[BW,thresh] = edge(I,'prewitt',...) returns the threshold value.
Roberts Method
BW = edge(I,method) specifies the Roberts method.
BW = edge(I,method,thresh) specifies the sensitivity threshold for the
Roberts method. edge ignores all edges that are not stronger than thresh. If
you do not specify thresh, or if thresh is empty ([]), edge chooses the value
automatically.
[BW,thresh] = edge(I,method,...) returns the threshold value.
Laplacian of Gaussian Method
BW = edge(I,'log') specifies the Laplacian of Gaussian method.
BW = edge(I,'log',thresh) specifies the sensitivity threshold for the
Laplacian of Gaussian method. edge ignores all edges that are not stronger
than thresh. If you do not specify thresh, or if thresh is empty ([]), edge
chooses the value automatically.
BW = edge(I,'log',thresh,sigma) specifies the Laplacian of Gaussian
method, using sigma as the standard deviation of the LoG filter. The default
sigma is 2; the size of the filter is n-by-n, where n = ceil(sigma*3)*2+1.
[BW,thresh] = edge(I,'log',...) returns the threshold value.
www.MatlabSite.com
11-53
edge
Zero-cross Method
BW = edge(I,'zerocross',thresh,h) specifies the zero-cross method, using
the filter h. thresh is the sensitivity threshold; if the argument is empty ([]),
edge chooses the sensitivity threshold automatically.
[BW,thresh] = edge(I,'zerocross',...) returns the threshold value.
Canny Method
BW = edge(I,'canny') specifies the Canny method.
BW = edge(I,'canny',thresh) specifies sensitivity thresholds for the Canny
method. thresh is a two-element vector in which the first element is the low
threshold, and the second element is the high threshold. If you specify a scalar
for thresh, this value is used for the high threshold and 0.4*thresh is used for
the low threshold. If you do not specify thresh, or if thresh is empty ([]), edge
chooses low and high values automatically.
BW = edge(I,'canny',thresh,sigma) specifies the Canny method, using
sigma as the standard deviation of the Gaussian filter. The default sigma is 1;
the size of the filter is chosen automatically, based on sigma.
[BW,thresh] = edge(I,'canny',...) returns the threshold values as a
two-element vector.
Cla ss Support
I can be of class uint8 or double. BW is of class uint8.
Rema rk s
For the 'log' and 'zerocross' methods, if you specify a threshold of 0, the
output image has closed contours, because it includes all of the zero crossings
in the input image.
11-54
www.MatlabSite.com
edge
Ex a mple
Find the edges of the rice.tif image using the Prewitt and Canny methods:
I = imread('rice.tif');
BW1 = edge(I,'prewitt');
BW2 = edge(I,'canny');
imshow(BW1)
figure, imshow(BW2)
References
Lim, Jae S. Two-Dimensional Signal and Image Processing. Englewood Cliffs,
NJ: Prentice Hall, 1990. pp. 478-488.
Parker, James R. Algorithms for Image Processing and Computer Vision. New
York: John Wiley & Sons, Inc., 1997. pp. 23-29.
Canny, John. “A Computational Approach to Edge Detection,” IEEE
Transactions on Pattern Analysis and Machine Intelligence, 1986. Vol. PAMI-8,
No. 6, pp. 679-698.
www.MatlabSite.com
11-55
erode
Purpose
11erode
Perform erosion on a binary image
Synta x
BW2 = erode(BW1,SE)
BW2 = erode(BW1,SE,alg)
BW2 = erode(BW1,SE,...,n)
Description
BW2 = erode(BW1,SE) performs erosion on the binary image BW1, using the
binary structuring element SE. SE is a matrix containing only 1’s and 0’s.
BW2 = erode(BW1,SE,alg) performs erosion using the specified algorithm. alg
is a string that can have one of these values:
• 'spatial' (default) – processes the image in the spatial domain.
• 'frequency' – processes the image in the frequency domain.
Both algorithms produce the same result, but they make different tradeoffs
between speed and memory use. The frequency algorithm is faster for large
images and structuring elements than the spatial algorithm, but uses much
more memory.
BW2 = erode(BW1,SE,...,n) performs the erosion operation n times.
Cla ss Support
The input image BW1 can be of class double or uint8. The output image BW2 is
of class uint8.
Rema rk s
You should use the frequency algorithm only if you have a large amount of
memory on your system. If you use this algorithm with insufficient memory, it
may actually be slower than the spatial algorithm, due to virtual memory
paging. If the frequency algorithm slows down your system excessively, or if
you receive “out of memory” messages, use the spatial algorithm instead.
11-56
www.MatlabSite.com
erode
Ex a mple
BW1 = imread('text.tif')
SE = ones(3,1)
SE =
1
1
1
BW2 = erode(BW1,SE);
imshow(BW1)
figure, imshow(BW2)
See Also
bwmorph, dilate
References
Haralick, Robert M., and Linda G. Shapiro. Computer and Robot Vision,
Volume I. Addison-Wesley, 1992. p. 158.
Gonzalez, Rafael C., and Richard E. Woods. Digital Image Processing.
Addison-Wesley, 1992. p. 518.
www.MatlabSite.com
11-57
fft2
Purpose
11fft2
Compute two-dimensional fast Fourier transform (FFT)
Synta x
B = fft2(A)
B = fft2(A,m,n)
Description
B = fft2(A) performs a two-dimensional fast Fourier transform, returning the
result in B. B is the same size as A; if A is a vector, B has the same orientation
as A.
B = fft2(A,m,n) truncates or zero pads A, if necessary, to create an m-by-n
matrix before performing the FFT. The result B is also m-by-n.
Cla ss Support
The input matrix A can be of class uint8 or double. The output matrix B is of
class double.
Rema rk s
fft2 is a function in MATLAB.
11-58
www.MatlabSite.com
fft2
Ex a mple
load imdemos saturn2
imshow(saturn2)
B = fftshift(fft2(saturn2));
imshow(log(abs(B)),[]), colormap(jet(64)), colorbar
Algorithm
fft2(A) is simply
fft(fft(A).').'
This computes the one-dimensional fft of each column A, then of each row of
the result. The time required to compute fft2(A) depends on the number of
prime factors of m and n. fft2 is fastest when m and n are powers of 2.
See Also
dct2, fftshift, idct2, ifft2
fft, ifft in the online MATLAB Function Reference
www.MatlabSite.com
11-59
fftn
Purpose
11fftn
Compute N-dimensional fast Fourier transform
Synta x
B = fftn(A)
B = fftn(A,siz)
Description
B = fftn(A) performs the N-dimensional fast Fourier transform. The result B
is the same size as A.
B = fftn(A,siz) pads A with zeros (or truncates A) to create an N-dimensional
array of size siz before doing the transform. The size of the result is siz.
Cla ss Support
The input matrix A can be of class uint8 or double. The output matrix B is of
class double.
Rema rk s
fftn is a function in MATLAB.
Algorithm
fftn(A) is equivalent to:
B = A;
for p = 1:length(size(A))
B = fft(B,[],p);
end
This code computes the one-dimensional fast Fourier transform along each
dimension of A. The time required to compute fftn(A) depends strongly on the
number of prime factors of the dimensions of A. It is fastest when all of the
dimensions are powers of 2.
See Also
fft2, ifftn
fft in the online MATLAB Function Reference
11-60
www.MatlabSite.com
fftshift
Purpose
11fftshift
Shift DC component of fast Fourier transform to center of spectrum
Synta x
B = fftshift(A)
Description
B = fftshift(A) rearranges the outputs of fft, fft2, and fftn by moving the
zero frequency component to the center of the array.
For vectors, fftshift(A) swaps the left and right halves of A. For matrices,
fftshift(A) swaps quadrants one and three of A with quadrants two and four.
For higher-dimensional arrays, fftshift(A) swaps “half-spaces” of A along
each dimension.
Rema rk s
Ex a mple
See Also
fftshift is a function in MATLAB.
B = fftn(A);
C = fftshift(B);
fft2, fftn
fft in the online MATLAB Function Reference
www.MatlabSite.com
11-61
filter2
Purpose
11filter2
Perform two-dimensional linear filtering
Synta x
B = filter2(h,A)
B = filter2(h,A,shape)
Description
B = filter2(h,A) filters the data in A with the two-dimensional FIR filter in
the matrix h. It computes the result, B, using two-dimensional correlation, and
returns the central part of the correlation that is the same size as A.
B = filter2(h,A,shape) returns the part of B specified by the shape
parameter. shape is a string with one of these values:
• 'full' returns the full two-dimensional correlation. In this case, B is larger
than A.
• 'same' (the default) returns the central part of the correlation. In this case,
B is the same size as A.
• 'valid' returns only those parts of the correlation that are computed
without zero-padded edges. In this case, B is smaller than A.
Cla ss Support
The matrix inputs to filter2 can be of class uint8 or double. The output
matrix B is of class double.
Rema rk s
Two-dimensional correlation is equivalent to two-dimensional convolution
with the filter matrix rotated 180 degrees. See the Algorithm section for more
information about how filter2 performs linear filtering.
filter2 is a function in MATLAB.
11-62
www.MatlabSite.com
filter2
Ex a mple
A = magic(6)
A =
35
3
31
8
30
4
1
32
9
28
5
36
6
7
2
33
34
29
26
21
22
17
12
13
19
23
27
10
14
18
24
25
20
15
16
11
h = fspecial('sobel')
h =
1
0
–1
2
0
–2
1
0
–1
B = filter2(h,A,'valid')
B =
–8
–23
–23
–8
Algorithm
4
–44
–50
4
4
–5
1
4
–8
40
40
–8
Given an image A and a two-dimensional FIR filter h, filter2 rotates your
filter matrix (the computational molecule) 180 degrees to create a convolution
kernel. It then calls conv2, the two-dimensional convolution function, to
implement the filtering operation.
filter2 uses conv2 to compute the full two-dimensional convolution of the FIR
filter with the input matrix. By default, filter2 then extracts the central part
of the convolution that is the same size as the input matrix, and returns this as
the result. If the shape parameter specifies an alternate part of the convolution
for the result, filter2 returns the appropriate part.
See Also
conv2, roifilt2
www.MatlabSite.com
11-63
freqspa ce
Purpose
11freqspace
Determine frequency spacing for two-dimensional frequency response
Synta x
[f1,f2] = freqspace(n)
[f1,f2] = freqspace([m n])
[x1,y1] = freqspace(...,'meshgrid')
f = freqspace(N)
f = freqspace(N,'whole')
Description
freqspace returns the implied frequency range for equally spaced frequency
responses. freqspace is useful when creating desired frequency responses for
fsamp2, fwind1, and fwind2, as well as for various one-dimensional
applications.
[f1,f2] = freqspace(n) returns the two-dimensional frequency vectors f1
and f2 for an n-by-n matrix.
For n odd, both f1 and f2 are [–n+1:2:n–1]/n.
For n even, both f1 and f2 are [–n:2:n–2]/n.
[f1,f2] = freqspace([m n]) returns the two-dimensional frequency vectors
f1 and f2 for an m-by-n matrix.
[x1,y1] = freqspace(...,'meshgrid') is equivalent to
[f1,f2] = freqspace(...);
[x1,y1] = meshgrid(f1,f2);
f = freqspace(N) returns the one-dimensional frequency vector f assuming N
evenly spaced points around the unit circle. For N even or odd, f is (0:2/N:1).
For N even, freqspace therefore returns (N+2)/2 points. For N odd, it returns
(N+1)/2 points.
f = freqspace(N,'whole') returns N evenly spaced points around the whole
unit circle. In this case, f is 0:2/N:2*(N–1)/N.
Rema rk s
freqspace is a function in MATLAB.
See Also
fsamp2, fwind1, fwind2
meshgrid in the online MATLAB Function Reference
11-64
www.MatlabSite.com
freqz2
Purpose
11freqz2
Compute two-dimensional frequency response
Synta x
[H,f1,f2] = freqz2(h,n1,n2)
[H,f1,f2] = freqz2(h,[n2 n1])
[H,f1,f2] = freqz2(h,f1,f2)
[H,f1,f2] = freqz2(h)
[...] = freqz2(h,...,[dx dy])
[...] = freqz2(h,...,dx)
freqz2(...)
Description
[H,f1,f2] = freqz2(h,n1,n2) returns H, the n2-by-n1 frequency response of
h, and the frequency vectors f1 (of length n1) and f2 (of length n2). h is a
two-dimensional FIR filter, in the form of a computational molecule. f1 and f2
are returned as normalized frequencies in the range –1.0 to 1.0, where 1.0
corresponds to half the sampling frequency, or π radians.
[H,f1,f2] = freqz2(h,[n2 n1]) returns the same result returned by
[H,f1,f2] = freqz2(h,n1,n2).
[H,f1,f2] = freqz2(h) uses [n2 n1] = [64 64].
[H,f1,f2] = freqz2(h,f1,f2) returns the frequency response for the FIR
filter h at frequency values in f1 and f2. These frequency values must be in the
range –1.0 to 1.0, where 1.0 corresponds to half the sampling frequency, or π
radians.
[...] = freqz2(h,...,[dx dy]) uses [dx dy] to override the intersample
spacing in h. dx determines the spacing for the x-dimension and dy determines
the spacing for the y-dimension. The default spacing is 0.5, which corresponds
to a sampling frequency of 2.0.
[...] = freqz2(h,...,dx) uses dx to determine the intersample spacing in
both dimensions.
With no output arguments, freqz2(...) produces a mesh plot of the
two-dimensional magnitude frequency response.
Cla ss Support
The input matrix h can be of class uint8 or double. All other inputs to freqz2
must be of class double. All outputs are of class double.
www.MatlabSite.com
11-65
freqz2
Ex a mple
Use the window method to create a 16-by-16 filter, then view its frequency
response using freqz2.
Hd = zeros(16,16);
Hd(5:12,5:12) = 1;
Hd(7:10,7:10) = 0;
h = fwind1(Hd,bartlett(16));
colormap(jet(64))
freqz2(h,[32 32]); axis ([–1 1 –1 1 0 1])
See Also
11-66
freqz in the Signal Processing Toolbox
www.MatlabSite.com
fsa m p2
Purpose
11fsamp2
Design two-dimensional FIR filter using frequency sampling
Synta x
h = fsamp2(Hd)
h = fsamp2(f1,f2,Hd,[m n])
Description
fsamp2 designs two-dimensional FIR filters based on a desired
two-dimensional frequency response sampled at points on the Cartesian plane.
h = fsamp2(Hd) designs a two-dimensional FIR filter with frequency response
Hd, and returns the filter coefficients in matrix h. (fsamp2 returns h as a
computational molecule, which is the appropriate form to use with filter2.)
The filter h has a frequency response that passes through points in Hd. If Hd is
m-by-n, then h is also m-by-n.
Hd is a matrix containing the desired frequency response sampled at equally
spaced points between –1.0 and 1.0 along the x and y frequency axes, where 1.0
corresponds to half the sampling frequency, or π radians.
H d ( f 1, f 2 ) = H d ( ω 1, ω 2 )
ω 1 = π f 1, ω 2 = π f 2
For accurate results, use frequency points returned by freqspace to create Hd.
(See the entry for freqspace for more information.)
h = fsamp2(f1,f2,Hd,[m n]) produces an m-by-n FIR filter by matching the
filter response at the points in the vectors f1 and f2. The frequency vectors f1
and f2 are in normalized frequency, where 1.0 corresponds to half the sampling
frequency, or π radians. The resulting filter fits the desired response as closely
as possible in the least squares sense. For best results, there must be at least
m*n desired frequency points. fsamp2 issues a warning if you specify fewer than
m*n points.
Cla ss Support
The input matrix Hd can be of class uint8 or double. All other inputs to fsamp2
must be of class double. All outputs are of class double.
Ex a mple
Use fsamp2 to design an approximately symmetric two-dimensional bandpass
filter with passband between 0.1 and 0.5 (normalized frequency, where 1.0
corresponds to half the sampling frequency, or π radians).
www.MatlabSite.com
11-67
fsa mp2
1 Create a matrix Hd that contains the desired bandpass response. Use
freqspace to create the frequency range vectors f1 and f2.
[f1,f2] = freqspace(21,'meshgrid');
Hd = ones(21);
r = sqrt(f1.^2 + f2.^2);
Hd((r<0.1)|(r>0.5)) = 0;
colormap(jet(64))
mesh(f1,f2,Hd)
2 Design the filter that passes through this response.
h = fsamp2(Hd);
11-68
www.MatlabSite.com
fsa m p2
freqz2(h)
Algorithm
fsamp2 computes the filter h by taking the inverse discrete Fourier transform
of the desired frequency response. If the desired frequency response is real and
symmetric (zero phase), the resulting filter is also zero phase.
See Also
conv2, filter2, freqspace, ftrans2, fwind1, fwind2
Reference
Lim, Jae S. Two-Dimensional Signal and Image Processing. Englewood Cliffs,
NJ: Prentice Hall, 1990. pp. 213-217.
www.MatlabSite.com
11-69
fspecia l
Purpose
11fspecial
Create predefined filters
Synta x
h = fspecial(type)
h = fspecial(type,parameters)
Description
h = fspecial(type) creates a two-dimensional filter h of the specified type.
(fspecial returns h as a computational molecule, which is the appropriate
form to use with filter2.) type is a string having one of these values:
• 'gaussian' for a Gaussian lowpass filter
• 'sobel' for a Sobel horizontal edge-emphasizing filter
• 'prewitt' for a Prewitt horizontal edge-emphasizing filter
• 'laplacian' for a filter approximating the two-dimensional Laplacian
operator
• 'log' for a Laplacian of Gaussian filter
• 'average' for an averaging filter
• 'unsharp' for an unsharp contrast enhancement filter
Depending on type, fspecial may take additional parameters which you can
supply. These parameters all have default values.
h = fspecial('gaussian',n,sigma) returns a rotationally symmetric
Gaussian lowpass filter with standard deviation sigma (in pixels). n is a 1-by-2
vector specifying the number of rows and columns in h. (n can also be a scalar,
in which case h is n-by-n.) If you do not specify the parameters, fspecial uses
the default values of [3 3] for n and 0.5 for sigma.
h = fspecial('sobel') returns this 3-by-3 horizontal edge-finding and
y-derivative approximation filter:
[ 1 2 1
0 0 0
–1 –2 –1 ]
To find vertical edges, or for x-derivatives, use –h'.
11-70
www.MatlabSite.com
fspecia l
h = fspecial('prewitt') returns this 3-by-3 horizontal edge-finding and
y-derivative approximation filter:
[ 1 1 1
0 0 0
–1 –1 –1 ]
To find vertical edges, or for x-derivatives, use –h'.
h = fspecial('laplacian',alpha) returns a 3-by-3 filter approximating the
two-dimensional Laplacian operator. The parameter alpha controls the shape
of the Laplacian and must be in the range 0 to 1.0. fspecial uses the default
value of 0.2 if you do not specify alpha.
h = fspecial('log',n,sigma) returns a rotationally symmetric Laplacian of
Gaussian filter with standard deviation sigma (in pixels). n is a 1-by-2 vector
specifying the number of rows and columns in h. (n can also be a scalar, in
which case h is n-by-n.) If you do not specify the parameters, fspecial uses the
default values of [5 5] for n and 0.5 for sigma.
h = fspecial('average',n) returns an averaging filter. n is a 1-by-2 vector
specifying the number of rows and columns in h. (n can also be a scalar, in
which case h is n-by-n.) If you do not specify n, fspecial uses the default value
of [3 3].
h = fspecial('unsharp',alpha) returns a 3-by-3 unsharp contrast
enhancement filter. fspecial creates the unsharp filter from the negative of
the Laplacian filter with parameter alpha. alpha controls the shape of the
Laplacian and must be in the range 0 to 1.0. fspecial uses the default value
of 0.2 if you do not specify alpha.
www.MatlabSite.com
11-71
fspecia l
Ex a mple
Algorithms
I = imread('saturn.tif');
h = fspecial('unsharp',0.5);
I2 = filter2(h,I)/255;
imshow(I)
figure, imshow(I2)
fspecial creates Gaussian filters using:
h g ( n 1, n 2 ) = e
– ( n 1 + n 2 ) ⁄ ( 2σ )
2
2
2
h g ( n 1, n 2 )
h ( n 1, n 2 ) = ---------------------------hg
∑∑
n1 n2
fspecial creates Laplacian filters using:
2
2
2
∂
∂
∇ = --------- + --------2
2
∂y
∂x
α
--4
4
2
1
–
α
∇ ≈ ------------------ -----------(α + 1) 4 α
--4
1–α
------------4
–1
1–α
------------4
α
--4
1–α
------------4
α
--4
fspecial creates Laplacian of Gaussian (LoG) filters using:
11-72
www.MatlabSite.com
fspecia l
h g ( n 1, n 2 ) = e
– ( n 1 + n 2 ) ⁄ ( 2σ )
2
2
2
2
2
2
( n 1 + n 2 – 2σ )h g ( n 1, n 2 )
h ( n 1, n 2 ) = -----------------------------------------------------------------------6
2πσ
hg
∑∑
n1 n2
fspecial creates averaging filters using:
ones(n(1),n(2))/(n(1)*n(2))
fspecial creates unsharp filters using:
–α
1
------------------ α – 1
(α + 1)
–α
See Also
α–1
α+5
α–1
–α
α–1
–α
conv2, edge, filter2, fsamp2, fwind1, fwind2
del2 in the online MATLAB Function Reference
www.MatlabSite.com
11-73
ftra ns2
Purpose
11ftrans2
Design two-dimensional FIR filter using frequency transformation
Synta x
h = ftrans2(b,t)
h = ftrans2(b)
Description
h = ftrans2(b,t) produces the two-dimensional FIR filter h that corresponds
to the one-dimensional FIR filter b using the transform t. (ftrans2 returns h
as a computational molecule, which is the appropriate form to use with
filter2.) b must be a one-dimensional, odd-length (Type I) FIR filter such
as can be returned by fir1, fir2, or remez in the Signal Processing Toolbox.
The transform matrix t contains coefficients that define the frequency
transformation to use. If t is m-by-n and b has length Q, then h is size
((m–1)*(Q–1)/2+1)-by-((n–1)*(Q–1)/2+1).
h = ftrans2(b) uses the McClellan transform matrix t:
t = [1 2 1; 2 –4 2; 1 2 1]/8;
Rema rk s
The transformation below defines the frequency response of the
two-dimensional filter returned by ftrans2:
H ( ω 1, ω 2 ) = B ( ω )
cos ω = T ( ω 1, ω 2 )
where B(ω) is the Fourier transform of the one-dimensional filter b:
N
B(ω) =
∑
b ( n )e
– jωn
n = –N
and T(ω1,ω2) is the Fourier transform of the transformation matrix t:
T ( ω 1, ω 2 ) =
∑ ∑ t ( n1, n2 )e
– jω 1 n 1 – jω 2 n 2
e
n2 n1
The returned filter h is the inverse Fourier transform of H(ω1,ω2):
1
h ( n 1, n 2 ) = -------------2( 2π )
11-74
π
π
∫–π ∫–π H ( ω1, ω2 )e
jω 1 n 1 jω 2 n 2
www.MatlabSite.com
e
dω 1 dω 2
ftra ns2
Ex a mple
Use ftrans2 to design an approximately circularly symmetric two-dimensional
bandpass filter with passband between 0.1 and 0.6 (normalized frequency,
where 1.0 corresponds to half the sampling frequency, or π radians).
1 Since ftrans2 transforms a one-dimensional FIR filter to create a
two-dimensional filter, first design a one-dimensional FIR bandpass filter
using the Signal Processing Toolbox function remez:
colormap(jet(64))
b = remez(10,[0 0.05 0.15 0.55 0.65 1],[0 0 1 1 0 0]);
[H,w] = freqz(b,1,128,'whole');
plot(w/pi–1,fftshift(abs(H)))
2 Use ftrans2 with the default McClellan transformation to create the
desired approximately circularly symmetric filter
h = ftrans2(b);
www.MatlabSite.com
11-75
ftra ns2
freqz2(h)
See Also
conv2, filter2, fsamp2, fwind1, fwind2
Reference
Lim, Jae S. Two-Dimensional Signal and Image Processing. Englewood Cliffs,
NJ: Prentice Hall, 1990. pp. 218-237.
11-76
www.MatlabSite.com
fw ind1
Purpose
11fwind1
Design two-dimensional FIR filter using one-dimensional window method
Synta x
h = fwind1(Hd,win)
h = fwind1(Hd,win1,win2)
h = fwind1(f1,f2,Hd,...)
Description
fwind1 designs two-dimensional FIR filters using the window method. fwind1
uses a one-dimensional window specification to design a two-dimensional FIR
filter based on the desired frequency response Hd. fwind1 works with
one-dimensional windows only; use fwind2 to work with two-dimensional
windows.
h = fwind1(Hd,win) designs a two-dimensional FIR filter h with frequency
response Hd. (fwind1 returns h as a computational molecule, which is the
appropriate form to use with filter2.) fwind1 uses the one-dimensional
window win to form an approximately circularly symmetric two-dimensional
window using Huang’s method. You can specify win using windows from the
Signal Processing Toolbox, such as boxcar, hamming, hanning, bartlett,
blackman, kaiser, or chebwin. If length(win) is n, then h is n-by-n.
Hd is a matrix containing the desired frequency response sampled at equally
spaced points between –1.0 and 1.0 (in normalized frequency, where 1.0
corresponds to half the sampling frequency, or π radians) along the x and y
frequency axes. For accurate results, use frequency points returned by
freqspace to create Hd. (See the entry for freqspace for more information.)
h = fwind1(Hd,win1,win2) uses the two one-dimensional windows win1 and
win2 to create a separable two-dimensional window. If length(win1) is n and
length(win2) is m, then h is m-by-n.
h = fwind1(f1,f2,Hd,...) lets you specify the desired frequency response Hd
at arbitrary frequencies (f1 and f2) along the x and y axes. The frequency
vectors f1 and f2 should be in the range –1.0 to 1.0, where 1.0 corresponds to
half the sampling frequency, or π radians. The length of the window(s) controls
the size of the resulting filter, as above.
Ex a mple
Use fwind1 to design an approximately circularly symmetric two-dimensional
bandpass filter with passband between 0.1 and 0.5 (normalized frequency,
where 1.0 corresponds to half the sampling frequency, or π radians).
www.MatlabSite.com
11-77
fw ind1
1 Create a matrix Hd that contains the desired bandpass response. Use
freqspace to create the frequency range vectors f1 and f2.
[f1,f2] = freqspace(21,'meshgrid');
Hd = ones(21);
r = sqrt(f1.^2 + f2.^2);
Hd((r<0.1)|(r>0.5)) = 0;
colormap(jet(64))
mesh(f1,f2,Hd)
2 Design the filter using a one-dimensional Hamming window.
h = fwind1(Hd,hamming(21));
11-78
www.MatlabSite.com
fw ind1
freqz2(h)
Algorithm
fwind1 takes a one-dimensional window specification and forms an
approximately circularly symmetric two-dimensional window using Huang’s
method
w ( n 1, n 2 ) = w ( t )
t=
2
2
n1 + n2
where w(t) is the one-dimensional window and w(n1,n2) is the resulting
two-dimensional window.
Given two windows, fwind1 forms a separable two-dimensional window,
w ( n 1, n 2 ) = w 1 ( n 1 )w 2 ( n 2 )
fwind1 calls fwind2 with Hd and the two-dimensional window. fwind2
computes h using an inverse Fourier transform and multiplication by the
two-dimensional window:
jω 1 n 1 jω 2 n 2
1 π π
h d ( n 1, n 2 ) = -------------2H d ( ω 1, ω 2 )e
e
dω 1 dω 2
–
π
–
π
( 2π )
h ( n 1, n 2 ) = h d ( n 1, n 2 )w ( n 1, n 2 )
∫ ∫
www.MatlabSite.com
11-79
fw ind1
See Also
conv2, filter2, fsamp2, freqspace, ftrans2, fwind2
Reference
Lim, Jae S. Two-Dimensional Signal and Image Processing. Englewood Cliffs,
NJ: Prentice Hall, 1990.
11-80
www.MatlabSite.com
fw ind2
Purpose
11fwind2
Design two-dimensional FIR filter using two-dimensional window method
Synta x
h = fwind2(Hd,win)
h = fwind2(f1,f2,Hd,win)
Description
Use fwind2 to design two-dimensional FIR filters using the window method.
fwind2 uses a two-dimensional window specification to design a
two-dimensional FIR filter based on the desired frequency response Hd. fwind2
works with two-dimensional windows; use fwind1 to work with
one-dimensional windows.
h = fwind2(Hd,win) produces the two-dimensional FIR filter h using an
inverse Fourier transform of the desired frequency response Hd and
multiplication by the window win. Hd is a matrix containing the desired
frequency response at equally spaced points in the Cartesian plane. fwind2
returns h as a computational molecule, which is the appropriate form to use
with filter2. h is the same size as win.
For accurate results, use frequency points returned by freqspace to create Hd.
(See the entry for freqspace for more information.
h = fwind2(f1,f2,Hd,win) lets you specify the desired frequency response Hd
at arbitrary frequencies (f1 and f2) along the x and y axes. The frequency
vectors f1 and f2 should be in the range –1.0 to 1.0, where 1.0 corresponds to
half the sampling frequency, or π radians. h is the same size as win.
Ex a mple
Use fwind2 to design an approximately circularly symmetric two-dimensional
bandpass filter with passband between 0.1 and 0.5 (normalized frequency,
where 1.0 corresponds to half the sampling frequency, or π radians).
www.MatlabSite.com
11-81
fw ind2
1 Create a matrix Hd that contains the desired bandpass response. Use
freqspace to create the frequency range vectors f1 and f2.
[f1,f2] = freqspace(21,'meshgrid');
Hd = ones(21);
r = sqrt(f1.^2 + f2.^2);
Hd((r<0.1)|(r>0.5)) = 0;
colormap(jet(64))
mesh(f1,f2,Hd)
11-82
www.MatlabSite.com
fw ind2
2 Create a two-dimensional Gaussian window using fspecial.
win = fspecial('gaussian',21,2);
win = win ./ max(win(:)); % Make the maximum window value be 1.
mesh(win)
3 Design the filter using the window from step 2.
h = fwind2(Hd,win);
www.MatlabSite.com
11-83
fw ind2
freqz2(h)
Algorithm
fwind2 computes h using an inverse Fourier transform and multiplication by
the two-dimensional window win:
1
h d ( n 1, n 2 ) = -------------2( 2π )
π
π
∫–π ∫–π H d ( ω1, ω2 )e
jω 1 n 1 jω 2 n 2
e
dω 1 dω 2
h ( n 1, n 2 ) = h d ( n 1, n 2 )w ( n 1, n 2 )
See Also
conv2, filter2, fsamp2, freqspace, ftrans2, fwind1
Reference
Lim, Jae S. Two-Dimensional Signal and Image Processing. Englewood Cliffs,
NJ: Prentice Hall, 1990. pp. 202-213.
11-84
www.MatlabSite.com
getim a ge
Purpose
11getimage
Get image data from axes
Synta x
A = getimage(h)
[x,y,A] = getimage(h)
[...,A,flag] = getimage(h)
[...] = getimage
Description
A = getimage(h) returns the first image data contained in the Handle
Graphics object h. h can be a figure, axes, image, or texture-mapped surface. A
is identical to the image CData; it contains the same values and is of the same
class (uint8 or double) as the image CData. If h is not an image or does not
contain an image or texture-mapped surface, A is empty.
[x,y,A] = getimage(h) returns the image XData in x and the YData in y. XData
and YData are two-element vectors that indicate the range of the x-axis and
y-axis.
[...,A,flag] = getimage(h) returns an integer flag that indicates the type
of image h contains. This table summarizes the possible values for flag:
Fla g
Type of ima ge
0
Not an image; A is returned as an empty matrix
1
Intensity image with values in standard range ([0,1] for
double arrays, [0,255] for uint8 arrays)
2
Indexed image
3
Intensity data, but not in standard range
4
RGB image
[...] = getimage returns information for the current axes. It is equivalent to
[...] = getimage(gca).
Cla ss Support
The output array A is of the same class as the image CData. All other inputs and
outputs are of class double.
www.MatlabSite.com
11-85
getima ge
Ex a mple
This example illustrates obtaining the image data from an image displayed
directly from a file.
imshow rice.tif
I = getimage;
11-86
www.MatlabSite.com
gra y2 ind
Purpose
11gray2ind
Convert an intensity image to an indexed image
Synta x
[X,map] = gray2ind(I,n)
Description
gray2ind scales, then rounds, an intensity image to produce an equivalent
indexed image.
[X,map] = gray2ind(I,n) converts the intensity image I to an indexed image
X with colormap gray(n). If n is omitted, it defaults to 64.
Cla ss Support
The input image I can be of class uint8 or double. The class of the output
image X is uint8 if the colormap length is less than or equal to 256. If the
colormap length is greater than 256, X is of class double.
See Also
ind2gray
www.MatlabSite.com
11-87
gra yslice
Purpose
11grayslice
Create indexed image from intensity image, using multilevel thresholding
Synta x
X = grayslice(I,n)
X = grayslice(I,v)
Description
X = grayslice(I,n) thresholds the intensity image I using cutoff values
n–1
1 2
---, ---, …, ------------- , returning an indexed image in X.
n
n n
X = grayslice(I,v), where v is a vector of values between 0 and 1, thresholds
I using the values of v, returning an indexed image in X.
You can view the thresholded image using imshow(X,map) with a colormap of
appropriate length.
Cla ss Support
The input image I can be of class uint8 or double. Note that the threshold
values are always between 0 and 1, even if I is of class uint8. In this case, each
threshold value is multiplied by 255 to determine the actual threshold to use.
The class of the output image X depends on the number of threshold values, as
specified by n or length(v). If the number of threshold values is less than 256,
then X is of class uint8, and the values in X range from 0 to n or length(v). If
the number of threshold values is 256 or greater, X is of class double, and the
values in X range from 1 to n+1 or length(v)+1.
Ex a mple
See Also
11-88
I = imread('ngc4024m.tif');
X = grayslice(I,16);
imshow(I)
figure, imshow(X,jet(16))
gray2ind
www.MatlabSite.com
histeq
Purpose
Synta x
11histeq
Enhance contrast using histogram equalization
J = histeq(I,hgram)
J = histeq(I,n)
[J,T] = histeq(I,...)
newmap = histeq(X,map,hgram)
newmap = histeq(X,map)
[newmap,T] = histeq(X,...)
Description
histeq enhances the contrast of images by transforming the values in an
intensity image, or the values in the colormap of an indexed image, so that the
histogram of the output image approximately matches a specified histogram.
J = histeq(I,hgram) transforms the intensity image I so that the histogram
of the output intensity image J with length(hgram) bins approximately
matches hgram. The vector hgram should contain integer counts for equally
spaced bins with intensity values from 0 to 1.0. histeq automatically scales
hgram so that sum(hgram) = prod(size(I)). The histogram of J will better
match hgram when length(hgram) is much smaller than the number of discrete
levels in I.
J = histeq(I,n) transforms the intensity image I, returning in J an intensity
image with n discrete gray levels. A roughly equal number of pixels is mapped
to each of the n levels in J, so that the histogram of J is approximately flat. (The
histogram of J is flatter when n is much smaller than the number of discrete
levels in I.) The default value for n is 64.
[J,T] = histeq(I,...) returns the gray scale transformation that maps gray
levels in the intensity image I to gray levels in J.
newmap = histeq(X,map,hgram) transforms the colormap associated with the
indexed image X so that the histogram of the gray component of the indexed
image (X,newmap) approximately matches hgram. histeq returns the
transformed colormap in newmap. length(hgram) must be the same as
size(map,1).
newmap = histeq(X,map) transforms the values in the colormap so that the
histogram of the gray component of the indexed image X is approximately flat.
It returns the transformed colormap in newmap.
www.MatlabSite.com
11-89
histeq
[newmap,T] = histeq(X,...) returns the grayscale transformation T that
maps the gray component of map to the gray component of newmap.
Cla ss Support
For syntaxes that include an intensity image I as input, I can be of class uint8
or double, and the output image J has the same class as I. For syntaxes that
include an indexed image X as input, X can be of class uint8 or double; the
output colormap is always of class double. Also, the optional output T (the gray
level transform) is always of class double.
Ex a mples
Enhance the contrast of an intensity image using histogram equalization.
I = imread('tire.tif');
J = histeq(I);
imshow(I)
figure, imshow(J)
Display the resulting histograms.
imhist(I,64)
figure; imhist(J,64)
11-90
www.MatlabSite.com
histeq
Algorithm
When you supply a desired histogram hgram, histeq chooses the grayscale
transformation T to minimize
c1 ( T ( k ) ) – c0 ( k )
where c0 is the cumulative histogram of A, c1 is the cumulative sum of hgram for
all intensities k. This minimization is subject to the constraints that T must be
monotonic and c1(T(a)) cannot overshoot c0(a) by more than half the distance
between the histogram counts at a. histeq uses this transformation to map the
gray levels in X (or the colormap) to their new values
b = T (a)
If you do not specify hgram, histeq creates a flat hgram
hgram = ones(1,n)*prod(size(A))/n;
and then applies the previous algorithm.
See Also
brighten, imadjust, imhist
www.MatlabSite.com
11-91
hsv2 rgb
Purpose
11hsv2rgb
Convert hue-saturation-value (HSV) values to RGB color space
Synta x
rgbmap = hsv2rgb(hsvmap)
RGB = hsv2rgb(HSV)
Description
rgbmap = hsv2rgb(hsvmap) converts the HSV values in hsvmap to RGB color
space. hsvmap is an m-by-3 matrix that contains hue, saturation, and value
components as its three columns, and rgbmap is returned as an m-by-3 matrix
that represents the same set of colors as red, green, and blue values. Both
rgbmap and hsvmap contain values in the range 0 to 1.0.
RGB = hsv2rgb(HSV) converts the HSV image to the equivalent RGB image.
HSV is an m-by-n-by-3 image array whose three planes contain the hue,
saturation, and value components for the image. RGB is returned as an
m-by-n-by-3 image array whose three planes contain the red, green, and blue
components for the image.
Cla ss Support
The input array to hsv2rgb must be of class double. The output array is of class
double.
Rema rk s
hsv2rgb is a function in MATLAB.
See Also
rgb2hsv, rgbplot
colormap in the online MATLAB Function Reference
11-92
www.MatlabSite.com
idct2
Purpose
Synta x
Description
11idct2
Compute two-dimensional inverse discrete cosine transform
B = idct2(A)
B = idct2(A,m,n)
B = idct2(A,[m n])
B = idct2(A) returns the two-dimensional inverse discrete cosine transform
of A.
B = idct2(A,m,n) or B = idct2(A,[m n]) pads A with zeros to size m-by-n
before transforming. If [m n] < size(A), idct2 crops A before transforming.
For any A, idct2(dct2(A)) equals A to within roundoff error.
Cla ss Support
The input matrix A can be of class uint8 or double. The output matrix B is of
class double.
Algorithm
idct2 computes the two-dimensional inverse DCT using
M–1 N–1
A mn =
∑ ∑
p=0 q=0
π ( 2m + 1 ) p
π ( 2n + 1 )q
α p α q B pq cos ------------------------------- cos ----------------------------- ,
2M
2N
1 ⁄ M, p = 0
αp =
2 ⁄ M, 1 ≤ p ≤ M – 1
0≤m≤M–1
0≤n≤N–1
1 ⁄ N , q = 0
αq =
2 ⁄ N, 1 ≤ q ≤ N – 1
See Also
dct2, dctmtx, fft2, ifft2
References
Jain, Anil K. Fundamentals of Digital Image Processing. Englewood Cliffs, NJ:
Prentice Hall, 1989. pp. 150-153.
Pennebaker, William B., and Joan L. Mitchell. JPEG: Still Image Data
Compression Standard. New York: Van Nostrand Reinhold, 1993.
11
www.MatlabSite.com
11-93
ifft2
Purpose
11ifft2
Compute two-dimensional inverse fast Fourier transform
Synta x
B = ifft2(A)
B = ifft2(A,m,n)
Description
B = ifft2(A) returns the two-dimensional inverse fast Fourier transform of
matrix A. If A is a vector, B has the same orientation as A.
B = ifft(A,m,n) pads matrix A with zeros to size m-by-n. If [m n] < size(A),
ifft2 crops A before transforming.
For any A, ifft2(fft2(A)) equals A to within roundoff error. If A is real,
ifft2(fft2(A)) may have small imaginary parts.
Cla ss Support
The input matrix A can be of class uint8 or double. The output matrix B is of
class double.
Rema rk s
ifft2 is a function in MATLAB.
Algorithm
The algorithm for ifft2(A) is the same as the algorithm for fft2(A), except
for a sign change and scale factors of [m,n] = size(A). Like fft2, the execution
time is fastest when m and n are powers of 2 and slowest when they are large
prime numbers.
See Also
fft2, fftshift, idct2
dftmtx, filter, freqz, specplot, spectrum in the Signal Processing Toolbox
User’s Guide
fft, ifft in the online MATLAB Function Reference
11-94
www.MatlabSite.com
ifftn
Purpose
11ifftn
Compute N-dimensional inverse fast Fourier transform
Synta x
B = ifftn(A)
B = ifftn(A,siz)
Description
B = ifftn(A) performs the N-dimensional inverse fast Fourier transform. The
result B is the same size as A.
B = ifftn(A,siz) pads A with zeros (or truncates A) to create an
N-dimensional array of size siz before doing the inverse transform. The size
of the result is siz.
For any A, ifftn(fftn(A)) equals A within roundoff error. If A is real,
ifftn(fftn(A)) may have small imaginary parts.
Cla ss Support
The input matrix A can be of class uint8 or double. The output matrix B is of
class double.
Rema rk s
ifftn is a function in MATLAB.
Algorithm
ifftn(A) is equivalent to
B = A;
for p = 1:length(size(A))
B = ifft(B,[],p);
end
This code computes the one-dimensional inverse fast Fourier transform along
each dimension of A. The time required to compute ifftn(A) depends strongly
on the number of prime factors of the dimensions of A. It is fastest when all of
the dimensions are powers of 2.
See Also
fft2, fftn, ifft2
www.MatlabSite.com
11-95
im2 bw
Purpose
11im2bw
Convert an image to a binary image, based on threshold
Synta x
BW = im2bw(I,level)
BW = im2bw(X,map,level)
BW = im2bw(RGB,level)
Description
im2bw produces binary images from indexed, intensity, or RGB images. To do
this, it converts the input image to grayscale format (if it is not already an
intensity image), and then converts this grayscale image to binary by
thresholding. The output binary image BW has values of 0 (black) for all pixels
in the input image with luminance less than level and 1 (white) for all other
pixels. (Note that you specify level in the range [0,1], regardless of the class of
the input image.)
BW = im2bw(I,level) converts the intensity image I to black and white.
BW = im2bw(X,map,level) converts the indexed image X with colormap map to
black and white.
BW = im2bw(RGB,level) converts the RGB image RGB to black and white.
Cla ss Support
Ex a mple
See Also
11-96
The input image can be of class uint8 or double. The output image BW is of class
uint8.
load trees
BW = im2bw(X,map,0.4);
imshow(X,map)
figure, imshow(BW)
ind2gray, rgb2gray
www.MatlabSite.com
im 2 col
Purpose
11im2col
Rearrange image blocks into columns
Synta x
B = im2col(A,[m n],block_type)
B = im2col(A,[m n])
B = im2col(A,'indexed',...)
Description
im2col rearranges image blocks into columns. block_type is a string that can
have one of these values:
• 'distinct' for m-by-n distinct blocks
• 'sliding' for m-by-n sliding blocks (default)
B = im2col(A,[m n],'distinct') rearranges each distinct m-by-n block in the
image A into a column of B. im2col pads A with zeros, if necessary, so its size is
an integer multiple of m-by-n. If A = [A11 A12;A21 A22], where each Aij is
m-by-n, then B = [A11(:) A12(:) A21(:) A22(:)].
B = im2col(A,[m n],'sliding') converts each sliding m-by-n block of A into a
column of B, with no zero padding. B has m*n rows and will contain as many
columns as there are m-by-n neighborhoods of A. If the size of A is [mm nn], then
the size of B is (m*n)-by-((mm–m+1)*(nn–n+1)).
B = im2col(A,[m n]) uses the default block_type of 'sliding'.
For the sliding block case, each column of B contains the neighborhoods of A
reshaped as nhood(:) where nhood is a matrix containing an m-by-n
neighborhood of A. im2col orders the columns of B so that they can be reshaped
to form a matrix in the normal way. For example, suppose you use a function,
such as sum(B), that returns a scalar for each column of B. You can directly
store the result in a matrix of size (mm–m+1)-by-(nn–n+1), using these calls:
B = im2col(A,[m n],'sliding');
C = reshape(sum(B),mm–m+1,nn–n+1);
B = im2col(A,'indexed',...) processes A as an indexed image, padding with
zeros if the class of A is uint8, or ones if the class of A is double.
Cla ss Support
The input image A can be of class uint8 or double. The output matrix B is of
the same class as the input image.
See Also
blkproc, col2im, colfilt, nlfilter
www.MatlabSite.com
11-97
im2 double
Purpose
11im2double
Convert image array to double precision
Synta x
I2 = im2double(I1)
RGB2 = im2double(RGB1)
BW2 = im2double(BW1)
X2 = im2double(X1,'indexed')
Description
im2double takes an image as input, and returns an image of class double. If
the input image is of class double, the output image is identical to it. If the
input image is of class uint8, im2double returns the equivalent image of class
double, rescaling or offsetting the data as necessary.
I2 = im2double(I1) converts the intensity image I1 to double precision,
rescaling the data if necessary.
RGB2 = im2double(RGB1) converts the truecolor image RGB1 to double
precision, rescaling the data if necessary.
BW2 = im2double(BW1) converts the binary image BW1 to double precision.
X2 = im2double(X1,'indexed') converts the indexed image X1 to double
precision, offsetting the data if necessary.
See Also
11-98
double, im2uint8, uint8
www.MatlabSite.com
im 2 uint8
Purpose
11im2uint8
Convert image array to eight-bit unsigned integers
Synta x
I2 = im2uint8(I1)
RGB2 = im2uint8(RGB1)
BW2 = im2uint8(BW1)
X2 = im2uint8(X1,'indexed')
Description
im2uint8 takes an image as input, and returns an image of class uint8. If the
input image is of class uint8, the output image is identical to it. If the input
image is of class double, im2uint8 returns the equivalent image of class uint8,
rescaling or offsetting the data as necessary.
I2 = im2uint8(I1) converts the intensity image I1 to uint8, rescaling the
data if necessary.
RGB2 = im2uint8(RGB1) converts the truecolor image RGB1 to uint8, rescaling
the data if necessary.
BW2 = im2uint8(BW1) converts the binary image BW1 to uint8.
X2 = im2uint8(X1,'indexed') converts the indexed image X1 to uint8,
offsetting the data if necessary. Note that max(X1(:)) must be 256 or less, or
else X1 cannot be converted to uint8.
See Also
double, im2double, uint8
www.MatlabSite.com
11-99
ima djust
Purpose
11imadjust
Adjust image intensity values or colormap
Synta x
J = imadjust(I,[low high],[bottom top],gamma)
newmap = imadjust(map,[low high],[bottom top],gamma)
Description
J = imadjust(I,[low high],[bottom top],gamma) transforms the values in
the intensity image I to values in J by mapping values between low and high
to values between bottom and top. Values below low and above high are
clipped; that is, values below low map to bottom, and those above high map to
top. You can use an emptry matrix ([]) for [low high] or for [bottom top] to
specify the default of [0 1]. gamma specifies the shape of the curve describing the
relationship between the values in I and J. If gamma is less than 1, the mapping
is weighted toward higher (brighter) output values. If gamma is greater than
than 1, the mapping is weighted toward lower (darker) output values. If you
omit the argument, gamma defaults to 1 (linear mapping).
newmap = imadjust(map,[low high],[bottom top],gamma) transforms the
colormap associated with an indexed image. If [low high] and [bottom top]
are both 2-by-3, and gamma is a 1-by-3 vector, imadjust rescales the red, green,
and blue components separately. The rescaled colormap, newmap, is the same
size as map.
RGB2 = imadjust(RGB1,...) performs the adjustment on each image plane
(red, green, and blue) of the RGB image RGB1. As with the colormap
adjustment, you can use different parameter values for each plane by
specifying [low high] and [bottom top] as 2-by-3 matrices, and gamma as a
1-by-3 vector.
Cla ss Support
For syntaxes that include an input image (rather than a colormap), the input
image can be of class uint8 or double. The output image has the same class as
the input image.
Rema rk s
If top < bottom, the output image is reversed (i.e., as in a negative).
11-100
www.MatlabSite.com
im a djust
Ex a mple
See Also
I = imread('pout.tif');
J = imadjust(I,[0.3 0.7],[]);
imshow(I)
figure, imshow(J)
brighten, histeq
www.MatlabSite.com
11-101
ima pprox
Purpose
11imapprox
Approximate indexed image by one with fewer colors
Synta x
[Y,newmap] = imapprox(X,map,n)
[Y,newmap] = imapprox(X,map,tol)
Y = imapprox(X,map,newmap)
[...] = imapprox(...,dither_option)
Description
[Y,newmap] = imapprox(X,map,n) approximates the colors in the indexed
image X and associated colormap map by using minimum variance
quantization. imapprox returns indexed image Y with colormap newmap, which
has at most n colors.
[Y,newmap] = imapprox(X,map,tol) approximates the colors in X and map
through uniform quantization. newmap contains at most (floor(1/tol)+1)^3
colors. tol must be between 0 and 1.0.
Y = imapprox(X,map,newmap) approximates the colors in map by using
colormap mapping to find the colors in newmap that best match the colors in map.
Y = imapprox(...,dither_option) enables or disables dithering.
dither_option is a string that can have one of these values:
• 'dither' dithers, if necessary, to achieve better color resolution at the
expense of spatial resolution (default).
• 'nodither' maps each color in the original image to the closest color in the
new map. No dithering is performed.
Cla ss Support
The input image X can be of class uint8 or double. The output image Y is of
class uint8 if the length of newmap is less than or equal to 256. If the length of
newmap is greater than 256, X is of class double.
Algorithm
imapprox uses rgb2ind to create a new colormap that uses fewer colors.
See Also
cmunique, dither, rgb2ind
11-102
www.MatlabSite.com
im contour
Purpose
11imcontour
Create a contour plot of image data
Synta x
imcontour(I,n)
imcontour(I,v)
imcontour(x,y,...)
imcontour(...,LineSpec)
[C,h] = imcontour(...)
Description
imcontour(I,n) draws a contour plot of the intensity image I, automatically
setting up the axes so their orientation and aspect ratio match the image. n is
the number of equally spaced contour levels in the plot; if you omit the
argument, the number of levels and the values of the levels are chosen
automatically.
imcontour(I,v) draws a contour plot of I with contour lines at the data values
specified in vector v. The number of contour levels is equal to length(v).
imcontour(x,y,...) uses the vectors x and y to specify the x- and y-axis limits.
imcontour(...,LineSpec) draws the contours using the line type and color
specified by LineSpec. Marker symbols are ignored.
[C,h] = imcontour(...) returns the contour matrix C and a vector of handles
to the objects in the plot. (The objects are actually patches, and the lines are
the edges of the patches.) You can use the clabel function with the contour
matrix C to add contour labels to the plot.
Cla ss Support
The input image can be of class uint8 or double.
www.MatlabSite.com
11-103
imcontour
Ex a mple
See Also
11-104
I = imread('ic.tif');
imcontour(I,3)
clabel, contour, LineSpec in the online MATLAB Function Reference
www.MatlabSite.com
im crop
Purpose
Synta x
11imcrop
Crop an image
I2 = imcrop(I)
X2 = imcrop(X,map)
RGB2 = imcrop(RGB)
I2 = imcrop(I,rect)
X2 = imcrop(X,map,rect)
RGB2 = imcrop(RGB,rect)
[...] = imcrop(x,y,...)
[A,rect] = imcrop(...)
[x,y,A,rect] = imcrop(...)
Description
imcrop crops an image to a specified rectangle. In the syntaxes below, imcrop
displays the input image and waits for you to specify the crop rectangle with
the mouse:
I2 = imcrop(I)
X2 = imcrop(X,map)
RGB2 = imcrop(RGB)
If you omit the input arguments, imcrop operates on the image in the current
axes.
To specify the rectangle:
• For a single-button mouse, press the mouse button and drag to define the
crop rectangle. Finish by releasing the mouse button.
• For a 2- or 3-button mouse, press the left mouse button and drag to define
the crop rectangle. Finish by releasing the mouse button.
If you hold down the Shift key while dragging, or if you press the right mouse
button on a 2- or 3-button mouse, imcrop constrains the bounding rectangle to
be a square.
When you release the mouse button, imcrop returns the cropped image in the
supplied output argument. If you do not supply an output argument, imcrop
displays the output image in a new figure.
www.MatlabSite.com
11-105
imcrop
You can also specify the cropping rectangle noninteractively, using these
syntaxes:
I2 = imcrop(I,rect)
X2 = imcrop(X,map,rect)
RGB2 = imcrop(RGB,rect)
rect is a 4-element vector with the form [xmin ymin width height]; these
values are specified in spatial coordinates.
To specify a nondefault spatial coordinate system for the input image, precede
the other input arguments with two 2-element vectors specifying the XData and
YData:
[...] = imcrop(x,y,...)
If you supply additional output arguments, imcrop returns information about
the selected rectangle and the coordinate system of the input image:
[A,rect] = imcrop(...)
[x,y,A,rect] = imcrop(...)
A is the output image. x and y are the XData and YData of the input image.
Cla ss Support
The input image A can be of class uint8 or double. The output image B is of the
same class as A. rect is always of class double.
Rema rk s
Because rect is specified in terms of spatial coordinates, the width and height
elements of rect do not always correspond exactly with the size of the output
image. For example, suppose rect is [20 20 40 30], using the default spatial
coordinate system. The upper-left corner of the specified rectangle is the center
of the pixel (20,20) and the lower-right corner is the center of the pixel (50,60).
The resulting output image is 31-by-41, not 30-by-40, because the output image
includes all pixels in the input image that are completely or partially enclosed
by the rectangle.
11-106
www.MatlabSite.com
im crop
Ex a mple
See Also
I = imread('ic.tif');
I2 = imcrop(I,[60 40 100 90]);
imshow(I)
figure, imshow(I2)
zoom
www.MatlabSite.com
11-107
imfea ture
Purpose
11imfeature
Compute feature measurements for image regions
Synta x
stats = imfeature(L,measurements)
stats = imfeature(L,measurements,n)
Description
stats = imfeature(L,measurements) computes a set of measurements for
each labeled region in the label matrix L. Positive integer elements of L
correspond to different regions. For example, the set of elements of L equal to
1 corresponds to region 1; the set of elements of L equal to 2 corresponds to
region 2; and so on. stats is a structure array of length max(L(:)). The fields
of the structure array denote different measurements for each region, as
specified by measurements.
measurements can be a comma-separated list of strings, a cell array containing
strings, the single string 'all', or the single string 'basic'. The set of valid
measurement strings includes:
'Area'
'Image'
'EulerNumber'
'Centroid'
'FilledImage'
'Extrema'
'BoundingBox'
'FilledArea'
'EquivDiameter'
'MajorAxisLength'
'ConvexHull'
'Solidity'
'MinorAxisLength'
'ConvexImage'
'Extent'
'Eccentricity'
'ConvexArea'
'PixelList'
'Orientation'
Measurement strings are case insensitive and can be abbreviated.
If measurements is the string 'all', then all of the above measurements are
computed. If measurements is not specified or if it is the string 'basic', then
these measurements are computed: 'Area', 'Centroid', and 'BoundingBox'.
stats = imfeature(L,measurements,n) specifies the type of connectivity used
in computing the 'FilledImage', 'FilledArea', and 'EulerNumber'
measurements. n can have a value of either 4 or 8, where 4 specifies
4-connected objects and 8 specifies 8-connected objects; if the argument is
omitted, it defaults to 8.
11-108
www.MatlabSite.com
im fea ture
Definitions
'Area' – Scalar; the actual number of pixels in the region. (This value may
differ slightly from the value returned by bwarea, which weights different
patterns of pixels differently.)
'Centroid' – 1-by-2 vector; the x- and y-coordinates of the center of mass of the
region.
'BoundingBox' – 1-by-4 vector; the smallest rectangle that can contain the
region. The format of the vector is [x y width height], where x and y are the
x- and y-coordinates of the upper-left corner of the rectangle, and width and
height are the width and height of the rectangle. Note that x and y are always
noninteger values, because they are the spatial coordinates for the upper-left
corner of a pixel in the image; for example, if this pixel is the third pixel in the
fifth row of the image, then x = 2.5 and y = 4.5.
This figure illustrates the centroid and bounding box. The region consists of the
white pixels; the green box is the bounding box, and the red dot is the centroid:
'MajorAxisLength' – Scalar; the length (in pixels) of the major axis of the
ellipse that has the same second-moments as the region.
'MinorAxisLength' – Scalar; the length (in pixels) of the minor axis of the
ellipse that has the same second-moments as the region.
'Eccentricity' – Scalar; the eccentricity of the ellipse that has the same
second-moments as the region. The eccentricity is the ratio of the distance
between the foci of the ellipse and its major axis length. The value is between
0 and 1. (0 and 1 are degenerate cases; an ellipse whose eccentricity is 0 is
actually a circle, while an ellipse whose eccentricity is 1 is a line segment.)
'Orientation' – Scalar; the angle (in degrees) between the x-axis and the
major axis of the ellipse that has the same second-moments as the region.
This figure illustrates the axes and orientation of the ellipse. The left side of
the figure shows an image region and its corresponding ellipse. The right side
www.MatlabSite.com
11-109
imfea ture
shows the same ellipse, with features indicated graphically; the solid blue lines
are the axes, the red dots are the foci, and the orientation is the angle between
the horizontal dotted line and the major axis:
'Image' – Binary image (uint8) of the same size as the bounding box of the
region; the on pixels correspond to the region, and all other pixels are off.
'FilledImage' – Binary image (uint8) of the same size as the bounding box of
the region; the on pixels correspond to the region, with all holes filled in.
'FilledArea' – Scalar; the number of on pixels in FilledImage.
This figure illustrates ‘Image' and ‘FilledImage':
Original image, containing a single region
'Image'
'FilledImage'
'ConvexHull' – p-by-2 matrix; the smallest convex polygon that can contain
the region. Each row of the matrix contains the x- and y-coordinates of one
vertex of the polygon.
'ConvexImage' – Binary image (uint8); the convex hull, with all pixels within
the hull filled in (i.e., set to on). (For pixels that the boundary of the hull passes
11-110
www.MatlabSite.com
im fea ture
through, imfeature uses the same logic as roipoly to determine whether the
pixel is inside or outside the hull.) The image is the size of the bounding box of
the region.
'ConvexArea' – Scalar; the number of pixels in 'ConvexImage'.
'EulerNumber' – Scalar; equal to the number of objects in the region minus the
number of holes in those objects.
'Extrema' – 8-by-2 matrix; the extremal points in the region. Each row of the
matrix contains the x- and y-coordinates of one of the points; the format of the
vector is [top-left top-right right-top right-bottom bottom-right
bottom-left left-bottom left-top].
This figure illustrates the extrema of two different regions. In the region on the
left, each extremal point is distinct; in the region on the right, certain extremal
points (e.g., top-left and left-top) are identical:
top-left
top-right
top-left
top-right
left-top
right-top
left-top
right-top
left-bottom
right-bottom
left-bottom
right-bottom
bottom-left
bottom-right
bottom-left
bottom-right
'EquivDiameter' – Scalar; the diameter of a circle with the same area as the
region. Computed as sqrt(4*Area/pi).
'Solidity' – Scalar; the proportion of the pixels in the convex hull that are
also in the region. Computed as Area/ConvexArea.
'Extent' – Scalar; the proportion of the pixels in the bounding box that are
also in the region. Computed as the Area divided by area of the bounding box.
'PixelList' – p-by-2 matrix; the actual pixels in the region. Each row of the
matrix contains the x- and y-coordinates of one pixel in the region.
Cla ss Support
The input label matrix L can be of class uint8 or double.
www.MatlabSite.com
11-111
imfea ture
Rema rk s
The comma-separated list syntax for structure arrays is very useful when
working with the output of imfeature. For example, for a field that contains a
scalar, you can use a this syntax to create a vector containing the value of this
field for each region in the image.
For instance, if stats is a structure array with field Area, then these two
expressions are equivalent:
stats(1).Area, stats(2).Area, ..., stats(end).Area
and:
stats.Area
Therefore, you can use these calls to create a vector containing the area of each
region in the image:
stats = imfeature(L,'Area');
allArea = [stats.Area];
allArea is a vector of the same length as the structure array stats.
The function ismember is useful in conjunction with imfeature for selecting
regions based on certain criteria. For example, these commands create a binary
image containing only the regions in text.tif whose area is greater than 80:
idx = find([stats.Area] > 80);
BW2 = ismember(L,idx);
Most of the measurements take very little time to compute. The exceptions are
these, which may take significantly longer, depending on the number of regions
in L:
•
•
•
•
'ConvexHull'
'ConvexImage'
'ConvexArea'
'FilledImage'
Note that computing certain groups of measurements takes about the same
amount of time as computing just one of them, because imfeature takes
advantage of intermediate computations used in both computations. Therefore,
it is fastest to compute all of the desired measurements in a single call to
imfeature.
11-112
www.MatlabSite.com
im fea ture
Ex a mple
BW = imread('text.tif');
L = bwlabel(BW);
stats = imfeature(L,'all');
stats(23)
ans =
Area:
Centroid:
BoundingBox:
MajorAxisLength:
MinorAxisLength:
Eccentricity:
Orientation:
ConvexHull:
ConvexImage:
ConvexArea:
Image:
FilledImage:
FilledArea:
EulerNumber:
Extrema:
EquivDiameter:
Solidity:
Extent:
PixelList:
See Also
89
[95.6742 192.9775]
[87.5000 184.5000 16 15]
19.9127
14.2953
0.6961
9.0845
[28x2 double]
[15x16 uint8 ]
205
[15x16 uint8 ]
[15x16 uint8 ]
122
0
[ 8x2 double]
10.6451
0.4341
0.3708
[89x2 double]
bwlabel
ismember in the online MATLAB Function Reference
www.MatlabSite.com
11-113
imfinfo
Purpose
11imfinfo
Return information about a graphics file
Synta x
info = imfinfo(filename,fmt)
info = imfinfo(filename)
Description
info = imfinfo(filename,fmt) returns a structure whose fields contain
information about an image in a graphics file. filename is a string that
specifies the name of the graphics file, and fmt is a string that specifies the
format of the file. The file must be in the current directory or in a directory on
the MATLAB path. If imfinfo cannot find a file named filename, it looks for a
file named filename.fmt.
This table lists the possible values for fmt:
Form a t
File type
'bmp'
Windows Bitmap (BMP)
'hdf'
Hierarchical Data Format (HDF)
'jpg' or 'jpeg'
Joint Photographic Experts Group (JPEG)
'pcx'
Windows Paintbrush (PCX)
'tif' or 'tiff'
Tagged Image File Format (TIFF)
'xwd'
X Windows Dump (XWD)
If filename is a TIFF or HDF file containing more than one image, info is a
structure array with one element (i.e., an individual structure) for each image
in the file. For example, info(3) would contain information about the third
image in the file.
11-114
www.MatlabSite.com
im finfo
The set of fields in info depends on the individual file and its format. However,
the first nine fields are always the same. This table lists these fields and
describes their values:
Field
Va lue
Filename
A string containing the name of the file; if the file is
not in the current directory, the string contains the
full pathname of the file
FileModDate
A string containing the date when the file was last
modified
FileSize
An integer indicating the size of the file in bytes
Format
A string containing the file format, as specified by fmt;
for JPEG and TIFF files, the three-letter variant is
returned
FormatVersion
A string or number describing the version of the
format
Width
An integer indicating the width of the image in pixels
Height
An integer indicating the height of the image in pixels
BitDepth
An integer indicating the number of bits per pixel
ColorType
A string indicating the type of image; either
'truecolor' for a truecolor RGB image, 'grayscale'
for a grayscale intensity image, or 'indexed' for an
indexed image
info = imfinfo(filename) attempts to infer the format of the file from its
contents.
Rema rk s
imfinfo is a function in MATLAB.
www.MatlabSite.com
11-115
imfinfo
Ex a mple
info = imfinfo('canoe.tif')
info =
Filename:
FileModDate:
FileSize:
Format:
FormatVersion:
Width:
Height:
BitDepth:
ColorType:
FormatSignature:
ByteOrder:
NewSubfileType:
BitsPerSample:
Compression:
PhotometricInterpretation:
StripOffsets:
SamplesPerPixel:
RowsPerStrip:
StripByteCounts:
XResolution:
YResolution:
ResolutionUnit:
Colormap:
PlanarConfiguration:
TileWidth:
TileLength:
TileOffsets:
TileByteCounts:
Orientation:
FillOrder:
GrayResponseUnit:
MaxSampleValue:
MinSampleValue:
Thresholding:
See Also
11-116
'canoe.tif'
'25-Oct-1996 22:10:39'
69708
'tif'
[]
346
207
8
'indexed'
[73 73 42 0]
'little-endian'
0
8
'PackBits'
'RGB Palette'
[ 9x1 double]
1
23
[ 9x1 double]
72
72
'Inch'
[256x3 double]
'Chunky'
[]
[]
[]
[]
1
1
0.0100
255
0
1
imread, imwrite
www.MatlabSite.com
im hist
Purpose
11imhist
Display a histogram of image data
Synta x
imhist(I,n)
imhist(X,map)
[counts,x] = imhist(...)
Description
imhist(I,n) displays a histogram with n bins for the intensity image I above
a grayscale colorbar of length n. If you omit the argument, imhist uses a
default value of n = 256 if I is a grayscale image, or n = 2 if I is a binary image.
imhist(X,map) displays a histogram for the indexed image X. This histogram
shows the distribution of pixel values above a colorbar of the colormap map. The
colormap must be at least as long as the largest index in X. The histogram has
one bin for each entry in the colormap.
[counts,x] = imhist(...) returns the histogram counts in counts and the
bin locations in x so that stem(x,counts) shows the histogram. For indexed
images, it returns the histogram counts for each colormap entry; the length of
counts is the same as the length of the colormap.
Cla ss Support
Ex a mple
See Also
The input image can be of class uint8 or double.
I = imread('pout.tif');
imhist(I)
histeq
hist in the online MATLAB Function Reference
www.MatlabSite.com
11-117
immovie
Purpose
11immovie
Make a movie of a multiframe indexed image
Synta x
mov = immovie(X,map)
Description
mov = immovie(X,map) returns the movie matrix mov from the images in the
multiframe indexed image X. As it creates the movie matrix, it displays the
movie frames on the screen. You can play the movie using the MATLAB movie
function.
X comprises multiple indexed images, all having the same size and all using the
colormap map. X is an m-by-n-by-1-by-k array, where k is the number of images.
Cla ss Support
Ex a mple
See Also
X can be of class uint8 or double. mov is of class double.
load mri
mov = immovie(D,map);
montage
getframe, movie in the online MATLAB Function Reference
11-118
www.MatlabSite.com
im noise
Purpose
11imnoise
Add noise to an image
Synta x
J = imnoise(I,type)
J = imnoise(I,type,parameters)
Description
J = imnoise(I,type) adds noise of type type to the intensity image I. type is
a string that can have one of these values:
• 'gaussian' for Gaussian white noise
• 'salt & pepper' for “on and off” pixels
• 'speckle' for multiplicative noise
The parameters you supply depend on the type of noise. If you omit these
arguments, imnoise uses default values for the parameters.
J = imnoise(I,'gaussian',m,v) adds Gaussian white noise of mean m and
variance v to the image I. The default is zero mean noise with 0.01 variance.
J = imnoise(I,'salt & pepper',d) adds salt and pepper noise to the image
I, where d is the noise density. This affects approximately d*prod(size(I))
pixels. The default is 0.05 noise density.
J = imnoise(I,'speckle',v) adds multiplicative noise to the image I, using
the equation J = I + n*I, where n is uniformly distributed random noise with
mean 0 and variance v. The default for v is 0.04.
Cla ss Support
The input image I can be of class uint8 or double. The output image J is of the
same class as I.
www.MatlabSite.com
11-119
imnoise
Ex a mple
See Also
11-120
I = imread('eight.tif');
J = imnoise(I,'salt & pepper',0.02);
imshow(I)
figure, imshow(J)
rand, randn in the online MATLAB Function Reference
www.MatlabSite.com
im pix el
Purpose
Synta x
11impixel
Determine pixel color values
P = impixel(I)
P = impixel(X,map)
P = impixel(RGB)
P = impixel(I,c,r)
P = impixel(X,map,c,r)
P = impixel(RGB,c,r)
[c,r,P] = impixel(...)
P = impixel(x,y,I,xi,yi)
P = impixel(x,y,X,map,xi,yi)
P = impixel(x,y,RGB,xi,yi)
[xi,yi,P] = impixel(x,y,...)
Description
impixel returns the red, green, and blue color values of specified image pixels.
In the syntaxes below, impixel displays the input image and waits for you to
specify the pixels with the mouse:
P = impixel(I)
P = impixel(X,map)
P = impixel(RGB)
If you omit the input arguments, impixel operates on the image in the current
axes.
Use normal button clicks to select pixels. Press Backspace or Delete to
remove the previously selected pixel. A shift-click, right-click, or double-click
adds a final pixel and ends the selection; pressing Return finishes the
selection without adding a pixel.
When you finish selecting pixels, impixel returns an m-by-3 matrix of RGB
values in the supplied output argument. If you do not supply an output
argument, impixel returns the matrix in ans.
You can also specify the pixels noninteractively, using these syntaxes:
P = impixel(I,c,r)
P = impixel(X,map,c,r)
P = impixel(RGB,c,r)
www.MatlabSite.com
11-121
impix el
r and c are equal-length vectors specifying the coordinates of the pixels whose
RGB values are returned in P. The k-th row of P contains the RGB values for
the pixel (r(k),c(k)).
If you supply three output arguments, impixel returns the coordinates of the
selected pixels:
[c,r,P] = impixel(...)
To specify a nondefault spatial coordinate system for the input image, use
these syntaxes:
P = impixel(x,y,I,xi,yi)
P = impixel(x,y,X,map,xi,yi)
P = impixel(x,y,RGB,xi,yi)
x and y are 2-element vectors specifying the image XData and YData. xi and yi
are equal-length vectors specifying the spatial coordinates of the pixels whose
RGB values are returned in P. If you supply three output arguments, impixel
returns the coordinates of the selected pixels:
[xi,yi,P] = impixel(x,y,...)
Cla ss Support
Ex a mple
The input image can be of class uint8 or double. All other inputs and outputs
are of class double.
RGB = imread('flowers.tif');
c = [12 146 410];
r = [104 156 129];
pixels = impixel(RGB,c,r)
pixels =
61
253
237
See Also
11-122
59
240
37
101
0
44
improfile, pixval
www.MatlabSite.com
im profile
Purpose
Synta x
11improfile
Compute pixel-value cross-sections along line segments
c = improfile
c = improfile(n)
c = improfile(I,xi,yi)
c = improfile(I,xi,yi,n)
[cx,cy,c] = improfile(...)
[cx,cy,c,xi,yi] = improfile(...)
[...] = improfile(x,y,I,xi,yi)
[...] = improfile(x,y,I,xi,yi,n)
[...] = improfile(...,method)
Description
improfile computes the intensity values along a line or a multiline path in an
image. improfile selects equally spaced points along the path you specify, and
then uses interpolation to find the intensity value for each point. improfile
works with grayscale intensity images and RGB images.
If you call improfile with one of these syntaxes, it operates interactively on
the image in the current axes:
c = improfile
c = improfile(n)
n specifies the number of points to compute the intensity value for. If you do not
provide this argument, improfile chooses a value for n, roughly equal to the
number of pixels the path traverses.
You specify the line or path using the mouse, by clicking on points in the image.
Press Backspace or Delete to remove the previously selected point. A
shift-click, right-click, or double-click adds a final point and ends the selection;
pressing Return finishes the selection without adding a point. When you
finish selecting points, improfile returns the interpolated data values in c. c
is an n-by-1 vector if the input is a grayscale intensity image, or an n-by-1-by-3
array if the input is an RGB image.
www.MatlabSite.com
11-123
improfile
If you omit the output argument, improfile displays a plot of the computed
intensity values. If the specified path consists of a single line segment,
improfile creates a two-dimensional plot of intensity values versus the
distance along the line segment; if the path consists of two or more line
segments, improfile creates a three-dimensional plot of the intensity values
versus their x- and y-coordinates.
You can also specify the path noninteractively, using these syntaxes:
c = improfile(I,xi,yi)
c = improfile(I,xi,yi,n)
xi and yi are equal-length vectors specifying the spatial coordinates of the
endpoints of the line segments.
You can use these syntaxes to return additional information:
[cx,cy,c] = improfile(...)
[cx,cy,c,xi,yi] = improfile(...)
cx and cy are vectors of length n, containing the spatial coordinates of the
points at which the intensity values are computed.
To specify a nondefault spatial coordinate system for the input image, use
these syntaxes:
[...] = improfile(x,y,I,xi,yi)
[...] = improfile(x,y,I,xi,yi,n)
x and y are 2-element vectors specifying the image XData and YData.
[...] = improfile(...,method) uses the specified interpolation method.
method is a string that can have one of these values:
• 'nearest' (default) uses nearest neighbor interpolation.
• 'bilinear' uses bilinear interpolation.
• 'bicubic' uses bicubic interpolation.
If you omit the method argument, improfile uses the default method of
'nearest'.
Cla ss Support
11-124
The input image can be of class uint8 or double. All other inputs and outputs
are of class double.
www.MatlabSite.com
im profile
Ex a mple
See Also
I = imread('alumgrns.tif');
x = [35 338 346 103];
y = [253 250 17 148];
improfile(I,x,y), grid on
impixel, pixval
interp2 in the online MATLAB Function Reference
www.MatlabSite.com
11-125
imrea d
Purpose
11imread
Read images from graphics files
Synta x
A = imread(filename,fmt)
[X,map] = imread(filename,fmt)
[...] = imread(filename)
[...] = imread(...,idx)
(TIFF only)
[...] = imread(...,ref)
(HDF only)
Description
A = imread(filename,fmt) reads the image in filename into A, whose class is
uint8. If the file contains a grayscale intensity image, A is a two-dimensional
array. If the file contains a truecolor (RGB) image, A is a three-dimensional
(m-by-n-by-3) array. filename is a string that specifies the name of the graphics
file, and fmt is a string that specifies the format of the file. The file must be in
the current directory or in a directory in the MATLAB path, or you can specify
the full pathname for a file located anywhere on your system. If imread cannot
find a file named filename, it looks for a file named filename.fmt.
This table lists the possible values for fmt:
Form a t
File type
'bmp'
Windows Bitmap (BMP)
'hdf'
Hierarchical Data Format (HDF)
'jpg' or 'jpeg'
Joint Photographic Experts Group (JPEG)
'pcx'
Windows Paintbrush (PCX)
'tif' or 'tiff'
Tagged Image File Format (TIFF)
'xwd'
X Windows Dump (XWD)
[X,map] = imread(filename,fmt) reads the indexed image in filename into
X and its associated colormap into map. X is of class uint8, and map is of class
double. The colormap values are rescaled to the range [0,1].
[...] = imread(filename) attempts to infer the format of the file from its
content.
11-126
www.MatlabSite.com
im rea d
[...] = imread(...,idx) reads in one image from a multi-image TIFF file.
idx is an integer value that specifies the order in which the image appears in
the file. For example, if idx is 3, imread reads the third image in the file. If you
omit this argument, imread reads the first image in the file.
[...] = imread(...,ref) reads in one image from a multi-image HDF file.
ref is an integer value that specifies the reference number used to identify the
image. For example, if ref is 12, imread reads the image whose reference
number is 12. (Note that in an HDF file the reference numbers do not
necessarily correspond to the order of the images in the file.) If you omit this
argument, imread reads the first image in the file.
This table summarizes the types of images that imread can read:
Forma t
Va ria nts
BMP
1-bit, 4-bit, 8-bit, and 24-bit uncompressed images; 4-bit
and 8-bit run-length encoded (RLE) images
HDF
8-bit raster image datasets, with or without associated
colormap; 24-bit raster image datasets
JPEG
Any baseline JPEG image; JPEG images with some
commonly used extensions
PCX
1-bit, 8-bit, and 24-bit images
TIFF
Any baseline TIFF image, including 1-bit, 8-bit, and 24-bit
uncompressed images; 1-bit, 8-bit, and 24-bit images with
packbit compression; 1-bit images with CCITT compression
XWD
1-bit and 8-bit ZPixmaps; XYBitmaps; 1-bit XYPixmaps
Rema rk s
imread is a function in MATLAB.
Ex a mples
This example reads the sixth image in a TIFF file:
[X,map] = imread('flowers.tif',6);
www.MatlabSite.com
11-127
imrea d
This example reads the fourth image in an HDF file:
info = imfinfo('skull.hdf');
[X,map] = imread('skull.hdf',info(4).Reference);
See Also
imfinfo, imwrite
fread in the online MATLAB Function Reference
11-128
www.MatlabSite.com
im resize
Purpose
Synta x
11imresize
Resize an image
B = imresize(A,m,method)
B = imresize(A,[mrows ncols],method)
B = imresize(...,method,n)
B = imresize(...,method,h)
Description
imresize resizes an image of any type using the specified interpolation
method. method is a string that can have one of these values:
• 'nearest' (default) uses nearest neighbor interpolation.
• 'bilinear' uses bilinear interpolation.
• 'bicubic' uses bicubic interpolation.
If you omit the method argument, imresize uses the default method of
'nearest'.
B = imresize(A,m,method) returns an image that is m times the size of A. If m
is between 0 and 1.0, B is smaller than A. If m is greater than 1.0, B is larger than
A.
B = imresize(A,[mrows ncols],method) returns an image of size
[mrows ncols]. If the specified size does not produce the same aspect ratio
as the input image has, the output image is distorted.
When the specified output size is smaller than the size of the input image, and
method is 'bilinear' or 'bicubic', imresize applies a lowpass filter before
interpolation to reduce aliasing. The default filter size is 11-by-11.
You can specify a different order for the default filter using:
[...] = imresize(...,method,n)
n is an integer scalar specifying the size of the filter, which is n-by-n. If n is 0
(zero), imresize omits the filtering step.
You can also specify your own filter h using:
[...] = imresize(...,method,h)
h is any two-dimensional FIR filter (such as those returned by ftrans2, fwind1,
fwind2, or fsamp2).
www.MatlabSite.com
11-129
imresize
Cla ss Support
The input image can be of class uint8 or double. The output image is of the
same class as the input image.
See Also
interp2 in the online MATLAB Function Reference
11-130
www.MatlabSite.com
im rota te
Purpose
11imrotate
Rotate an image
Synta x
B = imrotate(A,angle,method)
B = imrotate(A,angle,method,'crop')
Description
B = imrotate(A,angle,method) rotates the image A by angle degrees in a
counter-clockwise direction, using the specified interpolation method. method
is a string that can have one of these values:
• 'nearest' (default) uses nearest neighbor interpolation.
• 'bilinear' uses bilinear interpolation.
• 'bicubic' uses bicubic interpolation.
If you omit the method argument, imrotate uses the default method of
'nearest'.
The returned image matrix B is, in general, larger than A to include the whole
rotated image. imrotate sets invalid values on the periphery of B to 0.
B = imrotate(A,angle,method,'crop') rotates the image A through angle
degrees and returns the central portion which is the same size as A.
Cla ss Support
The input image can be of class uint8 or double. The output image is of the
same class as the input image.
Rema rk s
To rotate the image clockwise, specify a negative angle.
www.MatlabSite.com
11-131
imrota te
Ex a mple
See Also
11-132
I = imread('ic.tif');
J = imrotate(I,–4,'bilinear','crop');
imshow(I)
figure, imshow(J)
imcrop, imresize
www.MatlabSite.com
im show
Purpose
Synta x
11imshow
Display an image
imshow(I,n)
imshow(I,[low high])
imshow(BW)
imshow(X,map)
imshow(RGB)
imshow(...,display_option)
imshow(x,y,A,...)
imshow filename
h = imshow(...)
Description
imshow(I,n) displays the intensity image I with n discrete levels of gray. If you
omit n, imshow uses 256 gray levels on 24-bit displays, or 64 gray levels on other
systems.
imshow(I,[low high]) displays I as a grayscale intensity image, specifying
the data range for I. The value low (and any value less than low) displays as
black, the value high (and any value greater than high) displays as white, and
values in between display as intermediate shades of gray. imshow uses the
default number of gray levels. If you use an empty matrix ([]) for [low high],
imshow uses [min(I(:)) max(I(:))]; the minimum value in I displays as
black, and the maximum value displays as white.
imshow(BW) displays the binary image BW. Values of 0 display as black, and
values of 1 display as white.
imshow(X,map) displays the indexed image X with the colormap map.
imshow(RGB) displays the truecolor image RGB.
imshow(...,display_option) displays the image, calling truesize if
display_option is 'truesize', or suppressing the call to truesize if
display_option is 'notruesize'. Either option string can be abbreviated. If
you do not supply this argument, imshow determines whether to call truesize
based on the setting of the 'ImshowTruesize' preference.
imshow(x,y,A,...) uses the 2-element vectors x and y to establish a
nondefault spatial coordinate system, by specifying the image XData and
YData.
www.MatlabSite.com
11-133
imshow
imshow filename displays the image stored in the graphics file filename.
imshow calls imread to read the image from the file, but the image data is not
stored in the MATLAB workspace. The file must be in the current directory or
on the MATLAB path.
h = imshow(...) returns the handle to the image object created by imshow.
Cla ss Support
The input image can be of class uint8 or double.
Rema rk s
You can use the iptsetpref function to set several toolbox preferences that
modify the behavior of imshow:
• 'ImshowBorder' controls whether imshow displays the image with a border
around it.
• 'ImshowAxesVisible' controls whether imshow displays the image with the
axes box and tick labels.
• 'ImshowTruesize' controls whether imshow calls the truesize function.
Note that the display_option argument to imshow enables you to override the
'ImshowTruesize' preference.
For more information about these preferences, see the reference entry for
iptsetpref.
See Also
getimage, imread, iptgetpref, iptsetpref, subimage, truesize, warp
image, imagesc in the online MATLAB Function Reference
11-134
www.MatlabSite.com
im w rite
Purpose
11imwrite
Write an image to a graphics file
Synta x
imwrite(A,filename,fmt)
imwrite(X,map,filename,fmt)
imwrite(...,filename)
imwrite(...,Parameter,Value,...)
Description
imwrite(A,filename,fmt) writes the image in A to filename. filename is a
string that specifies the name of the output file, and fmt is a string that
specifies the format of the file. If A is a grayscale intensity image or a truecolor
(RGB) image of class uint8, imwrite writes the actual values in the array to
the file. If A is of class double, imwrite rescales the values in the array before
writing, using uint8(round(255*A)). This operation converts the
floating-point numbers in the range [0,1] to 8-bit integers in the range [0,255].
This table lists the possible values for fmt:
Form a t
File type
'bmp'
Windows Bitmap (BMP)
'hdf'
Hierarchical Data Format (HDF)
'jpg' or 'jpeg'
Joint Photographers Expert Group (JPEG)
'pcx'
Windows Paintbrush (PCX)
'tif' or 'tiff'
Tagged Image File Format (TIFF)
'xwd'
X Windows Dump (XWD)
imwrite(X,map,filename,fmt) writes the indexed image in X, and its
associated colormap map, to filename. If X is of class uint8, imwrite writes the
actual values in the array to the file. If X is of class double, imwrite offsets the
values in the array before writing, using uint8(X–1). map must be of class
double; imwrite rescales the values in map using uint8(round(255*map)).
imwrite(...,filename) writes the image to filename, inferring the format to
use from the filename’s extension. The extension must be one of the legal
values for fmt.
www.MatlabSite.com
11-135
imw rite
imwrite(...,Parameter,Value,...) specifies parameters that control
various characteristics of the output file. Parameters are currently supported
for HDF, JPEG, and TIFF files.
This table describes the available parameters for HDF files:
Pa ra m eter
Va lues
Defa ult
'Compression'
One of these strings: 'none', 'rle',
'rle'
'jpeg'
'Quality'
A number between 0 and 100;
parameter applies only if
'Compression' is 'jpeg'; higher
numbers mean quality is better (less
image degradation due to
compression), but the resulting file
size is larger
75
'WriteMode'
One of these strings: 'overwrite',
'overwrite'
'append'
This table describes the available parameters for JPEG files:
11-136
Pa ra m eter
Va lues
Defa ult
'Quality'
A number between 0 and 100; higher
numbers mean quality is better (less
image degradation due to
compression), but the resulting file
size is larger
75
www.MatlabSite.com
im w rite
This table describes the available parameters for TIFF files:
Pa ra m eter
Va lues
Defa ult
'Compression'
One of these strings: 'none',
'packbits', 'ccitt'; 'ccitt' is
valid for binary images only
'ccitt' for
binary images;
'packbits' for all
other images
'Description'
Any string; fills in the
ImageDescription field returned
by imfinfo
empty
'Resolution'
A scalar value that is used for the
XResolution and YResolution tags
in the output file
72
This table summarizes the types of images that imwrite can write:
Forma t
Va ria nts
BMP
8-bit uncompressed images with associated colormap; 24-bit
uncompressed images
HDF
8-bit raster image datasets, with or without associated
colormap; 24-bit raster image datasets
JPEG
Baseline JPEG images1
PCX
8-bit images
TIFF
Baseline TIFF images, including 1-bit, 8-bit, and 24-bit
uncompressed images; 1-bit, 8-bit, and 24-bit images with
packbit compression; 1-bit images with CCITT compression
XWD
8-bit ZPixmaps
1. Indexed images are converted to RGB before writing out JPEG files, because the
JPEG format does not support indexed images.
www.MatlabSite.com
11-137
imw rite
Rema rk s
Ex a mple
See Also
imwrite is a function in MATLAB.
imwrite(X,map,'flowers.hdf','Compression','none',...
'WriteMode','append')
imfinfo, imread
fwrite in the online MATLAB Function Reference
11-138
www.MatlabSite.com
ind2 gra y
Purpose
11ind2gray
Convert an indexed image to an intensity image
Synta x
I = ind2gray(X,map)
Description
I = ind2gray(X,map) converts the image X with colormap map to an intensity
image I. ind2gray removes the hue and saturation information from the input
image while retaining the luminance.
Cla ss Support
X can be of class uint8 or double. I is of class double.
Ex a mple
Algorithm
load trees
I = ind2gray(X,map);
imshow(X,map)
figure,imshow(I)
ind2gray converts the colormap to NTSC coordinates using rgb2ntsc, and sets
the hue and saturation components (I and Q) to zero, creating a gray colormap.
ind2gray then replaces the indices in the image X with the corresponding
grayscale intensity values in the gray colormap.
See Also
gray2ind, imshow, rgb2ntsc
www.MatlabSite.com
11-139
ind2 rgb
Purpose
11ind2rgb
Convert an indexed image to an RGB image
Synta x
RGB = ind2rgb(X,map)
Description
RGB = ind2rgb(X,map) converts the matrix X and corresponding colormap map
to RGB (truecolor) format.
Cla ss Support
X can be of class uint8 or double. RGB is an m-by-n-by-3 array of class double.
See Also
ind2gray, rgb2ind
11-140
www.MatlabSite.com
iptgetpref
Purpose
11iptgetpref
Get Image Processing Toolbox preferences
Synta x
value = iptgetpref(prefname)
Description
value = iptgetpref(prefname) returns the value of the Image Processing
Toolbox preference specified by the string prefname. Preference names are case
insensitive and can be abbreviated.
iptgetpref without an input argument displays the current setting of all
Image Processing Toolbox preferences.
Ex a mple
value = iptgetpref('ImshowAxesVisible')
value =
off
See Also
imshow, iptsetpref
www.MatlabSite.com
11-141
iptsetpref
Purpose
11iptsetpref
Set Image Processing Toolbox preferences
Synta x
iptsetpref(prefname,value)
Description
iptsetpref(prefname,value) sets the Image Processing Toolbox preference
specified by the string prefname to value. The setting persists until the end of
the current MATLAB session, or until you change the setting. (To make the
value persist between sessions, put the command in your startup.m file.)
This table describes the available preferences. Note that the preference names
are case insensitive and can be abbreviated:
Preference N a m e
Va lues
'ImshowBorder'
'loose' (default) or 'tight'
If 'ImshowBorder' is 'loose', imshow displays the image with a border
between the image and the edges of the figure window, thus leaving room
for axes labels, titles, etc. If 'ImshowBorder' is 'tight', imshow adjusts the
figure size so that the image entirely fills the figure. (However, there may
still be a border if the image is very small, or if there are other objects
besides the image and its axes in the figure.)
11-142
www.MatlabSite.com
iptsetpref
Preference N a me
Va lues
'ImshowAxesVisible'
'on' or 'off' (default)
If 'ImshowAxesVisible' is 'on', imshow displays the image with the axes
box and tick labels. If 'ImshowAxesVisible' is 'off', imshow displays the
image without the axes box and tick labels.
'ImshowTruesize'
'auto' (default) or 'manual'
If 'ImshowTruesize' is 'manual', imshow does not call truesize. If
'ImshowTruesize' is 'auto', imshow automatically decides whether to call
truesize. (imshow calls truesize if there will be no other objects in the
resulting figure besides the image and its axes.) You can override this
setting for an individual display by specifying the display_option
argument to imshow, or you can call truesize manually after displaying
the image.
'TruesizeWarning'
'on' (default) or 'off'
If 'TruesizeWarning' is 'on', the truesize function displays a warning if
the image is too large to fit on the screen. (The entire image is still
displayed, but at less than true size.) If 'TruesizeWarning' is 'off',
truesize does not display the warning. Note that this preference applies
even when you call truesize indirectly, such as through imshow.
iptsetpref(prefname) displays the valid values for prefname.
Ex a mple
See Also
iptsetpref('ImshowBorder','tight')
imshow, iptgetpref, truesize
axis in the online MATLAB Function Reference
www.MatlabSite.com
11-143
ira don
Purpose
11iradon
Compute inverse Radon transform
Synta x
I = iradon(P,theta)
I = iradon(P,theta,interp,filter,d,n)
Description
I = iradon(P,theta) reconstructs the image I from projection data in the
two-dimensional array P. The columns of P are parallel beam projection data.
iradon assumes that the center of rotation is the center point of the projections,
which is defined as ceil(size(P,1)/2).
theta describes the angles (in degrees) at which the projections were taken. It
can be either a vector containing the angles or a scalar specifying D_theta, the
incremental angle between projections. If theta is a vector, it must contain
angles with equal spacing between them. If theta is a scalar specifying
D_theta, the projections are taken at angles theta = m*D_theta, where
m = 0,1,2,...,size(P,2)–1. If the input is the empty matrix ([]), D_theta
defaults to 180/size(P,2).
I = iradon(P,theta,interp,filter,d,n) specifies parameters to use in the
inverse Radon transform. You can specify any combination of the last four
arguments. iradon uses default values for any of these arguments that you
omit.
interp specifies the type of interpolation to use in the backprojection. The
available options are listed in order of increasing accuracy and computational
complexity:
• 'nearest' – nearest neighbor interpolation
• 'linear' – linear interpolation (default)
• 'spline' – spline interpolation
filter specifies the filter to use for frequency domain filtering. filter is a
string that specifies any of the following standard filters:
• 'Ram-Lak' – The cropped Ram-Lak or ramp filter (default). The frequency
response of this filter is | f |. Because this filter is sensitive to noise in the
projections, one of the filters listed below may be preferable. These filters
11-144
www.MatlabSite.com
ira don
multiply the Ram-Lak filter by a window that de-emphasizes high
frequencies.
• 'Shepp-Logan' – The Shepp-Logan filter multiplies the Ram-Lak filter by a
sinc function.
• 'Cosine' – The cosine filter multiplies the Ram-Lak filter by a cosine
function.
• 'Hamming' – The Hamming filter multiplies the Ram-Lak filter by a
Hamming window.
• 'Hann' – The Hann filter multiplies the Ram-Lak filter by a Hann window.
d is a scalar in the range (0,1] that modifies the filter by rescaling its frequency
axis. The default is 1. If d is less than 1, the filter is compressed to fit into the
frequency range [0,d], in normalized frequencies; all frequencies above d are set
to 0.
n is a scalar that specifies the number of rows and columns in the reconstructed
image. If n is not specified, the size is determined from the length of the
projections:
n = 2*floor(size(P,1)/(2*sqrt(2)))
If you specify n, iradon reconstructs a smaller or larger portion of the image,
but does not change the scaling of the data. If the projections were calculated
with the radon function, the reconstructed image may not be the same size as
the original image.
[I,h] = iradon(...) returns the frequency response of the filter in the vector
h.
Cla ss Support
All input arguments must be of class double. The output arguments are of class
double.
www.MatlabSite.com
11-145
ira don
Ex a mple
P = phantom(128);
R = radon(P,0:179);
I = iradon(R,0:179,'nearest','Hann');
imshow(P)
figure, imshow(I)
Algorithm
iradon uses the filtered backprojection algorithm to perform the inverse Radon
transform. The filter is designed directly in the frequency domain and then
multiplied by the FFT of the projections. The projections are zero-padded to a
power of 2 before filtering to prevent spatial domain aliasing and to speed up
the FFT.
See Also
radon, phantom
References
Kak, Avinash C., and Malcolm Slaney, Principles of Computerized
Tomographic Imaging. New York: IEEE Press.
11-146
www.MatlabSite.com
isbw
Purpose
11isbw
Return true for a binary image
Synta x
flag = isbw(A)
Description
flag = isbw(A) returns 1 if A is a binary image and 0 otherwise.
isbw uses these criteria to decide if A is a binary image:
• If A is of class double, all values must be either 0 or 1, and the number of
dimensions of A must be 2.
• If A is of class uint8, its logical flag must be on, and the number of
dimensions of A must be 2.
Note that a four-dimensional array that contains multiple binary images
returns 0, not 1.
Cla ss Support
A can be of class uint8 or double.
See Also
isind, isgray, isrgb
www.MatlabSite.com
11-147
isgra y
Purpose
11isgray
Return true for intensity image
Synta x
flag = isgray(A)
Description
flag = isgray(A) returns 1 if A is a grayscale intensity image and 0 otherwise.
isgray uses these criteria to decide if A is an intensity image:
• If A is of class double, all values must be in the range [0,1], and the number
of dimensions of A must be 2.
• If A is of class uint8, the number of dimensions of A must be 2.
Note that a four-dimensional array that contains multiple intensity images
returns 0, not 1.
Cla ss Support
A can be of class uint8 or double.
See Also
isbw, isind, isrgb
11-148
www.MatlabSite.com
isind
Purpose
11isind
Return true for an indexed image
Synta x
flag = isind(A)
Description
flag = isind(A) returns 1 if A is an indexed image and 0 otherwise.
isind uses these criteria to determine if A is an indexed image:
• If A is of class double, all values in A must be integers greater than or equal
to 1, and the number of dimensions of A must be 2.
• If A is of class uint8, its logical flag must be off, and the number of
dimensions of A must be 2.
Note that a four-dimensional array that contains multiple indexed images
returns 0, not 1.
Cla ss Support
A can be of class uint8 or double.
See Also
isbw, isgray, isrgb
www.MatlabSite.com
11-149
isrgb
Purpose
11isrgb
Return true for an RGB image
Synta x
flag = isrgb(A)
Description
flag = isrgb(A) returns 1 if A is an RGB truecolor image and 0 otherwise.
isrgb uses these criteria to determine if A is an RGB image:
• If A is of class double, all values must be in the range [0,1], and A must be
m-by-n-by-3.
• If A is of class uint8, A must be m-by-n-by-3.
Note that a four-dimensional array that contains multiple RGB images returns
0, not 1.
Cla ss Support
A can be of class uint8 or double.
See Also
isbw, isgray, isind
11-150
www.MatlabSite.com
m a k elut
Purpose
11makelut
Construct a lookup table for use with applylut
Synta x
lut = makelut(fun,n)
lut = makelut(fun,n,P1,P2,...)
Description
lut = makelut(fun,n) returns a lookup table for use with applylut. fun is
either a string containing the name of a function or an inline function object.
The function should take a 2-by-2 or 3-by-3 matrix of 1’s and 0’s as input and
return a scalar. n is either 2 or 3, indicating the size of the input to fun. makelut
creates lut by passing all possible 2-by-2 or 3-by-3 neighborhoods to fun, one
at a time, and constructing either a 16-element vector (for 2-by-2
neighborhoods) or a 512-element vector (for 3-by-3 neighborhoods). The vector
consists of the output from fun for each possible neighborhood.
lut = makelut(fun,n,P1,P2,...) passes the additional parameters
P1,P2,..., to fun.
Cla ss Support
lut is returned as a vector of class double.
11
www.MatlabSite.com
11-151
ma k elut
Ex a mple
In this example, the function returns 1 (true) if the number of 1’s in the
neighborhood is 2 or greater, and returns 0 (false) otherwise. makelut then uses
the function to construct a lookup table for 2-by-2 neighborhoods.
f = inline('sum(x(:)) >= 2');
lut = makelut(f,2)
lut =
0
0
0
1
0
1
1
1
0
1
1
1
1
1
1
1
See Also
11-152
applylut
www.MatlabSite.com
m a t2 gra y
Purpose
11mat2gray
Convert a matrix to a grayscale intensity image
Synta x
I = mat2gray(A,[amin amax])
I = mat2gray(A)
Description
I = mat2gray(A,[amin amax]) converts the matrix A to the intensity image I.
The returned matrix I contains values in the range 0 (black) to 1.0 (full
intensity or white). amin and amax are the values in A that correspond to 0 and
1.0 in I.
I = mat2gray(A) sets the values of amin and amax to the minimum and
maximum values in A.
Cla ss Support
Ex a mple
See Also
The input array A and the output image I are of class double.
I = imread('rice.tif');
J = filter2(fspecial('sobel'),I);
K = mat2gray(J);
imshow(I)
figure, imshow(K)
gray2ind
www.MatlabSite.com
11-153
mea n2
Purpose
11mean2
Compute the mean of the elements of a matrix
Synta x
b = mean2(A)
Description
b = mean2(A) computes the mean of the values in A.
Cla ss Support
A is an array of class uint8 or double. b is a scalar of class double.
Algorithm
mean2 computes the mean of an array A using mean(A(:)).
See Also
std2
mean, std in the online MATLAB Function Reference
11-154
www.MatlabSite.com
m edfilt2
Purpose
11medfilt2
Perform two-dimensional median filtering
Synta x
B = medfilt2(A,[m n])
B = medfilt2(A)
B = medfilt2(A,'indexed',...)
Description
Median filtering is a nonlinear operation often used in image processing to
reduce “salt and pepper” noise. Median filtering is more effective than
convolution when the goal is to simultaneously reduce noise and preserve
edges.
B = medfilt2(A,[m n]) performs median filtering of the matrix A in two
dimensions. Each output pixel contains the median value in the m-by-n
neighborhood around the corresponding pixel in the input image. medfilt2
pads the image with zeros on the edges, so the median values for the points
within [m n]/2 of the edges may appear distorted.
B = medfilt2(A) performs median filtering of the matrix A using the default
3-by-3 neighborhood.
B = medfilt2(A,'indexed',...) processes A as an indexed image, padding
with zeros if the class of A is uint8, or ones if the class of A is double.
Cla ss Support
The input image A can be of class uint8 or double. The output image B is of the
same class as A.
Rema rk s
If the input image A is of class uint8, all of the output values are returned as
uint8 integers. If the number of pixels in the neighborhood (i.e., m*n) is even,
some of the median values may not be integers. In these cases, the fractional
parts are discarded.
For example, suppose you call medfilt2 using 2-by-2 neighborhoods, and the
input image is a uint8 array that includes this neighborhood:
1 5
4 8
medfilt2 returns an output value of 4 for this neighborhood, although the true
median is 4.5.
www.MatlabSite.com
11-155
medfilt2
Ex a mple
This example adds salt and pepper noise to an image, then restores the image
using medfilt2.
I = imread('eight.tif');
J = imnoise(I,'salt & pepper',0.02);
K = medfilt2(J);
imshow(J)
figure, imshow(K)
Algorithm
medfilt2 uses ordfilt2 to perform the filtering.
See Also
filter2, ordfilt2, wiener2
Reference
Lim, Jae S. Two-Dimensional Signal and Image Processing. Englewood Cliffs,
NJ: Prentice Hall, 1990. pp. 469-476.
11-156
www.MatlabSite.com
m onta ge
Purpose
11montage
Display multiple image frames as a rectangular montage
Synta x
montage(I)
montage(BW)
montage(X,map)
montage(RGB)
h = montage(...)
Description
montage displays all of the frames of a multiframe image array in a single
image object, arranging the frames so that they roughly form a square.
montage(I) displays the k frames of the intensity image array I. I is
m-by-n-by-1-by-k.
montage(BW) displays the k frames of the binary image array BW. BW is
m-by-n-by-1-by-k.
montage(X,map) displays the k frames of the indexed image array X, using the
colormap map for all frames. X is m-by-n-by-1-by-k.
montage(RGB) displays the k frames of the truecolor image array RGB. RGB is
m-by-n-by-3-by-k.
h = montage(...) returns the handle to the image object.
Cla ss Support
The input image can be of class uint8 or double.
www.MatlabSite.com
11-157
monta ge
Ex a mple
See Also
11-158
load mri
montage(D,map)
immovie
www.MatlabSite.com
nlfilter
Purpose
11nlfilter
Perform general sliding-neighborhood operations
Synta x
B = nlfilter(A,[m n],fun)
B = nlfilter(A,[m n],fun,P1,P2,...)
B = nlfilter(A,'indexed',...)
Description
B = nlfilter(A,[m n],fun) applies the function fun to each m-by-n sliding
block of A. fun can be a string containing the name of a function, a string
containing an expression, or an inline function object. fun should accept an
m-by-n block as input, and return a scalar result:
c = fun(x)
c is the output value for the center pixel in the m-by-n block x. nlfilter calls
fun for each pixel in A. nlfilter zero pads the m-by-n block at the edges, if
necessary.
B = nlfilter(A,[m n],fun,P1,P2,...) passes the additional parameters
P1,P2,..., to fun.
B = nlfilter(A,'indexed',...) processes A as an indexed image, padding
with ones if A is of class double and zeros if A is of class uint8.
Cla ss Support
The input image A can be of any class supported by fun. The class of B depends
on the class of the output from fun.
Rema rk s
nlfilter can take a long time to process large images. In some cases, the
colfilt function can perform the same operation much faster.
Ex a mple
This call produces the same result as calling medfilt2 with a 3-by-3
neighborhood:
B = nlfilter(A,[3 3],'median(x(:))');
See Also
blkproc, colfilt
www.MatlabSite.com
11-159
ntsc2 rgb
Purpose
11ntsc2rgb
Convert NTSC values to RGB color space
Synta x
rgbmap = ntsc2rgb(yiqmap)
RGB = ntsc2rgb(YIQ)
Description
rgbmap = ntsc2rgb(yiqmap) converts the m-by-3 NTSC (television) color
values in yiqmap to RGB color space. If yiqmap is m-by-3 and contains the NTSC
luminance (Y) and chrominance (I and Q) color components as columns, then
rgbmap is an m-by-3 matrix that contains the red, green, and blue values
equivalent to those colors. Both rgbmap and yiqmap contain intensities in the
range 0 to 1.0. The intensity 0 corresponds to the absence of the component,
while the intensity 1.0 corresponds to full saturation of the component.
RGB = ntsc2rgb(YIQ) converts the NTSC image YIQ to the equivalent truecolor
image RGB.
ntsc2rgb computes the RGB values from the NTSC components using:
R
1.000
G = 1.000
B
1.000
0.956
– 0.272
– 1.106
0.621 Y
– 0.647 I
1.703 Q
Cla ss Support
The input image or colormap must be of class double. The output is of class
double.
See Also
rgb2ntsc, rgb2ind, ind2rgb, ind2gray
11-160
www.MatlabSite.com
ordfilt2
Purpose
11ordfilt2
Perform two-dimensional order-statistic filtering
Synta x
Y = ordfilt2(X,order,domain)
Y = ordfilt2(X,order,domain,S)
Description
Y = ordfilt2(X,order,domain) replaces each element in X by the order-th
element in the sorted set of neighbors specified by the nonzero elements in
domain.
Y = ordfilt2(X,order,domain,S), where S is the same size as domain, uses
the values of S corresponding to the nonzero values of domain as additive
offsets.
Cla ss Support
The class of X may be double or uint8. The class of Y is the same as the class
of X, unless the additive offset form of ordfilt2 is used, in which case the class
of Y is double.
Rema rk s
domain is equivalent to the structuring element used for binary image
operations. It is a matrix containing only 1’s and 0’s; the 1’s define the
neighborhood for the filtering operation.
For example, Y = ordfilt2(X,5,ones(3,3)) implements a 3-by-3 median
filter; Y = ordfilt2(X,1,ones(3,3)) implements a 3-by-3 minimum filter;
and Y = ordfilt2(X,9,ones(3,3)) implements a 3-by-3 maximum filter.
Y = ordfilt2(X,1,[0 1 0; 1 0 1; 0 1 0]) replaces each element in X by the
minimum of its north, east, south, and west neighbors.
The syntax that includes S (the matrix of additive offsets) can be used to
implement grayscale morphological operations, including grayscale dilation
and erosion.
See Also
medfilt2
Reference
Haralick, Robert M., and Linda G. Shapiro. Computer and Robot Vision,
Volume I. Addison-Wesley, 1992.
www.MatlabSite.com
11-161
pha ntom
Purpose
11phantom
Generate a head phantom image
Synta x
P = phantom(def,n)
P = phantom(E,n)
[p,E] = phantom(...)
Description
P = phantom(def,n) generates an image of a head phantom that can be used
to test the numerical accuracy of radon and iradon or other two-dimensional
reconstruction algorithms. P is a grayscale intensity image that consists of one
large ellipse (representing the brain) containing several smaller ellipses
(representing features in the brain).
def is a string that specifies the type of head phantom to generate. Valid values
are:
• 'Shepp-Logan' – a test image used widely by researchers in tomography.
• 'Modified Shepp-Logan' (default) – a variant of the Shepp-Logan phantom
in which the contrast is improved for better visual perception.
n is a scalar that specifies the number of rows and columns in P. If you omit the
argument, n defaults to 256.
P = phantom(E,n) generates a user-defined phantom, where each row of the
matrix E specifies an ellipse in the image. E has 6 columns, with each column
11-162
www.MatlabSite.com
pha ntom
containing a different parameter for the ellipses. This table describes the
columns of the matrix:
Colum n
Pa ra meter
M ea ning
Column 1
A
Additive intensity value of the
ellipse
Column 2
a
Length of the horizontal semi-axis of
the ellipse
Column 3
b
Length of the vertical semi-axis of
the ellipse
Column 4
x0
x-coordinate of the center of the
ellipse
Column 5
y0
y-coordinate of the center of the
ellipse
Column 6
phi
Angle (in degrees) between the
horizontal semi-axis of the ellipse
and the x-axis of the image
For purposes of generating the phantom, the domains for the x- and y-axes
span [–1,1]. Columns 2 through 5 must be specified in terms of this range.
[P,E] = phantom(...) returns the matrix E used to generate the phantom.
Cla ss Support
All inputs must be of class double. All outputs are of class double.
Rema rk s
For any given pixel in the output image, the pixel’s value is equal to the sum of
the additive intensity values of all ellipses that the pixel is a part of. If a pixel
is not part of any ellipse, its value is 0.
The additive intensity value A for an ellipse can be positive or negative; if it is
negative, the ellipse will be darker than the surrounding pixels. Note that,
depending on the values of A, some pixels may have values outside the range
[0,1].
www.MatlabSite.com
11-163
pha ntom
Ex a mple
P = phantom('Modified Shepp-Logan',200);
imshow(P)
References
Jain, Anil K. Fundamentals of Digital Image Processing. Englewood Cliffs, NJ:
Prentice Hall, 1989. p. 439.
See Also
radon, iradon
11-164
www.MatlabSite.com
pix va l
Purpose
11pixval
Display information about image pixels
Synta x
pixval on
pixval off
pixval
pixval(fig,option)
Purpose
pixval on turns on interactive display of information about image pixels in the
current figure. pixval installs a black bar at the bottom of the figure, which
displays the row-column coordinates for whatever pixel the cursor is currently
over, and the color information for that pixel. If the image is binary or
intensity, the color information is a single intensity value. If the image is
indexed or RGB, the color information is an RGB triplet. The values displayed
are the actual data values, regardless of the class of the image array, or
whether the data is in normal image range.
If you click on the image and hold down the mouse button while you move the
cursor, pixval also displays the Euclidean distance between the point you
clicked on and the current cursor location. pixval draws a line between these
points to indicate the distance being measured. When you release the mouse
button, the line and the distance display disappear.
You can move the display bar by clicking on it and dragging it to another place
in the figure.
pixval off turns interactive display off in the current figure. You can also turn
off the display by clicking the button on the right side of the display bar.
pixval toggles interactive display on or off in the current figure.
pixval(fig,option) applies the pixval command to the figure specified by
fig. option is string containing 'on' or 'off'.
Rema rk s
pixval conflicts with certain other functions, such as zoom and rotate3d, that
enable you to use a mouse to interact with the figure. Use only one of these
functions at a time.
See Also
impixel, improfile
www.MatlabSite.com
11-165
qtdecom p
Purpose
Synta x
11qtdecomp
Perform quadtree decomposition
S
S
S
S
=
=
=
=
qtdecomp(I)
qtdecomp(I,threshold)
qtdecomp(I,threshold,mindim)
qtdecomp(I,threshold,[mindim maxdim])
S = qtdecomp(I,fun)
S = qtdecomp(I,fun,P1,P2,...)
Description
qtdecomp divides a square image into four equal-sized square blocks, and then
tests each block to see if it meets some criterion of homogeneity. If a block
meets the criterion, it is not divided any further. If it does not meet the
criterion, it is subdivided again into four blocks, and the test criterion is
applied to those blocks. This process is repeated iteratively until each block
meets the criterion. The result may have blocks of several different sizes.
S = qtdecomp(I) performs a quadtree decomposition on the intensity image I,
and returns the quadtree structure in the sparse matrix S. If S(k,m) is nonzero,
then (k,m) is the upper-left corner of a block in the decomposition, and the size
of the block is given by S(k,m). By default, qtdecomp splits a block unless all
elements in the block are equal.
S = qtdecomp(I,threshold) splits a block if the maximum value of the block
elements minus the minimum value of the block elements is greater than
threshold. threshold is specified as a value between 0 and 1, even if I is of
class uint8. If I is uint8, the threshold value you supply is multiplied by 255
to determine the actual threshold to use.
S = qtdecomp(I,threshold,mindim) will not produce blocks smaller than
mindim, even if the resulting blocks do not meet the threshold condition.
S = qtdecomp(I,threshold,[mindim maxdim]) will not produce blocks
smaller than mindim or larger than maxdim. Blocks larger than maxdim are split
even if they meet the threshold condition. maxdim/mindim must be a power of 2.
S = qtdecomp(I,fun) uses the function fun to determine whether to split a
block. qtdecomp calls fun with all the current blocks of size m-by-m stacked into
an m-by-m-by-k array, where k is the number of m-by-m blocks. fun should return
a k-element vector, containing only 1’s and 0’s, where 1 indicates that the
11-166
www.MatlabSite.com
qtdecomp
corresponding block should be split, and 0 indicates it should not be split. (For
example, if k(3) is 0, the third m-by-m block should not be split.) fun can be a
string containing the name of a function, a string containing an expression, or
an inline function.
S = qtdecomp(I,fun,P1,P2,...) passes P1,P2,..., as additional arguments
to fun.
Cla ss Support
For the syntaxes that do not include a function,the input image can be of class
uint8 or double. For the syntaxes that include a function, the input image can
be of any class supported by the function. The output matrix is always of class
sparse.
Rema rk s
qtdecomp is appropriate primarily for square images whose dimensions are a
power of 2, such as 128-by-128 or 512-by-512. These images can be divided
until the blocks are as small as 1-by-1. If you use qtdecomp with an image
whose dimensions are not a power of 2, at some point the blocks cannot be
divided further. For example, if an image is 96-by-96, it can be divided into
blocks of size 48-by-48, then 24-by-24, 12-by-12, 6-by-6, and finally 3-by-3. No
further division beyond 3-by-3 is possible. To process this image, you must set
mindim to 3 (or to 3 times a power of 2); if you are using the syntax that includes
a function, the function must return 0 at the point when the block cannot be
divided further.
www.MatlabSite.com
11-167
qtdecom p
Ex a mple
I = [1
1
1
1
20
20
20
22
1
1
1
1
22
22
22
22
1
2
1
1
20
22
20
20
1
1
1
1
22
20
20
20
2
4
10
20
1
5
9
13
3
5
15
25
2
6
10
14
6
6
7
7
3
7
11
15
0
0
0
0
0
0
0
0
2
0
1
1
2
0
2
0
0
0
1
1
0
0
0
0
2
0
2
0
2
0
2
0
6
8
7
7
4
8
12
16];
S = qtdecomp(I,5);
full(S)
ans =
4
0
0
0
4
0
0
0
See Also
11-168
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
qtgetblk, qtsetblk
www.MatlabSite.com
0
0
0
0
0
0
0
0
qtgetblk
Purpose
11qtgetblk
Get block values in quadtree decomposition
Synta x
[vals,r,c] = qtgetblk(I,S,dim)
[vals,idx] = qtgetblk(I,S,dim)
Description
[vals,r,c] = qtgetblk(I,S,dim) returns in vals an array containing the
dim-by-dim blocks in the quadtree decomposition of I. S is the sparse matrix
returned by qtdecomp; it contains the quadtree structure. vals is a
dim-by-dim-by-k array, where k is the number of dim-by-dim blocks in the
quadtree decomposition; if there are no blocks of the specified size, all outputs
are returned as empty matrices. r and c are vectors containing the row and
column coordinates of the upper-left corners of the blocks.
[vals,idx] = qtgetblk(I,S,dim) returns in idx a vector containing the
linear indices of the upper-left corners of the blocks.
Cla ss Support
I can be of class uint8 or double. S is of class sparse.
Rema rk s
The ordering of the blocks in vals matches the columnwise order of the blocks
in I. For example, if vals is 4-by-4-by-2, vals(:,:,1) contains the values from
the first 4-by-4 block in I, and vals(:,:,2) contains the values from the second
4-by-4 block.
www.MatlabSite.com
11-169
qtgetblk
Ex a mple
This example continues the qtdecomp example.
[vals,r,c] = qtgetblk(I,S,4)
vals(:,:,1) =
1
1
1
1
1
1
1
1
1
2
1
1
1
1
1
1
20
22
20
20
22
20
20
20
vals(:,:,2) =
20
20
20
22
22
22
22
22
r =
1
5
c =
1
1
See Also
11-170
qtdecomp, qtsetblk
www.MatlabSite.com
qtsetblk
Purpose
11qtsetblk
Set block values in quadtree decomposition
Synta x
J = qtsetblk(I,S,dim,vals)
Description
J = qtsetblk(I,S,dim,vals) replaces each dim-by-dim block in the quadtree
decomposition of I with the corresponding dim-by-dim block in vals. S is the
sparse matrix returned by qtdecomp; it contains the quadtree structure. vals
is a dim-by-dim-by-k array, where k is the number of dim-by-dim blocks in the
quadtree decomposition.
Cla ss Support
I can be of class uint8 or double. S is of class sparse.
Rema rk s
The ordering of the blocks in vals must match the columnwise order of the
blocks in I. For example, if vals is 4-by-4-by-2, vals(:,:,1) contains the
values used to replace the first 4-by-4 block in I, and vals(:,:,2) contains the
values for the second 4-by-4 block.
Ex a mple
This example continues the qtgetblock example.
newvals = cat(3,zeros(4),ones(4));
J = qtsetblk(I,S,4,newvals)
J =
0
0
0
0
1
1
1
1
See Also
0
0
0
0
1
1
1
1
0
0
0
0
1
1
1
1
0
0
0
0
1
1
1
1
2
4
10
20
1
5
9
13
3
5
15
25
2
6
10
14
6
6
7
7
3
7
11
15
6
8
7
7
4
8
12
16
qtdecomp, qtgetblk
www.MatlabSite.com
11-171
ra don
Purpose
11radon
Compute Radon transform
Synta x
R = radon(I,theta)
R = radon(I,theta,n)
[R,xp] = radon(...)
Description
The radon function computes the Radon transform, which is the projection of
the image intensity along a radial line oriented at a specified angle.
R = radon(I,theta) returns the Radon transform of the intensity image I for
the angle theta degrees. If theta is a scalar, the result R is a column vector
containing the Radon transform for theta degrees. If theta is a vector, then R
is a matrix in which each column is the Radon transform for one of the angles
in theta. If you omit theta, it defaults to 0:179.
R = radon(I,theta,n) returns a Radon transform with the projection
computed at n points. R has n rows. If you do not specify n, the number of points
at which the projection is computed is:
2*ceil(norm(size(I)–floor((size(I)–1)/2)–1))+3
This number is sufficient to compute the projection at unit intervals, even
along the diagonal.
[R,xp] = radon(...) returns a vector xp containing the radial coordinates
corresponding to each row of R.
Cla ss Support
I can be of class uint8 or double. All other inputs and outputs are of class
double.
Rema rk s
The radial coordinates returned in xp are the values along the x'-axis, which is
oriented at theta degrees counterclockwise from the x-axis. The origin of both
axes is the center pixel of the image, which is defined as:
floor((size(I)+1)/2)
For example, in a 20-by-30 image, the center pixel is (10,15).
11-172
www.MatlabSite.com
ra don
Ex a mple
iptsetpref('ImshowAxesVisible','on')
I = zeros(100,100);
I(25:75,25:75) = 1;
theta = 0:180;
[R,xp] = radon(I,theta);
imshow(theta,xp,R,[]), colormap(hot), colorbar
See Also
iradon, phantom
References
Lim, Jae S. Two-Dimensional Signal and Image Processing. Englewood Cliffs,
NJ: Prentice Hall, 1990. pp. 42-45.
Bracewell, Ronald N. Two-Dimensional Imaging. Englewood Cliffs, NJ:
Prentice Hall, 1995. pp. 505-537.
www.MatlabSite.com
11-173
rgb2 gra y
Purpose
11rgb2gray
Convert an RGB image or colormap to grayscale
Synta x
I = rgb2gray(RGB)
newmap = rgb2gray(map)
Description
rgb2gray converts RGB images to grayscale by eliminating the hue and
saturation information while retaining the luminance.
I = rgb2gray(RGB) converts the truecolor image RGB to the grayscale intensity
image I.
newmap = rgb2gray(map) returns a grayscale colormap equivalent to map.
Cla ss Support
If the input is an RGB image, it can be of class uint8 or double; the output
image I is of the same class as the input image. If the input is a colormap, the
input and output colormaps are both of class double.
Algorithm
rgb2gray converts the RGB values to NTSC coordinates, sets the hue and
saturation components to zero, and then converts back to RGB color space.
See Also
11-174
ind2gray, ntsc2rgb, rgb2ind, rgb2ntsc
www.MatlabSite.com
rgb2 hsv
Purpose
11rgb2hsv
Convert RGB values to hue-saturation-value (HSV) color space
Synta x
hsvmap = rgb2hsv(rgbmap)
HSV = rgb2hsv(RGB)
Description
hsvmap = rgb2hsv(rgbmap) converts the m-by-3 RGB values in RGB to HSV
color space. hsvmap is an m-by-3 matrix that contains the hue, saturation, and
value components as columns that are equivalent to the colors in the RGB
colormap. Both rgbmap and hsvmap are of class double and contain values in
the range 0 to 1.0.
HSV = rgb2hsv(RGB) converts the truecolor image RGB to the equivalent HSV
image HSV.
Cla ss Support
If the input is an RGB image, it can be of class uint8 or double; the output
image is of class double. If the input is a colormap, the input and output
colormaps are both of class double.
Rema rk s
rgb2hsv is a function in MATLAB.
See Also
hsv2rgb, rgbplot
colormap in the online MATLAB Function Reference
www.MatlabSite.com
11-175
rgb2 ind
Purpose
11rgb2ind
Convert an RGB image to an indexed image
Synta x
[X,map] = rgb2ind(RGB)
[X,map] = rgb2ind(RGB,tol)
[X,map] = rgb2ind(RGB,n)
X = rgb2ind(RGB,map)
[...] = rgb2ind(...,dither_option)
Description
rgb2ind converts RGB images to indexed images using one of four different
methods: direct translation, uniform quantization, minimum variance
quantization, and colormap mapping. For all methods except direct
translation, rgb2ind dithers the image unless you specify 'nodither' for
dither_option.
[X,map] = rgb2ind(RGB) converts the RGB image in the array RGB to an
indexed image X with colormap map using direct translation. The resulting
colormap may be very long, as it has one entry for each pixel in RGB. Do not set
dither_option if you use this method.
[X,map] = rgb2ind(RGB,tol) converts the RGB image to an indexed image X
using uniform quantization. map contains at most (floor(1/tol)+1)^3 colors.
tol must be between 0 and 1.0.
[X,map] = rgb2ind(RGB,n) converts the RGB image to an indexed image X
using minimum variance quantization. map contains at most n colors.
X = rgb2ind(RGB,map) converts the RGB image to an indexed image X with
colormap map by matching colors in RGB with the nearest color in the colormap
map.
[...] = rgb2ind(...,dither_option) enables or disables dithering.
dither_option is a string that can have one of these values:
• 'dither' (default) dithers, if necessary, to achieve better color resolution at
the expense of spatial resolution.
• 'nodither' maps each color in the original image to the closest color in the
new map. No dithering is performed.
Cla ss Support
11-176
The input image can be of class uint8 or double. The output image is of class
uint8 if the length of map is less than or equal to 256, or double otherwise.
www.MatlabSite.com
rgb2 ind
Rema rk s
If you specify tol, rgb2ind uses uniform quantization to convert the image.
This method involves cutting the RGB color cube into smaller cubes of length
tol. For example, if you specify a tol of 0.1, the edges of the cubes are
one-tenth the length of the RGB cube. The total number of small cubes is:
n = (floor(1/tol)+1)^3
Each cube represents a single color in the output image. Therefore, the
maximum length of the colormap is n. rgb2ind removes any colors that don’t
appear in the input image, so the actual colormap may be much smaller than n.
If you specify n, rgb2ind uses minimum variance quantization. This method
involves cutting the RGB color cube into smaller boxes (not necessarily cubes)
of different sizes, depending on how the colors are distributed in the image. If
the input image actually uses fewer colors than the number you specify, the
output colormap is also smaller.
If you specify map, rgb2ind uses colormap mapping, which involves finding the
colors in map that best match the colors in the RGB image.
Ex a mple
See Also
RGB = imread('flowers.tif');
[X,map] = rgb2ind(RGB,128);
imshow(X,map)
cmunique, dither, imapprox, ind2rgb, rgb2gray
www.MatlabSite.com
11-177
rgb2 ntsc
Purpose
11rgb2ntsc
Convert RGB values to NTSC color space
Synta x
yiqmap = rgb2ntsc(rgbmap)
YIQ = rgb2ntsc(RGB)
Description
yiqmap = rgb2ntsc(rgbmap) converts the m-by-3 RGB values in rbgmap to
NTSC color space. yiqmap is an m-by-3 matrix that contains the NTSC
luminance (Y) and chrominance (I and Q) color components as columns that are
equivalent to the colors in the RGB colormap.
YIQ = rgb2ntsc(RGB) converts the truecolor image RGB to the equivalent NTSC
image YIQ.
rgb2ntsc defines the NTSC components using:
Y
0.299
=
I
0.596
Q
0.211
0.587
– 0.274
– 0.523
0.114 R
– 0.322 G
0.312 B
Cla ss Support
If the input is an RGB image, it can be of class uint8 or double; the output
image is of class double. If the input is a colormap, the input and output
colormaps are both of class double.
Rema rk s
In the NTSC color space, the luminance is the grayscale signal used to display
pictures on monochrome (black and white) televisions. The other components
carry the hue and saturation information.
See Also
ntsc2rgb, rgb2ind, ind2rgb, ind2gray
11-178
www.MatlabSite.com
rgb2 ycbcr
Purpose
11rgb2ycbcr
Convert RGB values to YCbCr color space
Synta x
ycbcrmap = rgb2ycbcr(rgbmap)
YCBCR = rgb2ycbcr(RGB)
Description
ycbcrmap = rgb2ycbcr(rgbmap) converts the RGB values in rbgmap to the
YCbCr color space. ycbcrmap is an m-by-3 matrix that contains the YCbCr
luminance (Y) and chrominance (Cb and Cr) color components as columns.
Each row represents the equivalent color to the corresponding row in the RGB
colormap.
YCBCR = rgb2ycbcr(RGB) converts the truecolor image RGB to the equivalent
image in the YCbCr color space.
Cla ss Support
If the input is an RGB image, it can be of class uint8 or double; the output
image is of the same class as the input image. If the input is a colormap, the
input and output colormaps are both of class double.
See Also
ntsc2rgb, rgb2ntsc, ycbcr2rgb
www.MatlabSite.com
11-179
rgbplot
Purpose
11rgbplot
Plot colormap
Synta x
rgbplot(map)
Description
rgbplot(map) plots the three columns of map, where map is an m-by-3 colormap
matrix. rgbplot draws the first column in red, the second in green, and the
third in blue.
Ex a mple
See Also
11-180
rgbplot(jet)
colormap in the online MATLAB Function Reference
www.MatlabSite.com
roicolor
Purpose
11roicolor
Select region of interest, based on color
Synta x
BW = roicolor(A,low,high)
BW = roicolor(A,v)
Description
roicolor selects a region of interest within an indexed or intensity image and
returns a binary image. (You can use the returned image as a mask for masked
filtering using roifilt2.)
BW = roicolor(A,low,high) returns a region of interest selected as those
pixels that lie within the colormap range [low high]:
BW = (A >= low) & (A <= high)
BW is a binary image with 0’s outside the region of interest and 1’s inside.
BW = roicolor(A,v) returns a region of interest selected as those pixels in A
that match the values in vector v. BW is a binary image with 1’s where the
values of A match the values of v.
Cla ss Support
Ex a mple
See Also
The input image A can be of class uint8 or double. The output image BW is of
class uint8.
I = imread('rice.tif');
BW = roicolor(I,128,255);
imshow(I);
figure, imshow(BW)
roifilt2, roipoly
www.MatlabSite.com
11-181
roifill
Purpose
Synta x
11roifill
Smoothly interpolate within an arbitrary image region
J = roifill(I,c,r)
J = roifill(I)
J = roifill(I,BW)
[J,BW] = roifill(...)
J = roifill(x,y,I,xi,yi)
[x,y,J,BW,xi,yi] = roifill(...)
Description
roifill fills in a specified polygon in an intensity image. It smoothly
interpolates inward from the pixel values on the boundary of the polygon by
solving Laplace’s equation. roifill can be used, for example, to “erase” small
objects in an image.
J = roifill(I,c,r) fills in the polygon specified by c and r, which are
equal-length vectors containing the row-column coordinates of the pixels on
vertices of the polygon. The k-th vertex is the pixel (r(k),c(k)).
J = roifill(I) displays the image I on the screen and lets you specify the
polygon using the mouse. If you omit I, roifill operates on the image in the
current axes. Use normal button clicks to add vertices to the polygon. Pressing
Backspace or Delete removes the previously selected vertex. A shift-click,
right-click, or double-click adds a final vertex to the selection and then starts
the fill; pressing Return finishes the selection without adding a vertex.
J = roifill(I,BW) uses BW (a binary image the same size as I) as a mask.
roifill fills in the regions in I corresponding to the nonzero pixels in BW. If
there are multiple regions, roifill performs the interpolation on each region
independently.
[J,BW] = roifill(...) returns the binary mask used to determine which
pixels in I get filled. BW is a binary image the same size as I with 1’s for pixels
corresponding to the interpolated region of I and 0’s elsewhere.
J = roifill(x,y,I,xi,yi) uses the vectors x and y to establish a nondefault
spatial coordinate system. xi and yi are equal-length vectors that specify
polygon vertices as locations in this coordinate system.
11-182
www.MatlabSite.com
roifill
[x,y,J,BW,xi,yi] = roifill(...) returns the XData and YData in x and y;
the output image in J; the mask image in BW; and the polygon coordinates in xi
and yi. xi and yi are empty if the roifill(I,BW) form is used.
If roifill is called with no output arguments, the resulting image is displayed
in a new figure.
Cla ss Support
Ex a mple
See Also
The input image I and the binary mask BW can be of class double or uint8. The
output image J is of the same class as I. All other inputs and outputs are of
class double.
I = imread('eight.tif');
c = [222 272 300 270 221 194];
r = [21 21 75 121 121 75];
J = roifill(I,c,r);
imshow(I)
figure, imshow(J)
roifilt2, roipoly
www.MatlabSite.com
11-183
roifilt2
Purpose
11roifilt2
Filter a region of interest
Synta x
J = roifilt2(h,I,BW)
J = roifilt2(I,BW,fun)
J = roifilt2(I,BW,fun,P1,P2,...)
Description
J = roifilt2(h,I,BW) filters the data in I with the two-dimensional linear
filter h. BW is a binary image the same size as I that is used as a mask for
filtering. roifilt2 returns an image that consists of filtered values for pixels
in locations where BW contains 1’s, and unfiltered values for pixels in locations
where BW contains 0’s. For this syntax, roifilt2 calls filter2 to implement
the filter.
J = roifilt2(I,BW,fun) processes the data in I using the function fun. The
result J contains computed values for pixels in locations where BW contains 1’s,
and the actual values in I for pixels in locations where BW contains 0’s.
fun can be a string containing the name of a function, a string containing an
expression, or an inline function object. fun should take a matrix as a single
argument and return a matrix of the same size:
y = fun(x)
J = roifilt2(I,BW,fun,P1,P2,...) passes the additional parameters
P1,P2,..., to fun.
Cla ss Support
11-184
For the syntax that includes a filter h, the input imageI can be of class double
or uint8, and the output array J is of class double. For the syntax that includes
a function, I can be of any class supported by fun, and the class of J depends
on the class of the output from fun.
www.MatlabSite.com
roifilt2
Ex a mple
This example continues the roipoly example.
h = fspecial('unsharp');
J = roifilt2(h,I,BW);
imshow(J)
See Also
filter2, roipoly
www.MatlabSite.com
11-185
roipoly
Purpose
Synta x
11roipoly
Select a polygonal region of interest
BW = roipoly(I,c,r)
BW = roipoly(I)
BW = roipoly(x,y,I,xi,yi)
[BW,xi,yi] = roipoly(...)
[x,y,BW,xi,yi] = roipoly(...)
Description
Use roipoly to select a polygonal region of interest within an image. roipoly
returns a binary image that you can use as a mask for masked filtering.
BW = roipoly(I,c,r) returns the region of interest selected by the polygon
described by vectors c and r. BW is a binary image the same size as I with 0’s
outside the region of interest and 1’s inside.
BW = roipoly(I) displays the image I on the screen and lets you specify the
polygon using the mouse. If you omit I, roipoly operates on the image in the
current axes. Use normal button clicks to add vertices to the polygon. Pressing
Backspace or Delete removes the previously selected vertex. A shift-click,
right-click, or double-click adds a final vertex to the selection and then starts
the fill; pressing Return finishes the selection without adding a vertex.
BW = roipoly(x,y,I,xi,yi) uses the vectors x and y to establish a nondefault
spatial coordinate system. xi and yi are equal-length vectors that specify
polygon vertices as locations in this coordinate system.
[BW,xi,yi] = roipoly(...) returns the polygon coordinates in xi and yi.
Note that roipoly always produces a closed polygon. If the points specified
describe a closed polygon (i.e., if the last pair of coordinates is identical to the
first pair), the length of xi and yi is equal to the number of points specified. If
the points specified do not describe a closed polygon, roipoly adds a final point
having the same coordinates as the first point. (In this case the length of xi and
yi is one greater than the number of points specified.)
[x,y,BW,xi,yi] = roipoly(...) returns the XData and YData in x and y; the
mask image in BW; and the polygon coordinates in xi and yi.
If roipoly is called with no output arguments, the resulting image is displayed
in a new figure.
11-186
www.MatlabSite.com
roipoly
Cla ss Support
The input image I can be of class double or uint8. The output image BW is of
class uint8. All other inputs and outputs are of class double.
Rema rk s
For any of the roipoly syntaxes, you can replace the input image I with two
arguments, m and n, that specify the row and column dimensions of an
arbitrary image. For example, these commands create a 100-by-200 binary
mask:
c = [112 112 79 79];
r = [37 66 66 37];
BW = roipoly(100,200,c,r);
If you specify m and n with an interactive form of roipoly, an m-by-n black
image is displayed, and you use the mouse to specify a polygon within this
image.
Ex a mple
See Also
I = imread('eight.tif');
c = [222 272 300 270 221 194];
r = [21 21 75 121 121 75];
BW = roipoly(I,c,r);
imshow(I)
figure, imshow(BW)
roifilt2, roicolor, roifill
www.MatlabSite.com
11-187
std2
Purpose
11std2
Compute the standard deviation of the elements of a matrix
Synta x
b = std2(A)
Description
b = std2(A) computes the standard deviation of the values in A.
Cla ss Support
A is an array of class uint8 or double. b is a scalar of class double.
Algorithm
std2 computes the standard deviation of the array A using std(A(:)).
See Also
corr2, mean2
std, mean in the online MATLAB Function Reference
11-188
www.MatlabSite.com
subim a ge
Purpose
11subimage
Display multiple images in the same figure
Synta x
subimage(X,map)
subimage(I)
subimage(BW)
subimage(RGB)
subimage(x,y,...)
h = subimage(...)
Description
You can use subimage in conjunction with subplot to create figures with
multiple images, even if the images have different colormaps. subimage works
by converting images to truecolor for display purposes, thus avoiding colormap
conflicts.
subimage(X,map) displays the indexed image X with colormap map in the
current axes.
subimage(I) displays the intensity image I in the current axes.
subimage(BW) displays the binary image BW in the current axes.
subimage(RGB) displays the truecolor image RGB in the current axes.
subimage(x,y...) displays an image using a nondefault spatial coordinate
system.
h = subimage(...) returns a handle to an image object.
Cla ss Support
The input image can be of class uint8 or double.
www.MatlabSite.com
11-189
subima ge
Ex a mple
See Also
load trees
[X2,map2] = imread('forest.tif');
subplot(1,2,1), subimage(X,map)
subplot(1,2,2), subimage(X2,map2)
imshow
subplot in the online MATLAB Function Reference
11-190
www.MatlabSite.com
truesize
Purpose
11truesize
Adjust display size of an image
Synta x
truesize(fig,[mrows mcols])
truesize(fig)
Description
truesize(fig,[mrows ncols]) adjusts the display size of an image. fig
is a figure containing a single image or a single image with a colorbar.
[mrows ncols] is a 1-by-2 vector that specifies the requested screen area in
pixels that the image should occupy.
truesize(fig) uses the image height and width for [mrows ncols]. This
results in the display having one screen pixel for each image pixel.
If you omit the figure argument, truesize works on the current figure.
Rema rk s
If the'TruesizeWarning' toolbox preference is 'on', truesize displays a
warning if the image is too large to fit on the screen. (The entire image is still
displayed, but at less than true size.) If 'TruesizeWarning' is 'off', truesize
does not display the warning. Note that this preference applies even when you
call truesize indirectly, such as through imshow.
See Also
imshow, iptsetpref, iptgetpref
www.MatlabSite.com
11-191
uint8
Purpose
11uint8
Convert data to unsigned 8-bit integers
Synta x
B = uint8(A)
Description
B = uint8(A) creates the unsigned 8-bit integer array B from the array A. If A
is a uint8 array, B is identical to A.
The elements of a uint8 array can range from 0 to 255. For any value in A
outside this range, the resulting value in B is not defined (and may vary from
platform to platform).
The fractional part of each value in A is discarded on conversion. This means,
for example, that uint8(102.99) is 102, not 103. Therefore, it is often a good
idea to round off the values in A before converting to uint8. For example:
B = uint8(round(A))
MATLAB supports these operations on uint8 arrays:
• Displaying data values
• Indexing into arrays using standard MATLAB subscripting
• Reshaping, reordering, and concatenating arrays, using functions such as
reshape, cat, and permute
• Saving to and loading from MAT-files
• The all and any functions
• Logical operators and indexing
• Relational operators
MATLAB also supports the find function for uint8 arrays, but the returned
array is of class double.
Most of the functions in the Image Processing Toolbox accept uint8 input. See
the individual Reference entries for information about uint8 support.
Rema rk s
uint8 is a MATLAB built-in function.
See Also
double, im2double, im2uint8
11-192
www.MatlabSite.com
w a rp
Purpose
11warp
Display an image as a texture-mapped surface
Synta x
warp(X,map)
warp(I,n)
warp(BW)
warp(RGB)
warp(z,...)
warp(x,y,z,...)
h = warp(...)
Description
warp(X,map) displays the indexed image X with colormap map as a texture map
on a simple rectangular surface.
warp(I,n) displays the intensity image I with gray scale colormap of length n
as a texture map on a simple rectangular surface.
warp(BW) displays the binary image BW as a texture map on a simple
rectangular surface.
warp(RGB) displays the RGB image in the array RGB as a texture map on a
simple rectangular surface.
warp(z,...) displays the image on the surface z.
warp(x,y,z...) displays the image on the surface (x,y,z).
h = warp(...) returns a handle to a texture mapped surface.
Cla ss Support
The input image can be of class uint8 or double.
Rema rk s
Texture-mapped surfaces render more slowly than images.
www.MatlabSite.com
11-193
w a rp
Ex a mple
This example texture maps an image of a test pattern onto a cylinder:
[x,y,z] = cylinder;
I = imread('testpat1.tif');
warp(x,y,z,I);
See Also
imshow
image, imagesc, surf in the online MATLAB Function Reference
11-194
www.MatlabSite.com
w iener2
Purpose
11wiener2
Perform two-dimensional adaptive noise-removal filtering
Synta x
J = wiener2(I,[m n],noise)
[J,noise] = wiener2(I,[m n])
Description
wiener2 lowpass filters an intensity image that has been degraded by constant
power additive noise. wiener2 uses a pixel-wise adaptive Wiener method based
on statistics estimated from a local neighborhood of each pixel.
J = wiener2(I,[m n],noise) filters the image I using pixel-wise adaptive
Wiener filtering, using neighborhoods of size m-by-n to estimate the local image
mean and standard deviation. If you omit the [m n] argument, m and n default
to 3. The additive noise (Gaussian white noise) power is assumed to be noise.
[J,noise] = wiener2(I,[m n]) also estimates the additive noise power before
doing the filtering. wiener2 returns this estimate in noise.
Cla ss Support
The input image I can be of class uint8 or double. The output image J is of the
same class as I.
Ex a mple
Degrade and then restore an intensity image using adaptive Wiener filtering.
I = imread('saturn.tif');
J = imnoise(I,'gaussian',0,0.005);
K = wiener2(J,[5 5]);
imshow(J)
figure, imshow(K)
Algorithm
wiener2 estimates the local mean and variance around each pixel
www.MatlabSite.com
11-195
w iener2
1
µ = ----------NM
∑
n 1, n 2 ∈ η
1
2
σ = ----------NM
∑
a ( n 1, n 2 )
2
n 1, n 2 ∈ η
a ( n 1, n 2 ) – µ
2
where η is the N-by-M local neighborhood of each pixel in the image A. wiener2
then creates a pixel-wise Wiener filter using these estimates
2
2
σ –ν
- ( a ( n 1, n 2 ) – µ )
b ( n 1, n 2 ) = µ + ----------------2
σ
where ν2 is the noise variance. If the noise variance is not given, wiener2 uses
the average of all the local estimated variances.
See Also
filter2, medfilt2
Reference
Lim, Jae S. Two-Dimensional Signal and Image Processing. Englewood Cliffs,
NJ: Prentice Hall, 1990. pp. 536-540.
11-196
www.MatlabSite.com
ycbcr2 rgb
Purpose
11ycbcr2rgb
Convert YCbCr values to RGB color space
Synta x
rgbmap = ycbcr2rgb(ycbcrmap)
RGB = ycbcr2rgb(YCBCR)
Description
rgbmap = ycbcr2rgb(ycbcrmap) converts the YCbCr values in the colormap
ycbcrmap to the RGB color space. If ycbcrmap is m-by-3 and contains the YCbCr
luminance (Y) and chrominance (Cb and Cr) color components as its columns,
then rgbmap is returned as an m-by-3 matrix that contains the red, green, and
blue values equivalent to those colors.
RGB = ycbcr2rgb(YCBCR) converts the YCbCr image YCBCR to the equivalent
truecolor image RGB.
Cla ss Support
If the input is a YCbCr image, it can be of class uint8 or double; the output
image is of the same class as the input image. If the input is a colormap, the
input and output colormaps are both of class double.
See Also
ntsc2rgb, rgb2ntsc, rgb2ycbcr
www.MatlabSite.com
11-197
zoom
Purpose
11zoom
Zoom in and out of an image
Synta x
zoom on
zoom off
zoom out
zoom reset
zoom
zoom xon
zoom yon
zoom(factor)
zoom(fig,option)
Description
zoom on turns on interactive zooming for the current figure. When zooming is
enabled, clicking the mouse on a point within an axes changes the axes limits
by a factor of 2, to either zoom in on or out from the point:
• For a single-button mouse, zoom in by clicking the mouse button and zoom
out by shift-clicking.
• For a two- or three-button mouse, zoom in by clicking the left mouse button
and zoom out by clicking the right mouse button.
Clicking and dragging over an axes when interactive zooming is enabled draws
a rubber-band box. When the mouse button is released, the axes zoom in to the
region enclosed by the rubber-band box.
Double-clicking within an axes returns the axes to its initial zoom setting.
zoom out returns the plot to its initial zoom setting.
zoom reset remembers the current zoom setting as the initial zoom setting.
Later calls to zoom out, or double-clicks when interactive zoom mode is
enabled, return to this zoom level.
zoom toggles the interactive zoom status.
zoom xon and zoom yon sets zoom on for the x- and y-axis, respectively.
zoom(factor) zooms in by the specified factor, without affecting the
interactive zoom mode. By default, factor is 2. A factor between 0 and 1
specifies zooming out by 1/factor.
11-198
www.MatlabSite.com
zoom
zoom(fig,option) applies the zoom command to the figure specified by fig.
option is a string containing any of the above arguments. If you do not specify
a figure, zoom works on the current figure.
See Also
imcrop
www.MatlabSite.com
11-199
zoom
11-200
www.MatlabSite.com
Index
A
adaptive filtering 7-23, 11-195
aliasing 3-5
analyzing images
contour plots 7-7
edge detection 7-10, 11-52
histograms 7-8, 11-117
intensity profiles 7-4, 11-123
pixel values 7-3, 11-121
quadtree decomposition 7-11, 11-166
summary statistics 7-9
anti-aliasing 3-5, 11-129
applylut 8-20, 11-10
area of binary images 8-18, 11-16
arrays
logical 1-7, 1-15
storing images 1-3
averaging filter 5-10, 11-70
B
bestblk 11-12
bicubic interpolation 3-3
bilinear interpolation 3-3
binary image operations 8-2
connected-components labeling 8-15, 11-23
feature measurement 8-18
flood fill 8-13, 11-20
lookup-table operations 8-20, 11-10, 11-151
morphological operations 8-4, 11-25
neighborhoods 8-2, 11-10
object-based operations 8-10
padding borders 8-2
binary images 1-7, 11-147
4-connected neighborhoods 8-10
8-connected neighborhoods 8-10
converting from other types 11-96
displaying 2-6, 8-3
Euler number 8-19, 11-18
image area 8-18, 11-16
object selection 8-16, 11-30
perimeter determination 8-12, 11-29
processing 8-2
binary masks 9-3
blkproc 4-8, 11-13
block processing 4-2
block size 11-12
column processing 4-11
distinct blocks 4-8, 11-13
padding borders 4-5
sliding neighborhoods 4-4, 11-159
BMP files 1-11, 11-114, 11-126, 11-135
borders
padding 4-5, 5-5, 8-2
brighten 11-15
bwarea 8-18, 11-16
bweuler 8-19, 11-18
bwfill 8-13, 11-20
bwlabel 8-15, 11-23
bwmorph 8-8, 11-25
bwperim 8-12, 11-29
bwselect 8-16, 11-30
C
Canny edge detector 11-52
center pixel
linear filtering 5-4
morphological operations 8-4
closure 8-7, 11-25
cmpermute 11-32
cmunique 11-33
col2im 11-34
www.MatlabSite.com
I-1
Index
colfilt 4-11, 11-35
color 10-2
approximation 10-6, 11-49, 11-102, 11-177
dithering 10-8, 11-49
quantization 10-6, 11-177
reducing number of colors 10-5
color depth 10-3
color spaces
converting between 1-13, 10-9, 11-92, 11-160,
11-175, 11-178, 11-179, 11-197
HSV 10-10, 11-92
NTSC 10-9, 11-160, 11-178
RGB 10-9
YCbCr 10-10, 11-179, 11-197
colorbar 2-10, 11-37
colormap mapping 10-7
colormaps
brightening 11-15
darkening 11-15
plotting RGB values 11-180
rearranging colors 11-32
reducing number of colors 10-7
removing duplicate entries 11-33
RGB components 1-5
column processing 4-11, 11-35
reshaping blocks into columns 11-97
reshaping columns into blocks 11-34
computational molecule 5-4
connected-components labeling 8-15, 11-23
contour plots 7-7, 11-103
conv2 5-3, 11-39
conversions between image types 1-12
convmtx2 11-41
convn 5-9, 11-42
convolution
convolution matrix 11-41
Fourier transform 6-12
I-2
higher-dimensional 5-9, 11-42
separability 5-8
two-dimensional 5-3, 11-39, 11-62
convolution kernel 5-3
center pixel 5-4
coordinate systems
pixel coordinates 1-16
spatial coordinates 1-17
corr2 7-9, 11-43
correlation 5-7, 11-62
Fourier transform 6-13
correlation coefficient 11-43
cropping an image 3-7, 11-105
D
data types
8-bit integers 1-3, 1-13, 11-192
converting between 1-14, 11-50, 11-192
double-precision 1-3, 11-50
dct2 6-15, 11-44
dctmtx 6-16, 11-46
dilate 8-6, 11-47
dilation 8-4, 11-26, 11-47
discrete cosine transform 6-15, 11-44
image compression 6-17
inverse 11-93
transform matrix 6-16, 11-46
discrete Fourier transform 6-8
display techniques 2-2, 11-133
adding a colorbar 2-10, 11-37
displaying at true size 2-4, 11-191
multiple images 2-14, 11-189
preferences 2-3
texture mapping 2-17, 11-193
zooming 2-16, 11-198
www.MatlabSite.com
Index
distinct block operations 4-8
overlap 4-9, 11-13
zero padding 4-8
dither 1-12, 11-49
dithering 10-8, 11-49, 11-176
double 1-14, 11-50
E
edge 7-10, 11-51
edge detection 7-10
methods 11-52
enhancing images
intensity adjustment 7-14, 11-100
noise removal 7-20
erode 8-6, 11-56
erosion 8-4, 11-26, 11-56
Euclidean distance 7-4, 11-165
Euler number 8-19, 11-18
F
fast Fourier transform 6-8
higher-dimensional 11-60
higher-dimensional inverse 11-95
two-dimensional 11-58
two-dimensional inverse 11-94
feature measurement 7-9, 11-108
binary images 8-18
fft 6-8
fft2 6-8, 11-58
fftn 6-8, 11-60
fftshift 11-61
file formats 1-11, 11-114, 11-126, 11-135
files
displaying images in 2-8
reading image data from 11-126
reading image information from 11-114
writing image data to 11-135
filling a region 9-8
filter design 5-13
frequency sampling method 5-15, 11-67
frequency transformation method 5-14, 11-74
windowing method 5-16, 11-77, 11-81
filter2 5-7, 11-62
filters
adaptive 7-23, 11-195
averaging 5-10, 11-70
binary masks 9-6
designing 5-13
Finite Impulse Response (FIR) 5-13
frequency response 5-19, 6-11
Gaussian 11-70
Infinite Impulse Response (FIR) 5-14
Laplacian 11-70
Laplacian of Gaussian 11-70
linear 5-3, 7-21, 11-62
median 7-21, 11-155
order-statistic 11-161
predefined types 5-9, 11-70
Prewitt 11-70
Sobel 5-11, 11-70
unsharp 11-70
FIR filters 5-13
flood-fill operation 8-13, 11-20
Fourier transform 6-3
computing frequency response 6-11
convolution 6-12
correlation 6-13
higher-dimensional 11-60
higher-dimensional inverse 11-95
rearranging output 11-61
two-dimensional 11-58
two-dimensional inverse 11-94
www.MatlabSite.com
I-3
Index
freqspace 5-18, 11-64
frequency response
computing 5-19, 6-11, 11-65
desired response matrix 5-18, 11-64
frequency sampling method (filter design) 5-15,
11-67
frequency transformation method (filter design)
5-14, 11-74
freqz2 5-19, 6-11, 11-65
fsamp2 5-15, 11-67
fspecial 5-9, 11-70
ftrans2 5-14, 11-74
fwind1 5-17, 11-77
fwind2 5-17, 11-81
Hough transform
detecting lines 6-22
HSV color space 10-10, 11-92, 11-175
hsv2rgb 10-10, 11-92
I
idct2 11-93
ifft 6-8
ifft2 6-8, 11-94
ifftn 6-8, 11-95
IIR filters 5-14
im2bw 1-12, 11-96
im2col 11-97
im2double 1-14, 11-98
im2uint8 1-14, 11-99
G
gamma correction 7-16
Gaussian filter 11-70
Gaussian noise 7-23
geometric functions 3-2
cropping 3-7, 11-105
interpolation 3-3
resizing 3-5, 11-129
rotation 3-6, 11-131
getimage 11-85
getting preference values 11-142
gray2ind 1-12, 11-87
grayscale morphological operations 11-161
grayslice 1-12, 11-88
H
HDF files 1-11, 11-114, 11-126, 11-135
histeq 7-18, 11-89
histogram equalization 7-18, 11-89
histograms 7-8, 11-117
I-4
imadjust 7-14, 11-100
image area (binary images) 8-18, 11-16
image types
binary 1-7, 8-2
converting between 1-11
indexed 1-5
intensity 1-6
multiframe images 1-9
RGB (truecolor) 1-8
images
analyzing 7-3
color 10-2
color depth 10-3
converting to binary 11-96
data types 1-3, 11-50, 11-192
displaying 2-2, 11-133
displaying multiple images 2-14, 11-189
enhancing 7-14
file formats 1-11, 11-114, 11-126, 11-135
getting data from axes 11-85
mean value 11-154
www.MatlabSite.com
Index
reading data from files 11-126
reading information from files 11-114
reducing number of colors 10-5, 11-102
standard deviation 11-188
storing in MATLAB 1-3
writing to files 11-135
imapprox 10-7, 11-102
imcontour 7-7, 11-103
imcrop 3-7, 11-105
imfeature 7-9, 8-18, 11-108
imfinfo 1-11, 11-114
imhist 7-8, 11-117
immovie 2-13, 11-118
imnoise 7-21, 11-119
impixel 7-3, 11-121
improfile 7-4, 11-123
imread 1-11, 11-126
imresize 3-5, 11-129
imrotate 3-6, 11-131
imshow 2-3, 11-133
imwrite 1-11, 11-135
ind2gray 1-12, 11-139
ind2rgb 1-12, 11-140
indexed images 1-5, 11-149
converting from intensity 11-87
converting from RGB 11-176
converting to intensity 11-139
converting to RGB 11-140
displaying 2-5
reducing number of colors 10-5
intensity adjustment 7-14, 11-100
gamma correction 7-16
histogram equalization 7-18
intensity images 1-6, 11-148
converting from indexed 11-139
converting from matrices 11-153
converting from RGB 11-174
converting to indexed 11-87
displaying 2-5
number of gray levels displayed 2-6
intensity profiles 7-4, 11-123
interpolation 3-3
bicubic 3-3
bilinear 3-3
intensity profiles 7-4
nearest neighbor 3-3
iptgetpref 2-4, 11-141
iptsetpref 2-3, 11-142
iradon 6-25, 11-144
isbw 11-147
isgray 11-148
isind 11-149
isrgb 11-150
J
JPEG files 1-11, 11-114, 11-126, 11-135
JPEG image compression 6-17
L
Laplacian filter 11-70
Laplacian of Gaussian edge detector 11-52
Laplacian of Gaussian filter 11-70
linear filtering 4-5, 5-3, 11-62
averaging filter 5-10
center pixel 5-4
computational molecule 5-4
convolution 5-3
convolution kernel 5-3
correlation 5-7
filter design 5-13
FIR filters 5-13
IIR filters 5-14
www.MatlabSite.com
I-5
Index
noise removal 7-21
predefined filter types 5-9
Sobel filter 5-11
logical arrays 1-7, 1-15
lookup-table operations 8-20, 11-151
movies
creating from images 2-13, 11-118
playing 2-14
multiframe images 1-9
displaying 2-11, 11-157
limitations 1-10
multilevel thresholding 11-88
M
makelut 8-20, 11-151
masked filtering 9-6, 11-184
mat2gray 1-12, 11-153
matrices
converting to intensity images 11-153
storing images 1-3
McClellan transform 11-74
mean2 7-9, 11-154
medfilt2 7-21, 11-155
median filtering 7-21, 11-155
minimum variance quantization 10-6, 11-177
Moiré patterns 3-5
montage 2-12, 11-157
morphological operations 8-4, 11-25
center pixel 8-4
closure 8-7, 11-25
diagonal fill 11-26
dilation 8-4, 11-26, 11-47
erosion 8-4, 11-26, 11-56
grayscale 11-161
opening 8-7, 11-26
predefined operations 8-8
removing spur pixels 11-27
shrinking objects 11-26
skeletonizing objects 11-26
structuring elements 8-4
thickening objects 11-27
thinning objects 11-27
I-6
N
nearest neighbor interpolation 3-3
neighborhood operations 4-2
neighborhoods
binary image operations 8-2, 8-10, 11-10
nlfilter 4-6, 11-159
noise removal 7-20
adding noise 11-119
Gaussian noise 7-23, 11-119
salt and pepper noise 7-21, 11-119
speckle noise 11-119
nonlinear filtering 4-5
NTSC color space 10-9, 11-160, 11-178
ntsc2rgb 10-9, 11-160
O
object selection 8-16, 11-30
opening 8-7, 11-26
order-statistic filtering 11-161
ordfilt2 11-161
P
padding borders
binary image operations 8-2
block processing 4-5
linear filtering 5-5
www.MatlabSite.com
Index
PCX files 1-11, 11-114, 11-126, 11-135
perimeter determination 8-12, 11-29
phantom 6-25, 11-162
pixel coordinates 1-16
pixel values 7-3, 11-121, 11-165
pixels
definition 1-3
pixval 7-4, 11-165
plotting colormap values 11-180
preferences 2-3
getting values 11-142
setting values 11-141
Prewitt edge detector 11-52
Prewitt filter 11-70
Q
qtdecomp 7-11, 11-166
qtgetblk 11-169
qtsetblk 11-171
quadtree decomposition 7-11, 11-166
getting block values 11-169
setting block values 11-171
quantization
minimum variance quantization 10-6, 11-177
uniform quantization 10-6, 11-177
R
radon 6-19, 11-172
Radon transform 6-19, 11-172
detecting lines 6-22
inverse 6-25, 11-144
region of interest
binary masks 9-3
filling 9-8, 11-182
filtering 9-6, 11-184
selecting 9-3, 9-5, 11-181, 11-186
resizing images 3-5, 11-129
anti-aliasing 3-5
RGB images 1-8, 11-150
converting from indexed 11-140
converting to indexed 11-176
converting to intensity 11-174
displaying 2-7
reducing number of colors 10-5
rgb2gray 1-12, 11-174
rgb2hsv 10-10, 11-175
rgb2ind 1-12, 10-5, 11-176
rgb2ntsc 10-9, 11-178
rgb2ycbcr 10-10
rgbplot 11-180
Roberts edge detector 11-52
roicolor 9-5, 11-181
roifill 9-8, 11-182
roifilt2 9-6, 11-184
roipoly 9-3, 11-186
rotating an image 3-6, 11-131
S
salt and pepper noise 7-21
separability in convolution 5-8
setting preference values 11-141
sliding neighborhood operations 4-4, 11-159
Sobel edge detector 11-52
Sobel filter 5-11, 11-70
spatial coordinates 1-17
std2 7-9, 11-188
structuring elements 8-4
center pixel 8-4
subimage 2-16, 11-189
subplot 2-15
www.MatlabSite.com
I-7
Index
T
Y
template matching 6-13
texture mapping 2-17, 11-193
thresholding 11-88, 11-96
TIFF files 1-11, 11-114, 11-126, 11-135
transforms 6-2
discrete cosine 6-15, 11-44
Fourier 6-3, 11-58, 11-60, 11-61
inverse discrete cosine 11-93
inverse Fourier 11-94, 11-95
inverse Radon 6-25, 11-144
Radon 6-19, 11-172
truecolor images 1-8
truesize 2-4, 11-191
YCbCr color space 10-10, 11-179, 11-197
ycbcr2rgb 10-10
Z
zero-cross edge detector 11-52
zoom 2-16, 11-198
zooming in 2-16, 11-198
U
uint8 11-192
uint8 arrays
storing images 1-3
supported operations 1-13, 11-192
uniform quantization 10-6, 11-177
unsharp filter 11-70
W
warp 2-17, 11-193
wiener2 7-23, 11-195
windowing method (filter design) 5-16, 11-77,
11-81
X
XWD files 1-11, 11-114, 11-126, 11-135
I-8
www.MatlabSite.com