Matlab image processing toolbox user's guide (copyright mathworks)
Trang 1Computation Visualization Programming
For Use with M ATLAB®
Toolbox
User’s Guide
Trang 2support@mathworks.com Technical support
suggest@mathworks.com Product enhancement suggestions
bugs@mathworks.com Bug reports
doc@mathworks.com Documentation error reports
service@mathworks.com Order status, license renewals, passcodes
info@mathworks.com Sales, pricing, and general information
The MathWorks, Inc Mail
3 Apple Hill Drive
Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
Image Processing Toolbox User’s Guide
COPYRIGHT 1993 - 2001 by The MathWorks, Inc.
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
repro-duced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by
or for the federal government of the United States By accepting delivery of the Program, the government hereby agrees that this software qualifies as "commercial" computer software within the meaning of FAR Part 12.212, DFARS Part 227.7202-1, DFARS Part 227.7202-3, DFARS Part 252.227-7013, and DFARS Part 252.227-7014 The terms and conditions of The MathWorks, Inc Software License Agreement shall pertain
to the government’s use and disclosure of the Program and Documentation, and shall supersede any conflicting contractual terms or conditions If this license fails to meet the government’s minimum needs or
is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Documentation, unused, to MathWorks.
MATLAB, Simulink, Stateflow, Handle Graphics, and Real-Time Workshop are registered trademarks, and Target Language Compiler is a trademark of The MathWorks, Inc.
Other product or brand names are trademarks or registered trademarks of their respective holders.
Printing History: August 1993 First printing Version 1
May 1997 Second printing Version 2 January 1998 Revised for Version 2.1 (Online only) January 1999 Revised for Version 2.2 (Release 11) (Online only) September 2000 Revised for Version 2.2.2 (Release 12) (Online only) April 2001 Third Printing Version 3.0
Trang 3trees 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 cell Cancer cellfrom a rat’s prostate, courtesy of Alan W Partin,
M.D., Ph.D., Johns Hopkins University School of Medicine LAN files Permission to use Landsat™ data sets provided by Space
Imaging, LLC, Denver, Colorado.
Copyright J C Russ, The Image Processing Handbook, Second Edition,
1994, CRC Press, Boca Raton, ISBN 0-8493-2516-1 Used with permission.
Trang 6Getting Started
Preface
What Is the Image Processing Toolbox? xxv
R12 Related Products List xxvi
Configuration Notes xxviii
About This Manual xxix
Words You Need to Know xxx
Typographical Conventions xxxi
Image Processing Demos xxxiii
MATLAB Newsgroup xxxvii
1
Getting Started
Overview 1-2
Exercise 1 — Some Basic Topics 1-3
1 Read and Display an Image 1-3
2 Check the Image in Memory 1-3
3 Perform Histogram Equalization 1-4
4 Write the Image 1-7
5 Check the Contents of the Newly Written File 1-8
Trang 74 Subtract the Background Image from the Original Image 1-13
5 Adjust the Image Contrast 1-14
6 Apply Thresholding to the Image 1-15
7 Determining the Number of Objects in the Image 1-16
8 Examine an Object 1-19
9 Measure Object Properties in the Image 1-20
10 Compute Statistical Properties of Objects in the Image 1-22
Where to Go from Here 1-25
Online Help 1-25 Toolbox Demos 1-25
Using the Image Processing Toolbox
2
Introduction
Overview 2-2
Words You Need to Know 2-2
Images in MATLAB and the Image Processing Toolbox 2-4
Storage Classes in the Toolbox 2-4
Image Types in the Toolbox 2-5
Indexed Images 2-5 Intensity Images 2-7 Binary Images 2-8 RGB Images 2-9 Multiframe Image Arrays 2-12 Summary of Image Types and Numeric Classes 2-13 Converting Image Types 2-14
Trang 8Converting Image Storage Classes 2-21
Converting Graphics File Formats 2-22
Image Arithmetic 2-23
Summary of Image Arithmetic Functions 2-24
Image Arithmetic Truncation Rules 2-24
Words You Need to Know 3-2
Displaying Images with imshow 3-3
Displaying Indexed Images 3-3
Displaying Intensity Images 3-4
Displaying Binary Images 3-6
Displaying RGB Images 3-11
Displaying Images Directly from Disk 3-13
Special Display Techniques 3-14
Adding a Colorbar 3-14
Displaying Multiframe Images 3-15
Displaying Multiple Images 3-19
Trang 9Printing Images 3-29 Troubleshooting 3-30
Performing General Spatial Transformations 4-11
Specifying the Transformation Type 4-11 Performing the Transformation 4-13 Advanced Spatial Transformation Techniques 4-14
Trang 10Selecting Control Points 5-15
Using the Control Point Selection Tool 5-15
Starting the Control Point Selection Tool 5-16
Viewing the Images 5-18
Specifying Matching Control Point Pairs 5-22
Saving Control Points 5-29
Using Correlation to Improve Control Points 5-32
6
Neighborhood and Block Operations
Overview 6-2
Words You Need to Know 6-2
Types of Block Processing Operations 6-3
Sliding Neighborhood Operations 6-4
Padding of Borders 6-5
Linear and Nonlinear Filtering 6-5
Distinct Block Operations 6-8
Overlap 6-9
Column Processing 6-11
Sliding Neighborhoods 6-11
Distinct Blocks 6-12
Trang 11Words You Need to Know 7-2
Linear Filtering 7-4
Convolution 7-4 Correlation 7-6 Filtering Using imfilter 7-7 Using Predefined Filter Types 7-14
Filter Design 7-16
FIR Filters 7-16 Frequency Transformation Method 7-17 Frequency Sampling Method 7-18 Windowing Method 7-19 Creating the Desired Frequency Response Matrix 7-20 Computing the Frequency Response of a Filter 7-21
Discrete Cosine Transform 8-17
The DCT Transform Matrix 8-18 The DCT and Image Compression 8-19
Radon Transform 8-21
Using the Radon Transform to Detect Lines 8-25
Trang 12Morphological Operations
Overview 9-2
Words You Need to Know 9-2
Dilation and Erosion 9-5
Understanding Dilation and Erosion 9-5
Structuring Elements 9-8
Dilating an Image 9-12
Eroding an Image 9-13
Combining Dilation and Erosion 9-15
Dilation- and Erosion-Based Functions 9-17
Example: Marker-Controlled Watershed Segmentation 9-42
Step 1: Read in Images 9-42
Step 2: Create the Structuring Element 9-43
Step 3: Enhance the Image Contrast 9-43
Step 4: Exaggerate the Gaps Between Objects 9-44
Step 5: Convert Objects of Interest 9-45
Step 6: Detect Intensity Valleys 9-46
Step 7: Watershed Segmentation 9-47
Step 8: Extract Features from Label Matrix 9-48
Objects, Regions, and Feature Measurement 9-50
Connected-Component Labeling 9-50
Selecting Objects in a Binary Image 9-52
Trang 13Analyzing and Enhancing Images
Overview 10-2
Words You Need to Know 10-2
Pixel Values and Statistics 10-4
Pixel Selection 10-4 Intensity Profile 10-5 Image Contours 10-9 Image Histogram 10-9 Summary Statistics 10-10 Region Property Measurement 10-10
Image Analysis 10-11
Edge Detection 10-11 Quadtree Decomposition 10-12
Image Enhancement 10-15
Intensity Adjustment 10-15 Noise Removal 10-21
11
Region-Based Processing
Overview 11-2
Words You Need to Know 11-2
Specifying a Region of Interest 11-4
Trang 14Using the Deblurring Functions 12-5
Deblurring with the Wiener Filter 12-6
Deblurring with a Regularized Filter 12-8
Deblurring with the Lucy-Richardson Algorithm 12-10
Creating Your Own Deblurring Functions 12-12
Avoiding Ringing in Deblurred Images 12-13
13
Color
Overview 13-2
Words You Need to Know 13-2
Working with Different Screen Bit Depths 13-4
Determining Your Systems Screen Bit Depth 13-4
Choosing a Screen Bit Depth 13-5
Trang 15Converting to Other Color Spaces 13-16
NTSC Color Space 13-16 YCbCr Color Space 13-17 HSV Color Space 13-17
Trang 17getnhood 14-150 getsequence 14-151 gray2ind 14-152 grayslice 14-153 graythresh 14-154 histeq 14-155 hsv2rgb 14-158 idct2 14-159 ifft2 14-160 ifftn 14-161 im2bw 14-162 im2col 14-164 im2double 14-165 im2mis 14-166 im2uint8 14-167 im2uint16 14-168 imabsdiff 14-169 imadd 14-170 imadjust 14-171 imapprox 14-174 imbothat 14-175 imclearborder 14-177 imclose 14-180 imcomplement 14-184 imcontour 14-186 imcrop 14-188 imdilate 14-191 imdivide 14-195 imerode 14-196 imextendedmax 14-199 imextendedmin 14-201 imfeature 14-203 imfill 14-209 imfilter 14-212 imfinfo 14-215 imhist 14-218
Trang 19phantom 14-314 pixval 14-317 psf2otf 14-318 qtdecomp 14-319 qtgetblk 14-322 qtsetblk 14-324 radon 14-325 reflect 14-327 regionprops 14-328 rgb2gray 14-334 rgb2hsv 14-335 rgb2ind 14-336 rgb2ntsc 14-338 rgb2ycbcr 14-339 rgbplot 14-340 roicolor 14-341 roifill 14-342 roifilt2 14-344 roipoly 14-346 std2 14-348 strel 14-349 stretchlim 14-355 subimage 14-357 tformarray 14-359 tformfwd 14-363 tforminv 14-364 translate 14-365 truesize 14-366 uint8 14-367 uint16 14-369 warp 14-371 watershed 14-373 wiener2 14-376 ycbcr2rgb 14-378 zoom 14-379
Trang 20Passing an Inline Object to a Function Function A-4
Passing a String to a Function Function A-4
Trang 22What Is the Image Processing Toolbox? xii
R12 Related Products List xiii
About This Manual xvi
Words You Need to Know xvii
Typographical Conventions xviii
MATLAB Newsgroup xxiv
Trang 23What Is the Image Processing Toolbox?
The Image Processing Toolbox is a collection of functions that extend thecapability of the MATLAB®numeric computing environment The toolboxsupports a wide range of image processing operations, including:
• Spatial image transformations
• Morphological operations
• Neighborhood and block operations
• Linear filtering and filter design
• Transforms
• Image analysis and enhancement
• Image registration
• Deblurring
• Region of interest operations
Many of the toolbox functions are MATLAB M-files, a series of MATLABstatements that implement specialized image processing algorithms You canview the MATLAB code for these functions using the statement
You can extend the capabilities of the Image Processing Toolbox by writingyour own M-files, or by using the toolbox in combination with other toolboxes,such as the Signal Processing Toolbox and the Wavelet Toolbox
For a list of the new features in version 3.0, see the Release Notes.
Trang 24R12 Related Products List
The Image Processing Toolbox requires MATLAB 6.0 (Release 12)
Additionally, The MathWorks provides several products that are especiallyrelevant to the kinds of tasks you can perform with the Image ProcessingToolbox
For more information about any of these products, see either:
• The online documentation for that product, if it is installed or if you are
reading the documentation from the CD
Note The toolboxes listed below all include functions that extend MATLAB’s
capabilities The blocksets all include blocks that extend Simulink’scapabilities
.
DSP Blockset Simulink block libraries for the design,
simulation, and prototyping of digital signalprocessing systems
Mapping Toolbox Tool for analyzing and displaying
geographically based information from withinMATLAB
MATLAB Integrated technical computing environment
that combines numeric computation, advancedgraphics and visualization, and a high-levelprogramming language
Trang 25Signal ProcessingToolbox
Tool for algorithm development, signal andlinear system analysis, and time-series datamodeling
Wavelet Toolbox Tool for signal and image analysis,
compression, and de-noising
Trang 26on your system and their version numbers.
For information about installing the toolbox, see the MATLAB Installation
Guide for your platform.
Note For the most up-to-date information about system requirements, see
the system requirements page, available in the products area at theMathWorks Web site (www.mathworks.com)
Trang 27About This Manual
This manual includes these chapters:
• Chapter 1, “Getting Started” contains two step-by-step examples that will
help you get started with using the Image Processing Toolbox
• Chapter 2, “Introduction” introduces the Image Processing Toolbox and its
capabilities
• Chapter 3, “Displaying and Printing Images” describes how to display and
print images in MATLAB
• Chapter 4, “Spatial Transformations” describes image cropping, resizing,
rotating, and other geometric transformations you can perform with theImage Processing Toolbox
• Chapter 5, “Image Registration” describes how to align two images of the
same scene using the Control Point Selection Tool
• Chapter 6, “Neighborhood and Block Operations” describes how to perform
block operations on images
• Chapter 7, “Linear Filtering and Filter Design” describes how to create
filters
• Chapter 8, “Transforms” discusses several important image transforms.
• Chapter 9, “Morphological Operations” describes the functions in the toolbox
that you can use to implement morphological image processing operations
• Chapter 10, “Analyzing and Enhancing Images” discusses working with
image data and displaying images in MATLAB and the Image ProcessingToolbox
• Chapter 11, “Region-Based Processing” describes how to perform image
processing on specific regions of an image
• Chapter 12, “Image Deblurring” describes the toolbox deblurring functions.
• Chapter 13, “Color” describes how to handle color images.
• Appendix A describes how to work with function functions.
For detailed reference descriptions of each toolbox function, go to the onlineReference Many reference descriptions also include examples, a description ofthe function’s algorithm, and references to additional reading material
Trang 28Words You Need to Know
At the beginning of each chapter (and sometimes at the beginning of a major
section within a chapter) are tables that serve as mini glossaries of words youneed to know in order to understand the information in the chapter These
titles are called “Words You Need to Know.” Some of the words are standard
image processing terms, which we have provided short definitions of for yourconvenience Many times the definition is intended to show how something isdefined in the realm of MATLAB, which may be a little different than in othersoftware packages In other cases, the words are included because they can
sometimes be confusing, even for domain experts Here are some examples:
• Sometimes in the field of image processing, one word is used to describe more
than one concept For example the resolution of an image can describe the
height and width of an image as a quantity of pixels in each direction, or itcan describe the number of pixels per linear measure, such as 100 dots perinch
• Sometimes in the field of image processing, the same concepts are described
by different terminology For example, a grayscale image can also be called
an intensity image.
Trang 29Typographical Conventions
This manual uses some or all of these conventions
Ellipsis ( ) ellipsis denotes all of the
syntaxes that came before
[c,ia,ib] = union( )
Example code Monospacefont To assign the value 5 toA,
enter
A = 5
Function names/syntax Monospacefont Thecosfunction finds the
cosine of each array element.Syntax line example is
MLGetVar ML_var_name
letter
Press the Return key.
Literal strings (in syntax
Italics for variables
Standard text font for functions,operators, and constants
This vector represents thepolynomial
p = x2+ 2x + 3
MATLAB output Monospace font MATLAB responds with
A =5
Menu titles, menu items,
dialog boxes, and controls
letter
Choose the File menu.
Trang 30New terms Italics An array is an ordered
collection of information
String variables (from a
finite list)
Trang 31Image Processing Demos
The Image Processing Toolbox is supported by a full complement of demoapplications These are very useful as templates for your own end-userapplications, or for seeing how to use and combine your toolbox functions forpowerful image analysis and enhancement The toolbox demos are locatedunder the subdirectory,
matlabroot\toolbox\images\imdemos
wherematlabrootrepresents your MATLAB installation directory
The table below lists the demos available Demos whose names begin with
"ipss"operate as slideshows Demos whose names begin with "ipex"areextended examples in HTML form
The easiest way to run an individual demo is to enter its name at the MATLABcommand prompt You can also launch MATLAB demos from the MATLAB
Demo Window To evoke this window select Demos from the Help menu of the
main MATLAB window, or simply typedemoat the command prompt To see
the list of available image processing demos, double-click on Toolboxes from the list on the left, then select Image Processing Select the desired demo and press the Run button.
If you want to know whether there is a demo that uses a particular function,check the function name in the index If there is a demo that demonstrates thisfunction, a subentry of “See alsodemoname” will appear, wheredemonameis thename of the demo
coefficients and it shows you a reconstructed imageand an error image
manual control over threshold, direction, andsigma, as appropriate to the method used
your own filter by changing the cut-off frequencyand filter order
Trang 32imadjdemo Contrast Adjustment and Histogram Equalization:
adjust intensity values using brightness, contrast,and gamma correction, or by using histogramequalization
use spatial- and image-transformation functions toperform a conformal mapping
algorithm: illustrates use of thedeconvlucy
function
illustrates use of thedeconvregfunction
illustrates use of thedeconvwnrfunction
illustrates how to use morphology functions toperform granulometry
Set: illustrates how to use the imagetransformation functions to interpolate and reslice
a three-dimensional MRI data set, providing aconvenient way to view a volume of data
Cross-correlation: illustrates how to use translation
to align two images
illustrates how to use the Control Point SelectionTool to align two images
Image: illustrates how to use thecp2tformfunction
to get the rotation angle and scale factor of adistorted image
Trang 33ipexsegcell Detecting a Cell Using Image Segmentation:
illustrates how to use dilation and erosion toperform edge detection
Segmentation: illustrates how to use morphologicalopening and closing to extract large objects from animage
Segmentation: illustrates use of morphologyfunctions to perform marker-control watershedsegmentation
illustrates how to use the padding options of theimage transformation functions
illustrates how to use theimtransformfunction toperform many types of image transformations
includes double thresholding, feature-based logic,and binary morphology All operations are
performed on one image
examples: the first example shows object selectionusingANDoperations on the ‘on’ pixels in two binaryimages; the second example shows filtering andthresholding on a single image
creates a coarse approximation of the background,subtracts it from the image, and then adjusts thepixel intensity values to fill the entire range
Trang 34nrfiltdemo Noise reduction using linear and non-linear filters:
allows you to add different types of noise withvariable densities, and choose a filter neighborhoodsize
a representation of the sparse matrix and areconstruction of the original image
and apply operations such as unsharp and fill Alsodisplays the binary mask of the ROI
Trang 35MATLAB Newsgroup
If you read newsgroups on the Internet, you might be interested in theMATLAB newsgroup (comp.soft-sys.matlab) This newsgroup gives youaccess to an active MATLAB user community It is an excellent way to seekadvice and to share algorithms, sample code, and M-files with other MATLABusers
Trang 36Getting Started
Exercise 1 — Some Basic Topics 1-3
1 Read and Display an Image 1-3
2 Check the Image in Memory 1-3
3 Perform Histogram Equalization 1-4
4 Write the Image 1-7
5 Check the Contents of the Newly Written File 1-8
Exercise 2 — Advanced Topics 1-10
1 Read and Display an Image 1-10
2 Use Morphological Opening to Estimate the Background 1-10
3 Display the Background Approximation as a Surface 1-11
4 Subtract the Background Image from the Original Image 1-13
5 Adjust the Image Contrast 1-14
6 Apply Thresholding to the Image 1-15
7 Determining the Number of Objects in the Image 1-16
8 Examine an Object 1-19
9 Measuring Object Properties in the Image 1-20
10 Compute Statistical Properties of Objects in the Image 1-23
Where to Go From Here 1-25
Online Help 1-25
Toolbox Demos 1-25
Trang 37This chapter contains two exercises to get you started doing image processingusing MATLAB and the Image Processing Toolbox The exercises includesections called “Here’s What Just Happened” so that you can read furtherabout the operations you just used In addition, the exercises containcross-references to other sections in this manual that have in-depth discussions
on the concepts presented in the examples
Note If you are new to MATLAB, you should first read Getting Started with
“Exercise 2 — Advanced Topics” includes more sophisticated topics, such ascomponents labeling and object property measurement, which are two of themany specialized types of image processing that you can perform using theImage Processing Toolbox
Trang 38Exercise 1 — Some Basic Topics
Before beginning with this exercise, start MATLAB You should already haveinstalled the Image Processing Toolbox, which runs seamlessly from MATLAB
For information about installing the toolbox, see the MATLAB Installation
Guide for your platform.
1 Read and Display an Image
Clear the MATLAB workspace of any variables and close open figure windows
clear, close all
To read an image, use theimreadcommand Let’s read in a TIFF image named
Processing Toolbox), and store it in an array namedI
I=imread('pout.tif');
Now callimshowto displayI
imshow(I)
2 Check the Image in Memory
Enter thewhoscommand to see howIis stored in memory
whos
Trang 39MATLAB responds with
Name Size Bytes Class
I 291x240 69840 uint8 arrayGrand total is 69840 elements using 69840 bytes
3 Perform Histogram Equalization
As you can see,pout.tifis a somewhat low contrast image To see thedistribution of intensities inpout.tifin its current state, you can create ahistogram by calling theimhistfunction (Precede the call toimhistwith the
Here’s What Just Happened
stored it in the variableI (For the list of graphics formats supported, see
The functionsimreadandimshowread and display graphics images inMATLAB In general, it is preferable to useimshowfor displaying imagesbecause it handles the image-related MATLAB properties for you (TheMATLAB functionimageis for low-level programming tasks.)
Note that ifpout.tifwere an indexed image, the appropriate syntax for
[X, map] = imread('pout.tif');
(For more information on the supported image types, see “Image Types inthe Toolbox” on page 2-5.)
into the MATLAB workspace As you saw,pout.tifis stored as a291-by-240 array Sincepout.tifwas an 8-bit image, it gets stored inmemory as anuint8array MATLAB can store images in memory asuint8,
an explanation of when the different storage classes are used.)
Trang 40figurecommand so that the histogram does not overwrite the display of the
imageIin the current figure window.)
figure, imhist(I) % Display a histogram of I in a new figure
Notice how the intensity range is rather narrow It does not cover the potentialrange of [0, 255], and is missing the high and low values that would result ingood contrast
Now callhisteqto spread the intensity values over the full range, thereby
improving the contrast ofI Return the modified image in the variableI2
I2 = histeq(I); % Equalize I and output in new array I2
Display the new equalized image,I2, in a new figure window
figure, imshow(I2) % Display the new equalized image I2