You are on page 1of 428

Computation

Visualization
Programming
For Use with MATLAB

Users Guide
Version 2
Image Processing
Toolbox
How to Contact The MathWorks:
508-647-7000 Phone
508-647-7001 Fax
The Mat hWor ks, Inc. Mail
24 Pr ime Par k Way
Nat ick, MA 01760-1500
http://www.mathworks.com Web
ftp.mathworks.com Anonymous FTP ser ver
comp.soft-sys.matlab Newsgr oup
support@mathworks.com Technical suppor t
suggest@mathworks.com Pr oduct enhancement suggest ions
bugs@mathworks.com Bug r epor t s
doc@mathworks.com Document at ion er r or r epor t s
subscribe@mathworks.com Subscr ibing user r egist r at ion
service@mathworks.com Or der st at us, license r enewals, passcodes
info@mathworks.com Sales, pr icing, and gener al infor mat ion
Image Processing Toolbox Users Guide
COPYRIGHT 1993 - 1998 by The Mat hWor ks, Inc. All Right s Reser ved.
The soft war e descr ibed in t his document is fur nished under a license agr eement . The soft war e may be used
or copied only under t he t er ms of t he license agr eement . No par t of t his manual may be phot ocopied or r epr o-
duced in any for m wit hout pr ior wr it t en consent fr om The Mat hWor ks, Inc.
U.S. GOVERNMENT: If Licensee is acquir ing t he Pr ogr ams on behalf of any unit or agency of t he U.S.
Gover nment , t he following shall apply: (a) For unit s of t he Depar t ment of Defense: t he Gover nment shall
have only t he r ight s specified in t he license under which t he commer cial comput er soft war e or commer cial
soft war e document at ion was obt ained, as set for t h in subpar agr aph (a) of t he Right s in Commer cial
Comput er Soft war e or Commer cial Soft war e Document at ion Clause at DFARS 227.7202-3, t her efor e t he
r ight s set for t h her ein shall apply; and (b) For any ot her unit or agency: NOTICE: Not wit hst anding any
ot her lease or license agr eement t hat may per t ain t o, or accompany t he deliver y of, t he comput er soft war e
and accompanying document at ion, t he r ight s of t he Gover nment r egar ding it s use, r epr oduct ion, and disclo-
sur e ar e as set for t h in Clause 52.227-19 (c)(2) of t he FAR.
MATLAB, Simulink, St at eflow, Handle Gr aphics, and Real-Time Wor kshop ar e r egist er ed t r ademar ks, and
Tar get Language Compiler is a t r ademar k of The Mat hWor ks, Inc.
Ot her pr oduct or br and names ar e t r ademar ks or r egist er ed t r ademar ks of t heir r espect ive holder s.
Pr int ing Hist or y: August 1993 Fir st pr int ing Ver sion 1
May 1997 Second pr int ing Ver sion 2
J anuar y 1998 Revised for Ver sion 2.1 (Online only)
J anuar y 1999 Revised for Ver sion 2.2 (Release 11) (Online only)
Image Credits
moon Copyr ight Michael Myer s. Used wit h per mission.
cameraman Copyr ight Massachuset t s Inst it ut e of Technology. Used wit h per mission.
trees Trees wit h a View, wat er color and ink on paper , copyr ight Susan Cohen.
Used wit h per mission.
forest Phot ogr aph of Car manah Ancient For est , Br it ish Columbia, Canada,
cour t esy of Susan Cohen.
circuit Micr ogr aph of 16-bit A/D conver t er cir cuit , cour t esy of St eve Decker and
Shujaat Nadeem, MIT, 1993.
m83 M83 spir al galaxy ast r onomical image cour t esy of Anglo-Aust r alian
Obser vat or y, phot ogr aphy by David Malin.
alumgrns
bacteria
blood1
bonemarr
circles
circlesm
debye1
enamel
flowers
ic
ngc4024l
ngc4024m
ngc4024s
rice
saturn
shot1
testpat1
testpat2
text
tire
Copyr ight J . C. Russ, The Image Processing Handbook, Second Edit ion,
1994, CRC Pr ess, Boca Rat on, ISBN 0-8493-2516-1. Used wit h per mission.
Befor e You Begin
What Is the Image Processi ng Toolbox? . . . . . . . . vi
New Feat ur es in Ver sion 2.x . . . . . . . . . . . . . . . vi
Inst alling t he Toolbox . . . . . . . . . . . . . . . . . . vii
About Thi s Manual . . . . . . . . . . . . . . . . . viii
Documentati on Conventi ons . . . . . . . . . . . . . ix
Before You Begin
vi
What Is the Image Processing Toolbox?
The Image Pr ocessing Toolbox is a collect ion of funct ions t hat ext end t he
capabilit y of t he MATLAB

numer ic comput ing envir onment . The t oolbox


suppor t s a wide r ange of image pr ocessing oper at ions, including:
Geomet r ic oper at ions
Neighbor hood and block oper at ions
Linear filt er ing and filt er design
Tr ansfor ms
Image analysis and enhancement
Binar y image oper at ions
Region of int er est oper at ions
Many of t he t oolbox funct ions ar e MATLAB M-files, ser ies of MATLAB
st at ement s t hat implement specialized image pr ocessing algor it hms. You can
view t he MATLAB code for t hese funct ions using t he st at ement :
type function_name
You can ext end t he capabilit ies of t he Image Pr ocessing Toolbox by wr it ing
your own M-files, or by using t he t oolbox in combinat ion wit h wit h ot her
t oolboxes, such as t he Signal Pr ocessing Toolbox and t he Wavelet Toolbox.
New Features in Version 2.x
Ver sion 2.2 (Release 11) of t he Image Pr ocessing Toolbox offer s a number of
advances over pr evious ver sions. This sect ion summar izes many of t he new
feat ur es since 1.0. For det ailed infor mat ion about t he new feat ur es (and
impor t ant bug fixes), please view t he Readme file. To view t he Readme, t ype t he
following command at t he MATLAB pr ompt :
helpwin images/Readme
Versi on 2.2 offer s t he following new feat ur es: 16-bit image pr ocessing (most
funct ions); speed opt imizat ion of many funct ions, including: bwfill, bwselect,
bwlabel, dilate, erode, histeq, imresize, imrotate, ordfilt2, medfilt2, and
im2uint8; new bor der -padding opt ions for medfilt2, and ordfilt2; and an
all-new funct ion, im2uint16.
What Is the Image Processing Toolbox?
vi i
In addit ion, some of t he new feat ur es and changes in MATLAB 5.3 (Release 11)
ar e r elevant t o t he oper at ion of t he Image Pr ocessing Toolbox 2.2. Relevant
changes in MATLAB 5.3 include: impr oved suppor t for int eger t ypes (uint8,
int8, uint16, int16, uint32, int32); suppor t for t wo new file for mat s, PNG and
HDF-EOS; 16-bit image display; and 16-bit TIFF file I/O.
Vers i on 2.1 offer ed t he following new feat ur es: inver se Radon t r ansfor m;
int er act ive pixel value display including dist ance bet ween t wo pixels; advanced
feat ur e measur ement ; Canny edge det ect ion; YCbCr color space suppor t ; easier
dat a pr ecision conver sion; and a new feat ur e for t he bwfill funct iont he
abilit y t o aut omat ically det ect and fill holes in object s.
Vers i on 2.0 offer ed t he following new feat ur es: suppor t for 8-bit image dat a;
suppor t for manipulat ing RGB and mult ifr ame images as mult idimensional
ar r ays; opt imizat ion of some 1.0 funct ions; and many new funct ions.
For a list of all of t he funct ions in t he Image Pr ocessing Toolbox, t ype t he
following command at t he MATLAB pr ompt :
helpwin images
Installing the Toolbox
To det er mine if t he Image Pr ocessing Toolbox is inst alled on your syst em, t ype
t his command at t he MATLAB pr ompt :
ver
When you ent er t his command, MATLAB displays infor mat ion about t he
ver sion of MATLAB you ar e r unning, including a list of all t oolboxes inst alled
on your syst em and t heir ver sion number s.
For infor mat ion about inst alling t he t oolbox, see t he MATLAB Installation
Guide for your plat for m.
Before You Begin
vii i
About This Manual
This manual has t hr ee main par t s:
Chapt er s 1 and 2 discuss wor king wit h image dat a and displaying images in
MATLAB and t he Image Pr ocessing Toolbox.
Chapt er s 3 t o 10 pr ovide in-dept h discussion of t he concept s behind t he
soft war e. Each chapt er cover s a differ ent t opic in image pr ocessing. For
example, Chapt er 5 discusses linear filt er ing, and Chapt er 9 discusses
binar y image oper at ions. Each chapt er pr ovides numer ous examples t hat
apply t he t oolbox t o r epr esent at ive image pr ocessing t asks.
Chapt er 11 gives a det ailed r efer ence descr ipt ion of each t oolbox funct ion.
Refer ence descr ipt ions include a synopsis of t he funct ions synt ax, as well as
a complet e explanat ion of opt ions. Many r efer ence descr ipt ions also include
examples, a descr ipt ion of t he funct ions algor it hm, and r efer ences t o
addit ional r eading mat er ial.
All user s should r ead Chapt er s 1 and 2. Less exper ienced user s will find
Chapt er s 3 t o 10 a valuable int r oduct ion t o image pr ocessing, while mor e
exper ienced user s may pr efer t o use Chapt er 11.
Documentation Conventions
ix
Documentation Conventions
We use some or all of t hese convent ions in our manuals.
To Indicate This Guide Uses Example
Example code Monospace type To assign t he value 5 t o A,
ent er
A = 5
Funct ion
names/synt ax
Monospace type The cos funct ion finds t he
cosine of each ar r ay
element .
Synt ax line example is
MLGetVar ML_var_name
Keys Boldface wit h an init ial
capit al let t er
Pr ess t he Re turn key.
Mat hemat ical
expr essions
Var iables in italics.
Funct ions, oper at or s, and
const ant s in st andar d
t ype.
This vect or r epr esent s t he
polynomial
p = x
2
+ 2x + 3
MATLAB
out put
Monospace type MATLAB r esponds wit h
A = 5
Menu names,
menu it ems,
and cont r ols
Boldface wit h an init ial
capit al let t er
Choose t he Fi le menu.
New t er ms italics An array is an or der ed
collect ion of infor mat ion.
Before You Begin
x
xi
Contents
Before You Begi n
What Is the Image Processi ng Toolbox? . . . . . . . . . . . . . . . . . . . . vi
New Feat ur es in Ver sion 2.x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vi
Inst alling t he Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vi i
About Thi s Manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vi i i
Documentati on Conventi ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i x
1
Introducti on
Overvi ew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Images i n MATLAB and the Image Processi ng Toolbox . . . 1-3
Dat a Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Image Types i n t he Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
Indexed Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
Int ensit y Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
Binar y Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
RGB Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7
Mult ifr ame Image Ar r ays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
Mult ifr ame Suppor t Limit at ions . . . . . . . . . . . . . . . . . . . . . . 1-9
Summar y of Image Types and Numer ic Classes . . . . . . . . . . . 1-10
Worki ng wi th Image Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
Reading a Gr aphics Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
Wr it ing a Gr aphics Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12
Quer ying a Gr aphics File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12
xi i Contents
Conver t ing The Image Type of Images . . . . . . . . . . . . . . . . . . . 1-13
Color Space Conver sions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14
Wor king wit h uint 8 and uint 16 Dat a . . . . . . . . . . . . . . . . . . . . 1-15
Mat hemat ical Oper at ions Suppor t for uint 8 and uint 16 . . 1-15
Conver t ing The Dat a Types of Images . . . . . . . . . . . . . . . . . . . 1-16
Tur ning t he Logical Flag on or off . . . . . . . . . . . . . . . . . . . . 1-17
Conver t ing t he Gr aphics File For mat of an Image . . . . . . . . . 1-17
Coordi nate Sys te ms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-18
Pixel Coor dinat es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-18
Spat ial Coor dinat es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19
Using a Nondefault Spat ial Coor dinat e Syst em . . . . . . . . . 1-20
2
Di splayi ng Images
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
St andard Di splay Techni ques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Displaying Images wit h imshow . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Pr efer ences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
The t r uesize Funct ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
Displaying Indexed Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
Displaying Int ensit y Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
Displaying Binar y Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Changing t he Display Color s . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Displaying RGB Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Displaying Images in Gr aphics Files . . . . . . . . . . . . . . . . . . . . . 2-8
Displaying Nonimage Dat a As an Int ensit y Image . . . . . . . . . . 2-8
Speci al Di splay Techni ques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
Adding a Color bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
Displaying Mult ifr ame Image Ar r ays . . . . . . . . . . . . . . . . . . . . 2-11
Displaying Fr ames Individually . . . . . . . . . . . . . . . . . . . . . . 2-11
Displaying All Fr ames at Once . . . . . . . . . . . . . . . . . . . . . . . 2-12
Conver t ing t he Ar r ay t o a Movie . . . . . . . . . . . . . . . . . . . . . 2-13
xi i i
Displaying Mult iple Images . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14
Displaying Each Image in a Separ at e Figur e . . . . . . . . . . . 2-14
Displaying Mult iple Images in t he Same Figur e . . . . . . . . . 2-15
Zooming in on a Region of an Image . . . . . . . . . . . . . . . . . . . . . 2-16
Text ur e Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17
Pri nti ng Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19
3
Geometri c Operati ons
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Inte rpolati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Image Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Image Re sizi ng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-5
Image Rotati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6
Image Croppi ng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7
4
Nei ghborhood and Block Operati ons
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Types of Block Pr ocessing Oper at ions . . . . . . . . . . . . . . . . . . . . 4-2
Sli di ng Neighborhood Operati ons . . . . . . . . . . . . . . . . . . . . . . . . . 4-4
Padding of Bor der s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
Linear and Nonlinear Filt er ing . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
Di st i nct Block Ope rat ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8
Over lap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9
xi v Contents
Column Proce s si ng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11
Sliding Neighbor hoods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11
Dist inct Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12
Rest r ict ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14
5
Li near Fi lte ri ng and Fi lter De si gn
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Linear Fi lteri ng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Convolut ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Rot at ing t he Convolut ion Ker nel . . . . . . . . . . . . . . . . . . . . . . 5-4
Det er mining t he Cent er Pixel . . . . . . . . . . . . . . . . . . . . . . . . . 5-4
Applying t he Comput at ional Molecule . . . . . . . . . . . . . . . . . . 5-4
Padding of Bor der s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
The filt er 2 Funct ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7
Separ abilit y . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8
Det er mining Separ abilit y . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9
Higher -Dimensional Convolut ion . . . . . . . . . . . . . . . . . . . . . . . . 5-9
Using Pr edefined Filt er Types . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9
Filter Desi gn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13
FIR Filt er s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13
Fr equency Tr ansfor mat ion Met hod . . . . . . . . . . . . . . . . . . . . . 5-14
Fr equency Sampling Met hod . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15
Windowing Met hod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16
Cr eat ing t he Desir ed Fr equency Response Mat r ix . . . . . . . . . 5-18
Comput ing t he Fr equency Response of a Filt er . . . . . . . . . . . . 5-19
xv
6
Transforms
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Fouri er Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Definit ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4
The Discr et e Four ier Tr ansfor m . . . . . . . . . . . . . . . . . . . . . . . . . 6-8
Relat ionship t o t he Four ier Tr ansfor m . . . . . . . . . . . . . . . . . 6-9
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9
Applicat ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-11
Fr equency Response of Linear Filt er s . . . . . . . . . . . . . . . . . 6-11
Fast Convolut ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-12
Locat ing Image Feat ur es . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-13
Di scre te Cosi ne Trans form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-15
The DCT Tr ansfor m Mat r ix . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16
The DCT and Image Compr ession . . . . . . . . . . . . . . . . . . . . . . 6-17
Radon Trans form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-19
Using t he Radon Tr ansfor m t o Det ect Lines . . . . . . . . . . . . . . 6-23
The Inver se Radon Tr ansfor m . . . . . . . . . . . . . . . . . . . . . . . . . 6-25
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-28
7
Analyzi ng and Enhanci ng Images
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
Pi xe l Values and St ati sti cs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3
Pixel Select ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3
Int ensit y Pr ofile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4
Image Cont our s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7
Image Hist ogr am . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8
Summar y St at ist ics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9
Feat ur e Measur ement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9
xvi Contents
Image Analysi s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10
Edge Det ect ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10
Quadt r ee Decomposit ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-11
Image Enhance ment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-14
Int ensit y Adjust ment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-14
Gamma Cor r ect ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-16
Hist ogr am Equalizat ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-18
Noise Removal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-20
Linear Filt er ing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-21
Median Filt er ing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-21
Adapt ive Filt er ing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-23
8
Bi nary Image Operat i ons
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Neighbor hoods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Padding of Bor der s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Displaying Binar y Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3
Morphologi cal Ope rations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4
Dilat ion and Er osion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4
Relat ed Oper at ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-7
Pr edefined Oper at ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-9
Obje ct -Based Operati ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-10
4- and 8-Connect ed Neighbor hoods . . . . . . . . . . . . . . . . . . . . . . 8-10
Per imet er Det er minat ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-12
Flood Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-13
Connect ed-Component s Labeling . . . . . . . . . . . . . . . . . . . . . . . 8-15
Object Select ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-16
Feat ure Measurement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-18
Image Ar ea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-18
Euler Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-19
xvi i
Lookup-Table Ope rat i ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-20
9
Regi on-Based Process i ng
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Speci fyi ng a Regi on of Interest . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-3
Select ing a Polygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-3
Ot her Select ion Met hods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-5
Filte ri ng a Regi on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6
Filli ng a Re gi on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-8
10
Color
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Worki ng wit h Di ffe re nt Color Depths . . . . . . . . . . . . . . . . . . . . 10-3
Re duci ng the Number of Colors i n an Image . . . . . . . . . . . . . 10-5
Using r gb2ind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-6
Quant izat ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-6
Color map Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-7
Using imappr ox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-8
Dit her ing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-8
Conve rting to Other Color Space s . . . . . . . . . . . . . . . . . . . . . . . . 10-9
NTSC For mat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-9
YCbCr For mat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-10
HSV For mat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-10
xvi i i Contents
11
Refere nce
1
Int r oduct ion
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . 1-2
Images i n MATLAB and the Image Processi ng Toolbox 1-3
Dat a Types . . . . . . . . . . . . . . . . . . . . . 1-3
Image Types i n t he Toolbox . . . . . . . . . . . . . 1-4
Indexed Images . . . . . . . . . . . . . . . . . . . 1-4
Int ensit y Images . . . . . . . . . . . . . . . . . . . 1-5
Binar y Images . . . . . . . . . . . . . . . . . . . . 1-6
RGB Images . . . . . . . . . . . . . . . . . . . . . 1-7
Mult ifr ame Image Ar r ays . . . . . . . . . . . . . . . 1-8
Summar y of Image Types and Numer ic Classes . . . . . . 1-10
Worki ng wi th Image Data . . . . . . . . . . . . . . 1-11
Reading a Gr aphics Image . . . . . . . . . . . . . . . 1-11
Wr it ing a Gr aphics Image . . . . . . . . . . . . . . . 1-12
Quer ying a Gr aphics File . . . . . . . . . . . . . . . 1-12
Conver t ing The Image Type of Images . . . . . . . . . . 1-13
Wor king wit h uint 8 and uint 16 Dat a . . . . . . . . . . 1-15
Conver t ing The Dat a Types of Images . . . . . . . . . . 1-16
Conver t ing t he Gr aphics File For mat of an Image . . . . . 1-17
Coordi nate Sys tems . . . . . . . . . . . . . . . . 1-18
Pixel Coor dinat es . . . . . . . . . . . . . . . . . . 1-18
Spat ial Coor dinat es . . . . . . . . . . . . . . . . . . 1-19
1 Introduction
1-2
Overview
This chapt er int r oduces you t o t he fundament als of image pr ocessing using
MATLAB and t he Image Pr ocessing Toolbox. It descr ibes t he t ypes of images
suppor t ed, and how MATLAB r epr esent s t hem. It also explains t he basics of
wor king wit h image dat a and coor dinat e syst ems.
Images in MATLAB and the Image Processing Toolbox
1-3
Images in MATLAB and the Image Processing Toolbox
The basic dat a st r uct ur e in MATLAB is t he array, an or der ed set of r eal or
complex element s. This object is nat ur ally suit ed t o t he r epr esent at ion of
images, r eal-valued, or der ed set s of color or int ensit y dat a. (MATLAB does not
suppor t complex-valued images.)
MATLAB st or es most images as t wo-dimensional ar r ays (i.e., mat r ices), in
which each element of t he mat r ix cor r esponds t o a single pixel in t he displayed
image. (Pixel is der ived fr om picture element and usually denot es a single dot
on a comput er display.) For example, an image composed of 200 r ows and 300
columns of differ ent color ed dot s would be st or ed in MATLAB as a 200-by-300
mat r ix. Some images, such as RGB, r equir e a t hr ee-dimensional ar r ay, wher e
t he fir st plane in t he t hir d dimension r epr esent s t he r ed pixel int ensit ies, t he
second plane r epr esent s t he gr een pixel int ensit ies, and t he t hir d plane
r epr esent s t he blue pixel int ensit ies.
This convent ion makes wor king wit h images in MATLAB similar t o wor king
wit h any ot her t ype of mat r ix dat a, and makes t he full power of MATLAB
available for image pr ocessing applicat ions. For example, you can select a
single pixel fr om an image mat r ix using nor mal mat r ix subscr ipt ing.
I(2,15)
This command r et ur ns t he value of t he pixel at r ow 2, column 15 of t he image I.
Data Types
By default , MATLAB st or es most dat a in ar r ays of class double. The dat a in
t hese ar r ays is st or ed as double pr ecision (64-bit ) float ing-point number s. All
of MATLABs funct ions and capabilit ies wor k wit h t hese ar r ays.
For image pr ocessing, however , t his dat a r epr esent at ion is not always ideal.
The number of pixels in an image may be ver y lar ge; for example, a
1000-by-1000 image has a million pixels. Since each pixel is r epr esent ed by at
least one ar r ay element , t his image would r equir e about 8 megabyt es of
memor y.
In or der t o r educe memor y r equir ement s, MATLAB suppor t s st or ing image
dat a in ar r ays of class uint8 and uint16. The dat a in t hese ar r ays is st or ed as
8-bit or 16-bit unsigned int eger s. These ar r ays r equir e one eight h or one four t h
as much memor y as double ar r ays.
1 Introduction
1-4
Image Types in the Toolbox
The Image Pr ocessing Toolbox suppor t s four basic t ypes of images:
Indexed Images
Int ensit y Images
Binar y Images
RGB Images
This sect ion discusses how MATLAB and t he Image Pr ocessing Toolbox
r epr esent each of t hese image t ypes.
Indexed Images
An indexed image consist s of a dat a mat r ix, X, and a color map mat r ix, map. map
is an m-by-3 ar r ay of class double cont aining float ing-point values in t he r ange
[0,1]. Each r ow of map specifies t he r ed, gr een, and blue component s of a single
color . An indexed image uses dir ect mapping of pixel values t o color map
values. The color of each image pixel is det er mined by using t he cor r esponding
value of X as an index int o map. The value 1 point s t o t he fir st r ow in map, t he
value 2 point s t o t he second r ow, and so on.
A color map is oft en st or ed wit h an indexed image and is aut omat ically loaded
wit h t he image when you use t he imread funct ion. However , you ar e not limit ed
t o using t he default color mapyou can use any color map t hat you choose. The
figur e below illust r at es t he st r uct ur e of an indexed image. The pixels in t he
Image Types in the Toolbox
1-5
image ar e r epr esent ed by int eger s, which ar e point er s (indices) t o color values
st or ed in t he color map.
The r elat ionship bet ween t he values in t he image mat r ix and t he color map
depends on t he class of t he image mat r ix. If t he image mat r ix is of class double,
t he value 1 point s t o t he fir st r ow in t he color map, t he value 2 point s t o t he
second r ow, and so on. If t he image mat r ix is of class uint8 or uint16, t her e is
an offset t he value 0 point s t o t he fir st r ow in t he color map, t he value 1 point s
t o t he second r ow, and so on. The offset is also used in gr aphics file for mat s t o
maximize t he number of color s t hat can be suppor t ed. In t he image above, t he
image mat r ix is of class double. Because t her e is no offset , t he value 5 point s
t o t he fift h r ow of t he color map.
Not e t hat t he t oolbox pr ovides only minimal suppor t for indexed images of class
uint16. You can r ead t hese images int o MATLAB and display t hem, but befor e
you can pr ocess a uint16 indexed image you must fir st conver t it t o eit her a
double or a uint8. To conver t t o a double, call im2double; t o r educe t he image
t o 256 color s or fewer (uint8) call imapprox. See t he Chapt er 11 descr ipt ions
for t hese funct ions.
Intensity Images
An int ensit y image is a dat a mat r ix, I, whose values r epr esent int ensit ies
wit hin some r ange. MATLAB st or es an int ensit y image as a single mat r ix, wit h
0 0 0
0.0627 0.0627 0.0314
0.2902 0.0314 0
0 0 1.0000
0.2902 0.0627 0.0627
0.3882 0.0314 0.0941
0.4510 0.0627 0
0.2588 0.1608 0.0627
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
.
.
.
1 Introduction
1-6
each element of t he mat r ix cor r esponding t o one image pixel. The mat r ix can
be of class double, uint8, or uint16. While int ensit y images ar e r ar ely saved
wit h a color map, MATLAB uses a color map t o display t hem. In essence,
MATLAB handles int ensit y images as indexed images.
The element s in t he int ensit y mat r ix r epr esent var ious int ensit ies, or gr ay
levels, wher e t he int ensit y 0 usually r epr esent s black and t he int ensit y 1, 255,
or 65535 usually r epr esent s full int ensit y, or whit e.
This figur e depict s an int ensit y image of class double.
Binary Images
In a binar y image, each pixel assumes one of only t wo discr et e values.
Essent ially, t hese t wo values cor r espond t o on and off. A binar y image is
st or ed as a t wo-dimensional mat r ix of 0s (off pixels) and 1s (on pixels).
A binar y image can be consider ed a special kind of int ensit y image, cont aining
only black and whit e. Ot her int er pr et at ions ar e possible, however ; you can also
t hink of a binar y image as an indexed image wit h only t wo color s.
A binar y image can be st or ed in an ar r ay of class double or uint8. (The t oolbox
does not suppor t binar y images of class uint16.) An ar r ay of class uint8 is
gener ally pr efer able t o an ar r ay of class double, because a uint8 ar r ay uses far
0.5342 0.2051 0.2157 0.2826 0.3822 0.4391 0.4391
0.5342 0.2251 0.2563 0.2826 0.2826 0.4391 0.4391
0.5342 0.1789 0.1307 0.1789 0.2051 0.3256 0.2483
0.4308 0.2483 0.2624 0.3344 0.3344 0.2624 0.2549
0.4510 0.3344 0.2624 0.3344 0.3344 0.3344 0.3344
Image Types in the Toolbox
1-7
less memor y. In t he Image Pr ocessing Toolbox, any funct ion t hat r et ur ns a
binar y image r et ur ns it as a uint8 logical ar r ay. The t oolbox uses a logical flag
t o indicat e t he dat a r ange of a uint8 logical ar r ay: if t he logical flag is on t he
dat a r ange is [0,1]; if t he logical flag is off, t he t oolbox assumes t he dat a r ange
is [0,255].)
This figur e shows an example of a binar y image.
RGB Images
An RGB image, somet imes r efer r ed t o as a t r uecolor image, is st or ed in
MATLAB as an m-by-n-by-3 dat a ar r ay t hat defines r ed, gr een, and blue color
component s for each individual pixel. RGB images do not use a palet t e. The
color of each pixel is det er mined by t he combinat ion of t he r ed, gr een, and blue
int ensit ies st or ed in each color plane at t he pixels locat ion. Gr aphics file
for mat s st or e RGB images as 24-bit images, wher e t he r ed, gr een, and blue
component s ar e 8 bit s each. This yields a pot ent ial of 16 million color s. The
pr ecision wit h which a r eal-life image can be r eplicat ed has led t o t he nickname
t r uecolor image.
An RGB MATLAB ar r ay can be of class double, uint8, or uint16. In an RGB
ar r ay of class double, each color component is a value bet ween 0 and 1. A pixel
whose color component s ar e (0,0,0) displays as black, and a pixel whose color
component s ar e (1,1,1) displays as whit e. The t hr ee color component s for each
pixel ar e st or ed along t he t hir d dimension of t he dat a ar r ay. For example, t he
r ed, gr een, and blue color component s of t he pixel (10,5) ar e st or ed in
RGB(10,5,1), RGB(10,5,2), and RGB(10,5,3), r espect ively.
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
1 Introduction
1-8
The next figur e shows an RGB image of class double.
To det er mine t he color of t he pixel at (2,3), you would look at t he RGB t r iplet
st or ed in (2,3,1:3). Suppose (2,3,1) cont ains t he value 0.5176, (2,3,2) cont ains
0.1608, and (2,3,3) cont ains 0.0627. The color for t he pixel at (2,3) is:
0.5176 0.1608 0.0627
Multiframe Image Arrays
For some applicat ions, you may need t o wor k wit h collect ions of images r elat ed
by t ime or view, such as magnet ic r esonance imaging (MRI) slices or movie
fr ames.
The Image Pr ocessing Toolbox pr ovides suppor t for st or ing mult iple images in
t he same ar r ay. Each separ at e image is called a frame. If an ar r ay holds
mult iple fr ames, t hey ar e concat enat ed along t he four t h dimension. For
0.5804 0.2235 0.1294 0.2902 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.4510 0.0941 0.0627 0.0941 0.0941 0.0941 0.0941
0.5176 0.1922 0.0627 0.1294 0.1922 0.2588 0.2588
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.4510 0.4196 0.3529 0.4196 0.4196 0.4196 0.4196
0.5490 0.2235 0.5490 0.5804 0.7412 0.7765 0.7765
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
Red
Green
Blue
Image Types in the Toolbox
1-9
example, an ar r ay wit h five 400-by-300 RGB images would be
400-by-300-by-3-by-5. A similar mult ifr ame int ensit y or indexed image would
be 400-by-300-by-1-by-5.
Use t he cat command t o st or e separ at e images int o one mult ifr ame file. For
example, if you have a gr oup of images A1, A2, A3, A4, and A5, you can st or e t hem
in a single ar r ay using:
A = cat(4,A1,A2,A3,A4,A5)
You can also ext r act fr ames fr om a mult ifr ame image. For example, if you have
a mult ifr ame image MULTI, t his command ext r act s t he t hir d fr ame.
FRM3 = MULTI(:,:,:,3)
Not e t hat in a mult ifr ame image ar r ay, each image must be t he same size and
have t he same number of planes. In a mult ifr ame indexed image, each image
must also use t he same color map.
Multiframe Support Limitations
Many of t he funct ions in t he t oolbox oper at e only on t he fir st t wo or fir st t hr ee
dimensions. You can st ill use four -dimensional ar r ays wit h t hese funct ions, but
you must pr ocess each fr ame individually. For example, t his call displays t he
sevent h fr ame in t he ar r ay MULTI.
imshow(MULTI(:,:,:,7))
If you pass an ar r ay t o a funct ion and t he ar r ay has mor e dimensions t han t he
funct ion is designed t o oper at e on, your r esult s may be unpr edict able. In some
cases, t he funct ion will simply pr ocess t he fir st fr ame of t he ar r ay, but in ot her
cases t he oper at ion will not pr oduce meaningful r esult s.
See t he MATLAB online r efer ence for infor mat ion about how individual
funct ions wor k wit h t he dimensions of an image ar r ay. For mor e infor mat ion
about displaying t he images in a mult ifr ame ar r ay, see Chapt er 2.
1 Introduction
1-10
Summary of Image Types and Numeric Classes
This t able summar izes t he way MATLAB int er pr et s dat a mat r ix element s as
pixel color s, depending on t he image t ype and dat a class.
Image Type double Data uint8 or uint16 Data
Binar y Image is an m-by-n ar r ay of
int eger s in t he r ange [0,1]
wher e t he logical flag is on.
Image is an m-by-n ar r ay of
int eger s in t he r ange [0,1]
if t he logical flag is on.
Indexed Image is an m-by-n ar r ay of
int eger s in t he r ange [1, p].
Color map is a p-by-3 ar r ay
of float ing-point values in
t he r ange [0, 1].
Image is an m-by-n ar r ay of
int eger s in t he r ange
[0, p 1].
Color map is a p-by-3 ar r ay
of float ing-point values in
t he r ange [0, 1].
Int ensit y Image is an m-by-n ar r ay of
float ing-point values t hat
ar e linear ly scaled by
MATLAB t o pr oduce
color map indices. The
t ypical r ange of values is [0,
1].
Color map is a p-by-3 ar r ay
of float ing-point values in
t he r ange [0, 1] and is
t ypically gr ayscale.
Image is an m-by-n ar r ay of
int eger s t hat ar e linear ly
scaled by MATLAB t o
pr oduce color map indices.
The t ypical r ange of values
is [0, 255] or [0, 65535].
Color map is a p-by-3 ar r ay
of float ing-point values in
t he r ange [0, 1] and is
t ypically gr ayscale.
RGB
(Tr uecolor )
Image is an m-by-n-by-3
ar r ay of float ing-point
values in t he r ange [0, 1].
Image is an m-by-n-by-3
ar r ay of int eger s in t he
r ange [0, 255] or [0, 65535].
Working with Image Data
1-11
Working with Image Data
MATLAB pr ovides commands for r eading, wr it ing, and displaying sever al
t ypes of gr aphics file for mat s images. As wit h MATLAB-gener at ed images,
once a gr aphics file for mat image is displayed, it becomes a Handle Gr aphics
Image object . MATLAB suppor t s t he following gr aphics file for mat s:
BMP (Micr osoft Windows Bit map)
HDF (Hier ar chical Dat a For mat )
J PEG (J oint Phot ogr aphic Exper t s Gr oup)
PCX (Paint br ush)
PNG (Por t able Net wor k Gr aphics)
TIFF (Tagged Image File For mat )
XWD (X Window Dump)
For t he lat est infor mat ion concer ning t he bit dept hs and/or image t ypes
suppor t ed for t hese for mat s, see t he online r efer ence descr ipt ions of imread and
imwrite.
This sect ion discusses how t o: r ead, wr it e, and wor k wit h gr aphics images; and
how t o conver t t he dat a t ype or gr aphics for mat of an image.
Reading a Graphics Image
The funct ion imread r eads an image fr om any suppor t ed gr aphics image file in
any of t he suppor t ed bit dept hs. Most of t he images t hat you will r ead ar e 8-bit .
When t hese ar e r ead int o memor y, MATLAB st or es t hem as class uint8. The
main except ion t o t his r ule is t hat MATLAB suppor t s 16-bit dat a for PNG and
TIFF images. If you r ead a 16-bit PNG or TIFF image, it will be st or ed as class
uint16.
Note: For indexed images, imread always r eads t he color map int o an ar r ay of
class double, even t hough t he image ar r ay it self may be of class uint8 or
uint16.
To see t he many synt ax subt let ies for r eading an image, see t he online
Funct ion Refer ence descr ipt ion of imread. For our discussion her e we will show
1 Introduction
1-12
one of t he most basic synt ax uses of imread. This code r eads t he image
ngc6543a.jpg:
RGB = imread(ngc6543a.jpg);
You can wr it e (save) image dat a using t he imwrite funct ion. The st at ement s
load clown
imwrite(X,map,'clown.bmp')
cr eat e a BMP file cont aining t he clown image.
Writing a Graphics Image
When you save an image using imwrite, MATLABs default behavior is t o
aut omat ically r educe t he bit dept h t o uint8. Many of t he images used in
MATLAB ar e 8-bit , and most gr aphics file for mat images do not r equir e
double-pr ecision dat a. One except ion t o MATLABs r ule for saving t he image
dat a as uint8 is t hat PNG and TIFF images may be saved as uint16. Since
t hese t wo for mat s suppor t 16-bit dat a, you may over r ide MATLABs default
behavior by specifying uint16 as t he dat a t ype for imwrite. The following
example shows wr it ing a 16-bit PNG file using imwrite:
imwrite(I,'clown.png','BitDepth',16);
See t he imread and imwrite ent r ies in t he online MATLAB Funct ion Refer ence
for mor e infor mat ion.
Querying a Graphics File
The imfinfo funct ion enables you t o obt ain infor mat ion about gr aphics files
t hat ar e in any of t he st andar d for mat s list ed above. The infor mat ion you
obt ain depends on t he t ype of file, but it always includes at least t he following:
Name of t he file, including t he dir ect or y pat h if t he file is not in t he cur r ent
dir ect or y
File for mat
Ver sion number of t he file for mat
File modificat ion dat e
File size in byt es
Image widt h in pixels
Working with Image Data
1-13
Image height in pixels
Number of bit s per pixel
Image t ype: RGB (t r uecolor ), int ensit y (gr ayscale), or indexed
See t he imfinfo ent r y in t he online MATLAB Funct ion Refer ence for mor e
infor mat ion.
Converting The Image Type of Images
For cer t ain oper at ions, it is helpful t o conver t an image t o a differ ent image
t ype. For example, if you want t o filt er a color image t hat is st or ed as an
indexed image, you should fir st conver t it t o RGB for mat . When you apply t he
filt er t o t he RGB image, MATLAB filt er s t he int ensit y values in t he image, as
is appr opr iat e. If you at t empt t o filt er t he indexed image, MATLAB simply
applies t he filt er t o t he indices in t he indexed image mat r ix, and t he r esult s
may not be meaningful.
The Image Pr ocessing Toolbox pr ovides sever al funct ions t hat enable you t o
conver t any image t o anot her image t ype. These funct ions have mnemonic
names; for example, ind2gray conver t s an indexed image t o a gr ayscale
int ensit y for mat .
Not e t hat when you conver t an image fr om one for mat t o anot her , t he r esult ing
image may look differ ent fr om t he or iginal. For example, if you conver t a color
indexed image t o an int ensit y image, t he r esult ing image is gr ayscale, not
color . For mor e infor mat ion about how t hese funct ions wor k, see t heir online
r efer ence ent r ies.
The t able below summar izes t hese image conver sion funct ions.
Function Purpose
dither Cr eat e a binar y image fr om a gr ayscale int ensit y image
by dit her ing; cr eat e an indexed image fr om an RGB
image by dit her ing
gray2ind Cr eat e an indexed image fr om a gr ayscale int ensit y
image
grayslice Cr eat e an indexed image fr om a gr ayscale int ensit y
image by t hr esholding
1 Introduction
1-14
You can also per for m cer t ain conver sions just using MATLAB synt ax. For
example, you can conver t an int ensit y image t o RGB for mat by concat enat ing
t hr ee copies of t he or iginal mat r ix along t he t hir d dimension.
RGB = cat(3,I,I,I);
The r esult ing RGB image has ident ical mat r ices for t he r ed, gr een, and blue
planes, so t he image displays as shades of gr ay.
In addit ion t o t hese st andar d conver sion t ools, t her e ar e some funct ions t hat
r et ur n a differ ent image t ype as par t of t he oper at ion t hey per for m. For
example, t he r egion of int er est r out ines each r et ur n a binar y image t hat you
can use t o mask an indexed or int ensit y image for filt er ing or for ot her
oper at ions.
Color Space Conversions
The Image Pr ocessing Toolbox r epr esent s color s as RGB values, eit her dir ect ly
(in an RGB image) or indir ect ly (in an indexed image). However , t her e ar e
ot her met hods for r epr esent ing color s. For example, a color can be r epr esent ed
by it s hue, sat ur at ion, and value component s (HSV). Differ ent met hods for
r epr esent ing color s ar e called color spaces.
The t oolbox pr ovides a set of r out ines for conver t ing bet ween RGB and ot her
color spaces. The image pr ocessing funct ions t hemselves assume all color dat a
im2bw Cr eat e a binar y image fr om an int ensit y image,
indexed image, or RGB image, based on a luminance
t hr eshold
ind2gray Cr eat e a gr ayscale int ensit y image fr om an indexed
image
ind2gray Cr eat e an RGB image fr om an indexed image
mat2gray Cr eat e a gr ayscale int ensit y image fr om dat a in a
mat r ix, by scaling t he dat a
rgb2gray Cr eat e a gr ayscale int ensit y image fr om an RGB image
rgb2ind Cr eat e an indexed image fr om an RGB image
Function Purpose
Working with Image Data
1-15
is RGB, but you can pr ocess an image t hat uses a differ ent color space by fir st
conver t ing it t o RGB, and t hen conver t ing t he pr ocessed image back t o t he
or iginal color space. For mor e infor mat ion about color space conver sion
r out ines, see Chapt er 10.
Working with uint8 and uint16 Data
Use imread t o r ead gr aphics images int o MATLAB as uint8 or uint16 ar r ays;
use imshow t o display t hese images; and use imwrite t o save t hese images.
Most of t he funct ions in t he Image Pr ocessing Toolbox accept uint8 and uint16
input . See t he r efer ence descr ipt ions for infor mat ion about t he individual
funct ions.
MATLAB pr ovides limit ed suppor t for st or ing images as 8-bit or 16-bit
unsigned int eger s. In addit ion t o r eading and wr it ing uint8 and uint16 ar r ays,
MATLAB suppor t s t he following oper at ions:
Displaying dat a values
Indexing int o ar r ays using st andar d MATLAB subscr ipt ing
Reshaping, r eor der ing, and concat enat ing ar r ays, using funct ions such as
reshape, cat, and permute
Saving t o and loading fr om MAT-files
The all and any funct ions
Logical oper at or s and indexing
Relat ional oper at or s
The find funct ion. Not e t hat t he r et ur ned ar r ay is of class double.
Mathematical Operations Support for uint8 and uint16
The following MATLAB mat hemat ical oper at ions suppor t uint8 and uint16
dat a: conv2, convn, fft2, fftn, sum. In t hese cases, t he out put is always double.
If you at t empt t o per for m an unsuppor t ed oper at ion on one of t hese ar r ays, you
will r eceive an er r or . For example,
BW3 = BW1 + BW2
??? Function '+' not defined for variables of class 'uint8'.
1 Introduction
1-16
Converting The Data Types of Images
If you want t o per for m oper at ions t hat ar e not suppor t ed for uint8 or uint16
ar r ays, you can conver t t he dat a t o double pr ecision using t he MATLAB
funct ion, double. For example,
BW3 = double(BW1) + double(BW2);
However , conver t ing bet ween dat a t ypes changes t he way MATLAB and t he
t oolbox int er pr et t he image dat a. If you want t he r esult ing ar r ay t o be
int er pr et ed pr oper ly as image dat a, you need t o r escale or offset t he dat a when
you conver t it .
For easier conver sion of dat a t ypes, use one of t hese Toolbox funct ions:
im2double, im2uint8, and im2uint16. These funct ions aut omat ically handle
t he r escaling and offset t ing of t he or iginal dat a. For example, t his command
conver t s a double-pr ecision RGB image wit h dat a in t he r ange [0,1] t o a uint8
RGB image wit h dat a in t he r ange [0,255]:
RGB2 = im2uint8(RGB1);
Not e t hat when you conver t fr om one class t o anot her t hat uses fewer bit s t o
r epr esent number s, you gener ally lose some of t he infor mat ion in your image.
For example, consider what happens when you conver t a uint16 int ensit y
image t o a uint8 int ensit y image. A uint16 int ensit y image is capable of
st or ing up t o 65,536 dist inct shades of gr ay, but a uint8 int ensit y image can
st or e only 256 dist inct shades of gr ay. In or der t o per for m t he conver sion,
im2uint8 must quantize t he gr ay shades in t he or iginal image. In ot her wor ds,
all values fr om 0 t o 128 in t he or iginal image become 0 in t he uint8 image,
values fr om 129 t o 385 all become 1, and so on. This loss of infor mat ion is oft en
not a pr oblem, however , since 256 st ill exceeds t he number of shades of gr ay
t hat your eye is likely t o discer n.
Wit h indexed images, t he image mat r ix cont ains only indexes int o a color map,
r at her t han t he color dat a it self, so t her e is no quant izat ion of t he color dat a
possible dur ing t he conver sion. Ther efor e, it is not always possible t o conver t
an indexed image fr om one ar r ay class t o anot her . For example, a uint16 or
double indexed image wit h 300 color s cannot be conver t ed t o uint8, because
uint8 ar r ays have only 256 dist inct values. If you want t o per for m t his
conver sion, you must fir st r educe t he number of t he color s in t he image using
t he imapprox funct ion, as descr ibed in Chapt er 10, Over view. This funct ion
per for ms t he quant izat ion on t he color s in t he color map, t o r educe t he number
of dist inct color s in t he image.
Working with Image Data
1-17
For mor e infor mat ion about im2double, im2uint8, and im2uint16, see t heir
online r efer ence ent r ies.
Turning the Logical Flag on or off
As discussed on page 1-6, a uint8 binar y image must have it s logical flag on. If
you use im2uint8 t o conver t a binar y image of t ype double t o uint8, t his flag
is t ur ned on aut omat ically. If you do t he conver sion manually, however , you
must use t he logical funct ion t o t ur n on t he logical flag. For example,
B = logical(uint8(round(A)));
To t ur n t he logical flag off, you can use t he unar y plus oper at or . For example,
if A is a uint8 logical ar r ay:
B = +A;
Converting the Graphics File Format of an Image
Somet imes you will want t o change t he gr aphics for mat of an image, per haps
for compat ibilit y wit h anot her soft war e pr oduct . This pr ocess is ver y
st r aight for war d. For example, t o conver t an image fr om a BMP t o a PNG, load
t he BMP using imread, set t he dat a t ype t o uint8, uint16, or double, and t hen
save t he image using imwrite, wit h 'PNG' specified as your t ar get for mat . See
t he online Funct ion Refer ence descr ipt ions for imread and imwrite for t he
specifics of which bit dept hs ar e suppor t ed for t he differ ent gr aphics for mat s,
and for how t o specify t he for mat t ype when wr it ing an image t o file.
1 Introduction
1-18
Coordinate Systems
Locat ions in an image can be expr essed in var ious coor dinat e syst ems,
depending on cont ext . This sect ion discusses t he t wo main coor dinat e syst ems
used in t he Image Pr ocessing Toolbox, and t he r elat ionship bet ween t hem.
These syst ems ar e:
The pixel coor dinat e syst em
The spat ial coor dinat e syst em
Pixel Coordinates
Gener ally, t he most convenient met hod for expr essing locat ions in an image is
t o use pixel coor dinat es. In t his coor dinat e syst em, t he image is t r eat ed as a
gr id of discr et e element s, or der ed fr om t op t o bot t om and left t o r ight . For
example,
For pixel coor dinat es, t he fir st component r (t he r ow) incr eases downwar d,
while t he second component c (t he column) incr eases t o t he r ight . Pixel
coor dinat es ar e int eger values and r ange bet ween 1 and t he lengt h of t he r ow
or column.
Ther e is a one-t o-one cor r espondence bet ween pixel coor dinat es and t he
coor dinat es MATLAB uses for mat r ix subscr ipt ing. This cor r espondence makes
t he r elat ionship bet ween an images dat a mat r ix and t he way t he image
displays easy t o under st and. For example, t he dat a for t he pixel in t he fift h
r ow, second column is st or ed in t he mat r ix element (5,2).
r
c
1
2
3
1
2 3
Coordinate Systems
1-19
Spatial Coordinates
In t he pixel coor dinat e syst em, a pixel is t r eat ed as a discr et e unit , uniquely
ident ified by a single coor dinat e pair , such as (5,2). Fr om t his per spect ive, a
locat ion such as (5.3,2.2) is not meaningful.
At t imes, however , it is useful t o t hink of a pixel as a squar e pat ch, having ar ea.
Fr om t his per spect ive, a locat ion such as (5.3,2.2) is meaningful, and is dist inct
fr om (5,2). In t his spat ial coor dinat e syst em, locat ions in an image ar e posit ions
on a plane, and t hey ar e descr ibed in t er ms of x and y.
This figur e illust r at es t he spat ial coor dinat e syst em used for images. Not ice
t hat y incr eases downwar d.
This spat ial coor dinat e syst em cor r esponds quit e closely t o t he pixel coor dinat e
syst em in many ways. For example, t he spat ial coor dinat es of t he cent er point
of any pixel ar e ident ical t o t he pixel coor dinat es for t hat pixel.
Ther e ar e some impor t ant differ ences, however . In pixel coor dinat es, t he
upper -left cor ner of an image is (1,1), while in spat ial coor dinat es, t his locat ion
by default is (0.5,0.5). This differ ence is due t o t he pixel coor dinat e syst em
being discr et e, while t he spat ial coor dinat e syst em is cont inuous. Also, t he
upper -left cor ner is always (1,1) in pixel coor dinat es, but you can specify a
nondefault or igin for t he spat ial coor dinat e syst em. See Using a Nondefault
Spat ial Coor dinat e Syst em for mor e infor mat ion.
Anot her pot ent ially confusing differ ence is lar gely a mat t er of convent ion: t he
or der of t he hor izont al and ver t ical component s is r ever sed in t he not at ion for
t hese t wo syst ems. Pixel coor dinat es ar e expr essed as (r,c), while spat ial
coor dinat es ar e expr essed as (x,y). In t he online r efer ence ent r ies, when t he
y
x
1
2
3
1 2 3
0.5
1.5
2.5
3.5
1.5 2.5 0.5 3.5
1 Introduction
1-20
synt ax for a funct ion uses r and c, it r efer s t o t he pixel coor dinat e syst em.
When t he synt ax uses x and y, it r efer s t o t he spat ial coor dinat e syst em.
Using a Nondefault Spatial Coordinate System
By default , t he spat ial coor dinat es of an image cor r espond wit h t he pixel
coor dinat es. For example, t he cent er point of t he pixel in r ow 5, column 3 has
spat ial coor dinat es x=3, y=5. (Remember , t he or der of t he coor dinat es is
r ever sed.) This cor r espondence simplifies many of t he t oolbox funct ions
consider ably. Sever al funct ions pr imar ily wor k wit h spat ial coor dinat es r at her
t han pixel coor dinat es, but as long as you ar e using t he default spat ial
coor dinat e syst em, you can specify locat ions in pixel coor dinat es.
In some sit uat ions, however , you may want t o use a nondefault spat ial
coor dinat e syst em. For example, you could specify t hat t he upper -left cor ner of
an image is t he point (19.0,7.5), r at her t han (0.5,0.5). If you call a funct ion t hat
r et ur ns coor dinat es for t his image, t he coor dinat es r et ur ned will be values in
t his nondefault spat ial coor dinat e syst em.
To est ablish a nondefault spat ial coor dinat e syst em, you can specify t he XData
and YData image pr oper t ies when you display t he image. These pr oper t ies ar e
t wo-element vect or s t hat cont r ol t he r ange of coor dinat es spanned by t he
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 r ow by 200 column image, t he default XData is
[1 200], and t he default YData is [1 100]. The values in t hese vect or s ar e
act ually t he coor dinat es for t he cent er point s of t he fir st and last pixels (not t he
pixel edges), so t he act ual coor dinat e r ange spanned is slight ly lar ger ; for
inst ance, if XData is [1 200], t he x-axis r ange spanned by t he image is
[0.5 200.5].
Coordinate Systems
1-21
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 t he online MATLAB funct ion r efer ence for infor mat ion about funct ions in
t he Image Pr ocessing Toolbox t hat can est ablish nondefault spat ial coor dinat e
syst ems.
1 Introduction
1-22
2
Displaying Images
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . 2-2
St andard Di s play Te chni que s . . . . . . . . . . . . 2-3
Displaying Images wit h imshow . . . . . . . . . . . . 2-3
Displaying Indexed Images . . . . . . . . . . . . . . 2-5
Displaying Int ensit y Images . . . . . . . . . . . . . . 2-5
Displaying Binar y Images . . . . . . . . . . . . . . . 2-6
Displaying RGB Images . . . . . . . . . . . . . . . . 2-7
Displaying Images in Gr aphics Files . . . . . . . . . . . 2-8
Displaying Nonimage Dat a As an Int ensit y Image . . . . . 2-8
Speci al Di splay Techniques . . . . . . . . . . . . . 2-10
Adding a Color bar . . . . . . . . . . . . . . . . . . 2-10
Displaying Mult ifr ame Image Ar r ays . . . . . . . . . . 2-11
Displaying Mult iple Images . . . . . . . . . . . . . . 2-14
Zooming in on a Region of an Image . . . . . . . . . . . 2-16
Text ur e Mapping . . . . . . . . . . . . . . . . . . . 2-17
Pri nti ng Images . . . . . . . . . . . . . . . . . . 2-19
2 Displaying Images
2-2
Overview
The Image Pr ocessing Toolbox suppor t s a number of image display t echniques.
For example, t he funct ion imshow displays any image t ype wit h a single
funct ion call. Ot her funct ions handle mor e specialized display needs. This
chapt er descr ibes basic display t echniques and discusses t opics such as
mult iple image display and t ext ur e mapping. In addit ion, it includes
infor mat ion about pr int ing images.
Standard Display Techniques
2-3
Standard Display Techniques
In MATLAB, t he pr imar y way t o display images is by using t he image funct ion.
This funct ion cr eat es a Handle Gr aphics

image object , and it includes synt ax


for set t ing t he var ious pr oper t ies of t he object . MATLAB also includes t he
imagesc funct ion, which is similar t o image but which aut omat ically scales t he
input dat a.
The Image Pr ocessing Toolbox includes an addit ional display r out ine, imshow.
Like image and imagesc, t his funct ion cr eat es a Handle Gr aphics image object .
However , imshow also aut omat ically set s var ious Handle Gr aphics pr oper t ies
and at t r ibut es of t he image t o opt imize t he display.
This sect ion discusses displaying images using imshow. In gener al, imshow is
pr efer able t o image and imagesc for image pr ocessing applicat ions. For mor e
infor mat ion, see t he online r efer ence ent r ies for image and imagesc. These
funct ions ar e also descr ibed in mor e det ail in t he Using MATLAB Graphics
manual.
Displaying Images with imshow
When you display an image using t he imshow funct ion, MATLAB set s figur e,
axes, and image pr oper t ies t hat cont r ol t he way image dat a is int er pr et ed.
These pr oper t ies include t he image CData and CDataMapping pr oper t y, t he axes
CLim pr oper t y, and t he figur e Colormap pr oper t y. In addit ion, depending on t he
ar gument s you specify and t he set t ings of t oolbox pr efer ences, imshow may
also:
Set ot her figur e and axes pr oper t ies t o t ailor t he display. For example, axes
and t ick mar ks may not display.
Include or omit a bor der ar ound t he image.
Call t he truesize funct ion t o display t he image wit hout int er polat ion.
This sect ion descr ibes how you can cont r ol t he behavior of imshow. The sect ions
t hat follow it discuss how imshow displays specific image t ypes.
2 Displaying Images
2-4
Preferences
The Image Pr ocessing Toolbox includes a funct ion, iptsetpref, t hat you can
use t o set pr efer ences t hat affect t he behavior of imshow:
The ImshowBorder pr efer ence cont r ols whet her imshow leaves a bor der
bet ween t he axes cont aining t he image and t he edges of t he figur e.
The ImshowAxesVisible pr efer ence cont r ols whet her imshow displays
images wit h t he axes box and t ick labels.
The ImshowTruesize pr efer ence cont r ols whet her imshow calls t he truesize
funct ion.
To det er mine t he cur r ent value of a pr efer ence, use t he iptgetpref funct ion.
For mor e infor mat ion about t hese and ot her t oolbox pr efer ences, and t he
values t hey accept , see t he r efer ence ent r ies for iptsetpref and iptgetpref.
The truesize Function
The truesize funct ion assigns a single scr een pixel t o each image pixel. This
is gener ally t he pr efer r ed way t o display an image.
If you display an image wit hout calling truesize, t he image displays at t he
default axis size; MATLAB must use int er polat ion t o det er mine t he values for
display pixels t hat do not cor r espond t o element s in t he image mat r ix. (See
Int er polat ion in Chapt er 3 for a discussion of int er polat ion.)
In most sit uat ions, t he imshow command calls truesize aut omat ically. If you
do not want imshow t o call truesize (for example, if you display an image wit h
a small number of pixels), you can set t he ImshowTruesize pr efer ence t o
'manual'. For example,
iptsetpref('ImshowTruesize','manual')
You can also over r ide t he set t ing of t he ImshowTruesize pr efer ence for a single
imshow command. For example, t he command below pr event s imshow fr om
calling truesize, r egar dless of t he pr efer ence set t ing.
imshow(X,map,'notruesize')
For mor e infor mat ion see t he r efer ence descr ipt ions for imshow and truesize.
Standard Display Techniques
2-5
Displaying Indexed Images
To display an indexed image wit h imshow, you specify bot h t he image mat r ix
and t he color map.
imshow(X,map)
For each pixel in X, imshow displays t he color st or ed in t he cor r esponding r ow
of map. imshow set s t he Handle Gr aphics pr oper t ies t hat cont r ol how color s
display:
The image CData is set t o t he dat a in X.
The image CDataMapping pr oper t y is set t o direct.
The axes CLim pr oper t y does not apply, because CDataMapping is set t o
direct.
The figur e Colormap pr oper t y is set t o t he dat a in map.
The r elat ionship bet ween t he values in t he image mat r ix and t he color map
depends on whet her t he image mat r ix is of class double or uint8. If t he image
mat r ix is of class double, t he value 1 point s t o t he fir st r ow in t he color map, t he
value 2 point s t o t he second r ow, and so on. If t he image mat r ix is of class uint8
or uint16, t her e is an offset ; t he value 0 point s t o t he fir st r ow in t he color map,
t he value 1 point s t o t he second r ow, and so on. The offset is handled
aut omat ically by t he image object , and is not cont r olled t hr ough a Handle
Gr aphics pr oper t y.
Displaying Intensity Images
To display a gr ayscale int ensit y image, t he synt ax is:
imshow(I)
imshow displays t he image by scaling t he int ensit y values t o ser ve as indices
int o a gr ayscale color map. This is done as follows:
The image CData is set t o t he dat a in t he image mat r ix.
The image CDataMapping pr oper t y is set t o scaled.
The axes CLim pr oper t y is set t o [0 1] if t he image mat r ix is of class double,
[0 255] if t he mat r ix is of class uint8, or [0 65535] if it is of class uint16.
The figur e Colormap pr oper t y is set t o a gr ayscale color map whose values
r ange fr om black t o whit e.
2 Displaying Images
2-6
By default , t he number of levels of gr ay in t he color map is 256 on syst ems wit h
24-bit color , and 64 on ot her syst ems.
You can explicit ly specify t he number of gr ay levels wit h imshow. For example,
you can display an image I wit h 32 gr ay levels using:
imshow(I,32)
Not e t hat t his is not equivalent t o:
imshow(I,gray(32))
If you use t he lat t er synt ax, imshow int er pr et s t he values in I as indices int o a
color map and t her efor e does not set CDataMapping t o scaled.
Because MATLAB scales int ensit y images t o fill t he color map r ange, you can
use any size color map. Lar ger color maps enable you t o see mor e det ail, but t hey
also use up mor e color slot s. For infor mat ion about t he number of color slot s
available on your syst em, see page 2-14.
Displaying Binary Images
To display a binar y image, t he synt ax is:
imshow(BW)
If t he image mat r ix is of class double, imshow t r eat s a binar y image as an
int ensit y image, set t ing CDataMapping t o scaled, CLim t o [0 1], and Colormap
t o a gr ayscale color map. This means t hat t he 0 values in t he image mat r ix
display as black, and t he 1 values display as whit e.
If t he image mat r ix is of class uint8, t he behavior depends on whet her or not
t he mat r ix has it s logical flag on:
If t he logical flag is off, imshow t r eat s t he mat r ix as a uint8 int ensit y image,
set t ing CLim t o [0 255].
If t he logical flag is on, imshow set s CLim t o [0 1].
In gener al, t his means t hat a uint8 binar y image must have it s logical flag on
t o display pr oper ly. Ther efor e, all of t he t oolbox r out ines t hat r et ur n binar y
images r et ur n t hem as uint8 logical mat r ices.
imread r eads in an image as a uint8 logical ar r ay of 0s and 1s only if t he image
is st or ed in t he file wit h 1 bit per pixel. If a binar y image is st or ed in a file wit h
Standard Display Techniques
2-7
4 or 8 bit s per pixel, imread int er pr et s t his as a gr ayscale int ensit y image; t he
r esult ing ar r ay has values of 0 and 255, and t he logical flag is off. You can
conver t t his image t o a uint8 logical ar r ay using t he NOT EQUAL (~=)
oper at or in MATLAB.
BW2 = BW ~= 0;
Not e t hat t he t oolbox does not suppor t binar y images of class uint16.
Changing the Display Colors
You may pr efer t o inver t binar y images when you display t hem, so t hat 0
values display as whit e and 1 values display as black. To do t his, use t he NOT
(~) oper at or in MATLAB. For example,
imshow(~BW)
You can also display a binar y image using a color map. If t he image is of class
uint8, t he 0 values display as t he fir st color in t he color map, and t he 1 values
display as t he second color . For example, t he following command displays 0 as
r ed and 1 as blue.
imshow(BW,[1 0 0; 0 0 1])
If t he image is of class double, you need t o add 1 t o each value in t he image
mat r ix, because t her e is no offset in t he color map indexing.
imshow(BW + 1,[1 0 0; 0 0 1])
Displaying RGB Images
RGB images, also called truecolor images, r epr esent color values dir ect ly,
r at her t han t hr ough a color map.
To display an RGB image, t he synt ax is:
imshow(RGB)
RGB is m-by-n-by-3 ar r ay. For each pixel (r,c) in RGB, imshow displays t he color
r epr esent ed by t he t r iplet (r,c,1:3).
As wit h ot her image t ypes, MATLAB set s t he image CData t o t he dat a in t he
image ar r ay. However , in t his case CData is a t hr ee-dimensional ar r ay, r at her
t han a t wo-dimensional mat r ix. If CData is t hr ee-dimensional, MATLAB
2 Displaying Images
2-8
int er pr et s t he ar r ay as t r uecolor dat a, and ignor es t he values of t he
CDataMapping, CLim, and Colormap pr oper t ies.
An RGB image ar r ay can be of class double, uint8, or uint16:
If t he ar r ay is of class double, t he dat a values ar e in t he r ange [0,1].
If t he ar r ay is of class uint8, t he dat a r ange is [0,255].
If t he ar r ay is of class uint16, t he dat a r ange is [0,65535].
Syst ems t hat use 24 bit s per scr een pixel can display t r uecolor images dir ect ly,
because t hey allocat e 8 bit s (256 levels) each t o t he r ed, gr een, and blue color
planes. On syst ems wit h fewer color s, MATLAB displays t he image using a
combinat ion of color appr oximat ion and dit her ing. See Chapt er 10 for mor e
infor mat ion.
Displaying Images in Graphics Files
Gener ally, when you display an image, t he image dat a is st or ed as one or mor e
var iables in t he MATLAB wor kspace. However , if you have an image st or ed in
a gr aphics file t hat imread can r ead, you can display a file dir ect ly using t his
synt ax:
imshow filename
The file must be in t he cur r ent dir ect or y or on t he MATLAB pat h.
For example, t o display a file named flowers.tif:
imshow flowers.tif
This synt ax is ver y useful for scanning t hr ough images st or ed in gr aphics files.
Not e, however , t hat when you use t his synt ax, t he image dat a is not st or ed in
t he MATLAB wor kspace; if you want t o pr ocess t he image, you need t o use
imread t o r ead in t he dat a, or else use getimage t o get t he image dat a fr om t he
Handle Gr aphics image object . Also, if you use t his synt ax wit h a file
cont aining mor e t han one image, imshow displays only t he fir st image.
Displaying Nonimage Data As an Intensity Image
In some cases, you may have dat a you want t o display as an int ensit y image,
even t hough t he dat a is out side t he appr opr iat e r ange (i.e., [0,1] for double
ar r ays, [0,255] for uint8 ar r ays, or [0,65535] for uint16 ar r ays). For example,
Standard Display Techniques
2-9
if you filt er an int ensit y image, t he out put dat a may not fall in t he r ange of t he
or iginal dat a, but you may st ill want t o display t he r esult s as an image.
To display t his dat a as an image, you can specify t he dat a r ange dir ect ly, using:
imshow(I,[low high])
When you use t his synt ax, imshow set s t he axes CLim pr oper t y t o [low high].
CDataMapping is always scaled for int ensit y images, so t he image dat a is
scaled so t hat low cor r esponds t o t he fir st r ow of t he gr ayscale color map and
high cor r esponds t o t he last r ow.
If you use an empt y mat r ix ([]) for t he dat a r ange, imshow scales t he dat a
aut omat ically, set t ing low and high t o t he minimum and maximum values in
t he ar r ay. For example,
I = imread('testpat1.tif');
J = filter2([1 2;1 2],I);
imshow(J,[])
2 Displaying Images
2-10
Special Display Techniques
In addit ion t o imshow, t he t oolbox includes funct ions t hat per for m specialized
display oper at ions, or exer cise mor e dir ect cont r ol over t he display for mat .
These funct ions, t oget her wit h t he MATLAB gr aphics funct ions, pr ovide a
r ange of image display opt ions.
This sect ion includes t he following t opics:
Adding a color bar t o an image display
Displaying mult ifr ame image ar r ays
Displaying mult iple images
Zooming in on a r egion of an image
Text ur e mapping an image ont o a sur face
Adding a Colorbar
You can use t he colorbar funct ion t o add a color bar t o an axes object . If you
add a color bar t o an axes object t hat cont ains an image object , t he color bar
indicat es t he dat a values t hat t he differ ent color s in t he image cor r espond t o.
Seeing t he cor r espondence bet ween dat a values and t he color s displayed is
especially useful if you ar e displaying nonimage dat a as an image, as descr ibed
Special Display Techniques
2-11
on page 2-8. In t he example below, you filt er a gr ayscale image of class uint8,
and t he r esult ing dat a is no longer in t he r ange [0,255].
I = imread('saturn.tif');
h = [1 2 1; 0 0 0; 1 2 1];
I2 = filter2(h,I);
imshow(I2,[]), colorbar
Displaying Multiframe Image Arrays
To view t he images in a mult ifr ame ar r ay, you can use any of t hese opt ions:
Displaying Fr ames Individually, using t he imshow funct ion
Displaying All Fr ames at Once, using t he montage funct ion
Conver t ing t he Ar r ay t o a Movie, using t he immovie funct ion
Displaying Frames Individually
To view an individual fr ame, call imshow and specify t he fr ame using st andar d
MATLAB indexing not at ion. For example, t o view t he sevent h fr ame in t he
int ensit y ar r ay I:
imshow(I(:,:,:,7))
2 Displaying Images
2-12
Displaying All Frames at Once
To view all of t he fr ames in a mult ifr ame ar r ay at one t ime, use t he montage
funct ion. montage divides a figur e int o mult iple display r egions and displays
each image in a separ at e r egion.
The synt ax for montage is similar t o t he imshow synt ax. To display a
mult ifr ame int ensit y image, t he synt ax is:
montage(I)
To display a mult ifr ame indexed image, t he synt ax is:
montage(X,map)
Not e t hat all of t he fr ames in a mult ifr ame indexed ar r ay must use t he same
color map.
The commands below display a mult ifr ame image ar r ay. Not ice t hat montage
displays images in a r ow-wise manner . The fir st fr ame appear s in t he fir st
Special Display Techniques
2-13
posit ion of t he fir st r ow, t he next fr ame in t he second posit ion of t he fir st r ow,
and so on. montage ar r anges t he fr ames so t hat t hey r oughly for m a squar e.
load mri
montage(D,map)
Converting the Array to a Movie
To cr eat e a MATLAB movie fr om a mult ifr ame image ar r ay, use t he immovie
funct ion. This funct ion wor ks only wit h indexed images; if you want t o conver t
anot her t ype of image ar r ay t o a movie, you must fir st conver t it t o an indexed
image, using one of t he conver sion funct ions descr ibed in Chapt er 1.
This call cr eat es a movie fr om t he mult ifr ame indexed image shown above:
mov = immovie(D,map);
2 Displaying Images
2-14
You can play t he movie in MATLAB using t he movie funct ion.
movie(mov)
Not e t hat when you play t he movie, you need t o supply t he color map used by
t he or iginal image ar r ay. For example,
mov = immovie(D,map);
colormap(map), movie(mov)
Displaying Multiple Images
MATLAB does not place any r est r ict ions on t he number of images you can
display simult aneously. However , t her e ar e usually syst em limit at ions t hat
ar e dependent on t he comput er har dwar e you ar e using.
The main limit at ion is t he number of color s your syst em can display. This
number depends pr imar ily on t he number of bit s t hat ar e used t o st or e t he color
infor mat ion for each pixel. Most syst ems use eit her 8, 16, or 24 bit s per pixel.
If you ar e using a syst em wit h 16 or 24 bit s per pixel, you ar e unlikely t o r un
int o any pr oblems, r egar dless of t he number of images you display. However ,
if your syst em uses 8 bit s per pixel, it can display a maximum of 256 differ ent
color s, so you can quickly r un out of color slot s if you display mult iple images.
(Act ually, t he t ot al number of color s you can display is slight ly fewer t han 256,
because some color slot s ar e r eser ved for Handle Gr aphics object s. The
oper at ing syst em usually r eser ves a few color s as well.)
To det er mine t he number of bit s per pixel on your syst em, ent er t his command:
get(0,'ScreenDepth')
See Chapt er 10 for mor e infor mat ion about wor king wit h differ ent color dept hs.
This sect ion discusses met hods you can use t o display mult iple images at t he
same t ime, and includes infor mat ion about wor king ar ound syst em limit at ions.
This sect ion discusses:
Displaying each image in a separ at e figur e
Displaying mult iple images in t he same figur e
Displaying Each Image in a Separate Figure
The simplest way t o display mult iple images is t o display t hem in differ ent
figur e windows. imshow always displays in t he cur r ent figur e, so if you display
Special Display Techniques
2-15
t wo images in succession, t he second image r eplaces t he fir st image. Ther efor e,
if you want t o display t wo or mor e images in separ at e windows, you must
explicit ly cr eat e a new empt y figur e befor e calling imshow for t he second and
subsequent images. For example,
imshow(I)
figure, imshow(I2)
When you use t his appr oach, t he figur es you cr eat e ar e empt y init ially, so t he
images ar e displayed using truesize.
If you have an 8-bit display, you must make sur e t hat t he t ot al number of
color map ent r ies does not exceed 256. For example, if you t r y t o display t hr ee
images, each having a differ ent color map wit h 128 ent r ies, at least one of t he
images will display wit h t he wr ong color s. (If all t hr ee images use t he same
color map, t her e will not be a pr oblem, because only 128 color slot s ar e used.)
Not e t hat int ensit y images ar e displayed using color maps, so t he color slot s
used by t hese image count t owar d t he 256-color t ot al.
One way t o avoid t hese display pr oblems is t o manipulat e t he color maps t o use
fewer color s. Ther e ar e var ious ways t o do t his, such as using t he imapprox
funct ion. See Chapt er 10 for infor mat ion about r educing t he number of color s
used by an image.
Anot her solut ion is t o conver t images t o RGB (t r uecolor ) for mat for display.
The color s used by t r uecolor images do not count t owar d t he 256-color t ot al,
because MATLAB aut omat ically uses dit her ing and color appr oximat ion t o
display t hese images.
For example, t o display an indexed image as an RGB image:
imshow(ind2rgb(X,map))
To display an int ensit y image as an RGB image:
imshow(cat(3,I,I,I))
Displaying Multiple Images in the Same Figure
You can display mult iple images in a single figur e window wit h some
limit at ions. This discussion shows you how t o do t his by using imshow or
subimage in conjunct ion wit h t he subplot funct ion. subplot divides a figur e
int o mult iple display r egions. The synt ax of subplot is:
subplot(m,n,p)
2 Displaying Images
2-16
This call divides t he figur e int o an m-by-n mat r ix of display r egions and makes
t he p-t h display r egion act ive. For example, you can display t wo images side by
side using:
subplot(1,2,1), imshow(X1,map)
subplot(1,2,2), imshow(X2,map)
Note: When displaying mult iple images in t he same figur e wit h imshow, all
images will use t he color map of t he last image displayed by imshow. This will
usually cause an imper fect display because t wo or mor e images r ar ely shar e
an ident ical color map. To avoid t his pr oblem, you can use subimage as shown
below.
The funct ion subimage, which displays images in subplot s, may be used in
place of imshow. For example, t o display t wo images in t he same figur e:
subplot(1,2,1), subimage(X1,map1)
subplot(1,2,2), subimage(X2,map2)
Bot h images will display cor r ect ly, even if t hey have differ ent color maps
because subimage conver t s t he images t o RGB befor e displaying.
Zooming in on a Region of an Image
The zoom command enables you t o examine t he det ails of an image by using t he
mouse t o zoom in or out . When you zoom in, t he figur e r emains t he same size,
but only a por t ion of t he image is displayed, at a higher magnificat ion. (zoom
wor ks by changing t he axis limit s; it does not change t he image dat a in t he
figur e.)
To t ur n zoom mode on, t ype:
zoom on
Special Display Techniques
2-17
Ther e ar e t wo ways t o zoom in on an image:
Click on a spot in t he image by placing t he cur sor on t he spot and t he
pr essing t he left mouse but t on. The view changes aut omat ically. The cent er
of t he new view is t he spot wher e you clicked.
Select a r egion by clicking on t he image, holding down t he mouse but t on, and
dr agging t he mouse. A dot t ed r ect angle appear s. When you r elease t he
mouse but t on, t he r egion enclosed by t he r ect angle is displayed.
To zoom out , click on t he image wit h t he r ight mouse but t on. (If you have a
single-but t on mouse, hold down t he Shi ft key and click.) To zoom out
complet ely and r est or e t he or iginal view, ent er :
zoom out
To t ur n zoom mode off:
zoom off
Texture Mapping
When you use t he imshow command, MATLAB displays t he image in a
t wo-dimensional view. However , it is also possible t o display an image on a
par amet r ic sur face, such as a spher e, or below a sur face plot . The warp funct ion
cr eat es t hese displays by texture mapping t he image. Text ur e mapping is a
pr ocess t hat maps an image ont o a sur face gr id using bilinear int er polat ion.
2 Displaying Images
2-18
This example t ext ur e maps an image of a t est pat t er n ont o a cylinder .
[x,y,z] = cylinder;
I = imread('testpat1.tif');
warp(x,y,z,I);
For mor e infor mat ion about t ext ur e mapping, see t he r efer ence ent r y for t he
warp funct ion.
Printing Images
2-19
Printing Images
If you want t o out put a MATLAB image t o use it in anot her applicat ion (such
as a wor d-pr ocessing pr ogr am or gr aphics edit or ), use imwrite t o cr eat e a file
in t he appr opr iat e for mat .
If you want t o pr int t he cont ent s of a MATLAB figur e (including nonimage
element s such as labels), use t he MATLAB print command, or choose t he
Pri nt opt ion fr om t he Fi le menu of t he figur e window. If you pr oduce out put
t his way, t he r esult s r eflect t he set t ings of var ious Handle Gr aphics pr oper t ies.
In some cases, you may need t o change t he set t ings of cer t ain pr oper t ies t o get
t he r esult s you want .
Her e ar e some t ips t hat may be helpful when you pr int images:
Image color s pr int as shown on t he scr een. This means t hat images do not
obey t he InvertHardcopy figur e pr oper t y.
To ensur e t hat pr int ed images have t he pr oper size and aspect r at io,
you should set t he figur es PaperPositionMode pr oper t y t o auto. When
PaperPositionMode is set t o auto, t he widt h and height of t he pr int ed figur e
ar e det er mined by t he figur es dimensions on t he scr een. By default , t he
value of PaperPositionMode is manual. If you want t he default value of
PaperPositionMode t o be auto, ent er t his line in your startup.m file:
set(0,'DefaultFigurePaperPositionMode','auto')
For mor e infor mat ion about pr int ing and about Handle Gr aphics, see t he Using
MATLAB Graphics manual. For a complet e list of opt ions for t he print
command, ent er help print at t he MATLAB command line pr ompt .
2 Displaying Images
2-20
3
Geomet r ic Oper at ions
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . 3-2
Interpolati on . . . . . . . . . . . . . . . . . . . 3-3
Image Types . . . . . . . . . . . . . . . . . . . . 3-4
Image Resi zi ng . . . . . . . . . . . . . . . . . . . 3-5
Image Rotati on . . . . . . . . . . . . . . . . . . . 3-6
Image Croppi ng . . . . . . . . . . . . . . . . . . 3-7
3 Geometric Operations
3-2
Overview
This chapt er descr ibes some basic image pr ocessing t ools, t he geomet r ic
funct ions. These funct ions modify t he geomet r y of an image by r esizing,
r ot at ing, or cr opping t he image. These funct ions suppor t all image t ypes.
The chapt er begins wit h a discussion of interpolation, an oper at ion common t o
most of t he geomet r ic funct ions. It t hen discusses each of t he geomet r ic
funct ions separ at ely, and shows how t o apply t hem t o sample images.
Interpolation
3-3
Interpolation
The imresize and imrotate geomet r ic funct ions use t wo-dimensional
int er polat ion as par t of t he oper at ions t hey per for m. (The improfile image
analysis funct ion also uses int er polat ion. See Chapt er 7 for infor mat ion about
t his funct ion.) Int er polat ion is t he pr ocess by which t he soft war e r esamples t he
image dat a t o det er mine values bet ween defined pixels. For example, if you
r esize an image so it cont ains mor e pixels t han it did or iginally, t he soft war e
obt ains values for t he addit ional pixels t hr ough int er polat ion.
The Image Pr ocessing Toolbox pr ovides t hr ee int er polat ion met hods:
Near est neighbor int er polat ion
Bilinear int er polat ion
Bicubic int er polat ion
The int er polat ion met hods all wor k in a fundament ally similar way. In each
case, t o det er mine t he value for an int er polat ed pixel, you find t he point in t he
input image t hat t he out put pixel cor r esponds t o. You t hen assign a value t o
t he out put pixel by comput ing a weight ed aver age of some set of pixels in t he
vicinit y of t he point . The weight ings ar e based on t he dist ance each pixel is
fr om t he point .
The met hods differ in t he set of pixels t hat ar e consider ed:
For near est neighbor int er polat ion, t he out put pixel is assigned t he value of
t he pixel t hat t he point falls wit hin. No ot her pixels ar e consider ed.
For bilinear int er polat ion, t he out put pixel value is a weight ed aver age of
pixels in t he near est 2-by-2 neighbor hood.
For bicubic int er polat ion, t he out put pixel value is a weight ed aver age of
pixels in t he near est 4-by-4 neighbor hood.
The number of pixels consider ed affect s t he complexit y of t he comput at ion.
Ther efor e t he bilinear met hod t akes longer t han near est neighbor
int er polat ion, and t he bicubic met hod t akes longer t han bilinear . However , t he
gr eat er t he number of pixels consider ed, t he mor e accur at e t he effect is, so
t her e is a t r adeoff bet ween pr ocessing t ime and qualit y.
3 Geometric Operations
3-4
Image Types
The funct ions t hat use int er polat ion t ake an ar gument t hat specifies t he
int er polat ion met hod. For t hese funct ions, t he default met hod is near est
neighbor int er polat ion. This met hod pr oduces accept able r esult s for all image
t ypes, and is t he only met hod t hat is appr opr iat e for indexed images. For
int ensit y and RGB images, however , you should gener ally specify bilinear or
bicubic int er polat ion, because t hese met hods pr oduce bet t er r esult s t han
near est neighbor int er polat ion.
For RGB images, int er polat ion is per for med on t he r ed, gr een, and blue image
planes individually.
For binar y images, int er polat ion has effect s t hat you should be awar e of. If you
use bilinear or bicubic int er polat ion, t he comput ed values for t he pixels in t he
out put image will not all be 0 or 1. The effect on t he r esult ing out put image
depends on t he class of t he input image:
If t he class of t he input image is double, t he out put image is a gr ayscale
image of class double. The out put image is not binar y, because it includes
values ot her t han 0 and 1.
If t he class of t he input image is uint8, t he out put image is a binar y image
of class uint8. The int er polat ed pixel values ar e r ounded off t o 0 and 1 so t he
out put image can be of class uint8.
If you use near est neighbor int er polat ion, t he r esult is always binar y, because
t he values of t he int er polat ed pixels ar e t aken dir ect ly fr om pixels in t he input
image.
Image Resizing
3-5
Image Resizing
The t oolbox funct ion imresize changes t he size of an image using a specified
int er polat ion met hod. If you do not specify an int er polat ion met hod, t he
funct ion uses near est neighbor int er polat ion.
You can use imresize t o r esize an image by a specific magnificat ion fact or . To
enlar ge an image, specify a fact or gr eat er t han 1. For example, t he command
below doubles t he number of pixels in X in each dir ect ion.
Y = imresize(X,2)
To r educe an image, specify a number bet ween 0 and 1 as t he magnificat ion
fact or .
You can also specify t he act ual size of t he out put image. The command below
cr eat es an out put image of size 100-by-150.
Y = imresize(X,[100 150])
If t he specified size does not pr oduce t he same aspect r at io as t he input image
has, t he out put image will be dist or t ed.
If you r educe t he image size and use bilinear or bicubic int er polat ion, imresize
applies a lowpass filt er t o t he image befor e int er polat ion. This r educes t he
effect of Moir patterns, r ipple pat t er ns t hat r esult fr om aliasing dur ing
r esampling. Not e, however , t hat even wit h lowpass filt er ing, t he r esizing
oper at ion can int r oduce ar t ifact s, because infor mat ion is always lost when you
r educe t he size of an image.
imresize does not apply a lowpass filt er if near est neighbor int er polat ion is
used, unless you explicit ly specify t he filt er . This int er polat ion met hod is
pr imar ily used for indexed images, and lowpass filt er ing is not appr opr iat e for
t hese images.
For infor mat ion about specifying a differ ent filt er , see t he online r efer ence
ent r y for imresize.
3 Geometric Operations
3-6
Image Rotation
The imrotate funct ion r ot at es an image, using a specified int er polat ion
met hod and r ot at ion angle. If you do not specify an int er polat ion met hod, t he
funct ion uses near est neighbor int er polat ion.
You specify t he r ot at ion angle in degr ees. If you specify a posit ive value,
imrotate r ot at es t he image count er clockwise; if you specify a negat ive value,
imrotate r ot at es t he image clockwise.
For example, t hese commands r ot at e an image 35 count er clockwise:
I = imread('ic.tif');
J = imrotate(I,35,'bilinear');
imshow(I)
figure, imshow(J)
In or der t o include t he ent ir e or iginal image, imrotate pads t he out side wit h
0s. This cr eat es t he black backgr ound in J and r esult s in t he out put image
being lar ger t han t he input image.
imrotate has an opt ion for cr opping t he out put image t o t he same size as t he
input image. See t he online r efer ence ent r y for imrotate for mor e infor mat ion.
Image Cropping
3-7
Image Cropping
The funct ion imcrop ext r act s a r ect angular por t ion of an image. You can
specify t he cr op r ect angle t hr ough input ar gument s, or select it wit h a mouse.
If you call imcrop wit hout specifying t he cr op r ect angle, t he cur sor changes t o
a cr oss hair when it is over t he image. Click on one cor ner of t he r egion you
want t o select , and while holding down t he mouse but t on, dr ag acr oss t he
image. imcrop dr aws a r ect angle ar ound t he ar ea you ar e select ing. When you
r elease t he mouse but t on, imcrop cr eat es a new image fr om t he select ed r egion.
In t his example, you display an image and call imcrop. The r ect angle you select
is shown in r ed.
imshow ic.tif
I = imcrop;
Now display t he cr opped image:
imshow(I)
If you do not pr ovide any out put ar gument s, imcrop displays t he image in a
new figur e.
3 Geometric Operations
3-8
4
Neighbor hood and Block
Oper at ions
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . 4-2
Types of Block Pr ocessing Oper at ions . . . . . . . . . . 4-2
Slidi ng Nei ghborhood Operati ons . . . . . . . . . . 4-4
Padding of Bor der s . . . . . . . . . . . . . . . . . . 4-5
Linear and Nonlinear Filt er ing . . . . . . . . . . . . . 4-5
Di s ti nct Block Ope rat i ons . . . . . . . . . . . . . . 4-8
Over lap . . . . . . . . . . . . . . . . . . . . . . 4-9
Column Processing . . . . . . . . . . . . . . . . . 4-11
Sliding Neighbor hoods . . . . . . . . . . . . . . . . 4-11
Dist inct Blocks . . . . . . . . . . . . . . . . . . . 4-12
4 Neighborhood and Block Operations
4-2
Overview
Cer t ain image pr ocessing oper at ions involve pr ocessing an image in sect ions
called blocks, r at her t han pr ocessing t he ent ir e image at once. For example,
many linear filt er ing oper at ions and binar y image oper at ions wor k t his way.
The Image Pr ocessing Toolbox pr ovides sever al funct ions for specific
oper at ions t hat wor k wit h blocks; for example, t he dilate funct ion for binar y
image dilat ion. In addit ion, t he t oolbox pr ovides mor e gener ic funct ions for
pr ocessing an image in blocks. This chapt er discusses t hese gener ic block
pr ocessing funct ions.
To use one of t he funct ions descr ibed in t his chapt er , you supply infor mat ion
about t he size of t he blocks, and specify a separ at e funct ion t o use t o pr ocess
t he blocks. The block pr ocessing funct ion does t he wor k of br eaking t he input
image int o blocks, calling t he specified funct ion for each block, and
r eassembling t he r esult s int o an out put image.
Types of Block Processing Operations
Using t hese funct ions, you can per for m var ious block pr ocessing oper at ions,
including sliding neighborhood operations and distinct block operations:
In a sliding neighbor hood oper at ion, t he input image is pr ocessed in a
pixelwise fashion. That is, for each pixel in t he input image, some oper at ion
is per for med t o det er mine t he value of t he cor r esponding pixel in t he out put
image. The oper at ion is based on t he values of a block of neighbor ing pixels.
In a dist inct block oper at ion, t he input image is pr ocessed a block at a t ime.
That is, t he image is divided int o r ect angular blocks, and some oper at ion is
per for med on each block individually t o det er mine t he values of t he pixels in
t he cor r esponding block of t he out put image.
In addit ion, t he t oolbox pr ovides funct ions for column processing operations.
These oper at ions ar e not act ually dist inct fr om block oper at ions; inst ead, t hey
ar e a way of speeding up block oper at ions by r ear r anging blocks int o mat r ix
columns.
Not e t hat even if you do not use t he block pr ocessing funct ions descr ibed in t his
chapt er , t he infor mat ion her e may be useful t o you, as it includes concept s
fundament al t o many ar eas of image pr ocessing. In par t icular , t he discussion
of sliding neighbor hood oper at ions is applicable t o linear filt er ing and binar y
Overview
4-3
mor phological oper at ions. See Chapt er 5, Linear Filt er ing and Filt er Design
and Chapt er 8, Binar y Image Oper at ions for infor mat ion about t hese
applicat ions.
4 Neighborhood and Block Operations
4-4
Sliding Neighborhood Operations
A sliding neighbor hood oper at ion is an oper at ion t hat is per for med a pixel at a
t ime, wit h t he value of any given pixel in t he out put image being det er mined
by applying some algor it hm t o t he values of t he cor r esponding input pixels
neighborhood. A pixels neighbor hood is some set of pixels, defined by t heir
locat ions r elat ive t o t hat pixel, which is called t he center pixel. The
neighbor hood is a r ect angular block, and as you move fr om one element t o t he
next in an image mat r ix, t he neighbor hood block slides in t he same dir ect ion.
The figur e below shows t he neighbor hood blocks for some of t he element s in a
6-by-5 mat r ix wit h 2-by-3 sliding blocks. The cent er pixel for each
neighbor hood is mar ked wit h a dot .
The cent er pixel is t he act ual pixel in t he input image being pr ocessed by t he
oper at ion. If t he neighbor hood has an odd number of r ows and columns, t he
cent er pixel is act ually in t he cent er of t he neighbor hood. If one of t he
dimensions has even lengt h, t he cent er pixel is just t o t he left of cent er or just
above cent er . For example, in a 2-by-2 neighbor hood, t he cent er pixel is t he
upper left one.
For any m-by-n neighbor hood, t he cent er pixel is:
floor(([m n]+1)/2)
In t he 2-by-3 block shown in t he figur e above, t he cent er pixel is (1,2), t he pixel
in t he second column of t he t op r ow of t he neighbor hood.
Sliding Neighborhood Operations
4-5
A sliding neighbor hood oper at ion pr oceeds like t his:
1 Select a single pixel.
2 Det er mine t he pixels neighbor hood.
3 Apply a funct ion t o t he values of t he pixels in t he neighbor hood. This
funct ion must r et ur n a scalar .
4 Find t he pixel in t he out put image whose posit ion cor r esponds t o t hat of t he
cent er pixel in t he input image. Set t his out put pixel t o t he value r et ur ned
by t he funct ion.
5 Repeat st eps 1 t hr ough 4 for each pixel in t he input image.
For example, suppose t he figur e above r epr esent s an aver aging oper at ion. The
funct ion might sum t he values of t he six neighbor hood pixels and t hen divide
by 6. The r esult is t he value of t he out put pixel.
Padding of Borders
As t he figur e on page 4-4 shows, some of t he pixels in a neighbor hood may be
missing, especially if t he cent er pixel is on t he bor der of t he image. Not ice t hat
in t he figur e, t he upper left and bot t om r ight neighbor hoods include pixels
t hat ar e not par t of t he image.
To pr ocess t hese neighbor hoods, sliding neighbor hood oper at ions pad t he
bor der s of t he image, usually wit h 0s. In ot her wor ds, t hese funct ions pr ocess
t he bor der pixels by assuming t hat t he image is sur r ounded by addit ional r ows
and columns of 0s. These r ows and columns do not become par t of t he out put
image and ar e used only as par t s of t he neighbor hoods of t he act ual pixels in
t he image.
Linear and Nonlinear Filtering
You can use sliding neighbor hood oper at ions t o implement many kinds of
filt er ing oper at ions. One example of a sliding neighbor oper at ion is
convolut ion, which is used t o implement linear filt er ing. MATLAB pr ovides t he
conv2 and filter2 funct ions for per for ming convolut ion. See Chapt er 5,
Linear Filt er ing and Filt er Design for mor e infor mat ion about t hese
funct ions.
4 Neighborhood and Block Operations
4-6
In addit ion t o convolut ion, t her e ar e many ot her filt er ing oper at ions you can
implement t hr ough sliding neighbor hoods. Many of t hese oper at ions ar e
nonlinear in nat ur e. For example, you can implement a sliding neighbor hood
oper at ion wher e t he value of an out put pixel is equal t o t he st andar d deviat ion
of t he values of t he pixels in t he input pixels neighbor hood.
You can use t he nlfilter funct ion t o implement a var iet y of sliding
neighbor hood oper at ions. nlfilter t akes as input ar gument s an image, a
neighbor hood size, and a funct ion t hat r et ur ns a scalar , and r et ur ns an image
of t he same size as t he input image. The value of each pixel in t he out put image
is comput ed by passing t he cor r esponding input pixels neighbor hood t o t he
funct ion. For example, t his call comput es each out put pixel by t aking t he
st andar d deviat ion of t he values of t he input pixels 3-by-3 neighbor hood (t hat
is, t he pixel it self and it s eight cont iguous neighbor s):
I2 = nlfilter(I,[3 3],'std2');
You can wr it e an M-file t o implement a specific funct ion, and t hen use t his
funct ion wit h nlfilter. For example, t his command pr ocesses t he mat r ix I in
2-by-3 neighbor hoods wit h a funct ion called myfun.m:
nlfilter(I,[2 3],'myfun');
You can also use an inline funct ion; in t his case, t he funct ion name appear s in
t he nlfilter call wit hout quot at ion mar ks. For example,
f = inline('sqrt(min(x(:)))');
I2 = nlfilter(I,[2 2],f);
Sliding Neighborhood Operations
4-7
The example below uses nlfilter t o set each pixel t o t he maximum value in
it s 3-by-3 neighbor hood.
I = imread('tire.tif');
f = inline('max(x(:))');
I2 = nlfilter(I,[3 3],f);
imshow(I);
figure, imshow(I2);
Many oper at ions t hat nlfilter can implement r un much fast er if t he
comput at ions ar e per for med on mat r ix columns r at her t han r ect angular
neighbor hoods. For infor mat ion about t his appr oach, see t he discussion of t he
colfilt funct ion on page 4-11.
4 Neighborhood and Block Operations
4-8
Distinct Block Operations
Distinct blocks ar e r ect angular par t it ions t hat divide a mat r ix int o m-by-n
sect ions. Dist inct blocks over lay t he image mat r ix st ar t ing in t he upper -left
cor ner , wit h no over lap. If t he blocks dont fit exact ly over t he image, t he
t oolbox adds zer o padding so t hat t hey do.
The figur e below shows a 15-by-30 mat r ix divided int o 4-by-8 blocks.
The zer o padding pr ocess adds 0s t o t he bot t om and r ight of t he image mat r ix,
as needed. Aft er zer o padding, t he mat r ix is size 16-by-32.
The funct ion blkproc per for ms dist inct block oper at ions. blkproc ext r act s
each dist inct block fr om an image and passes it t o a funct ion you specify.
blkproc assembles t he r et ur ned blocks t o cr eat e an out put image.
For example, t he command below pr ocesses t he mat r ix I in 4-by-6 blocks wit h
t he funct ion myfun.
I2 = blkproc(I,[4 6],'myfun');
You can specify t he funct ion as an inline funct ion; in t his case, t he funct ion
name appear s in t he blkproc call wit hout quot at ion mar ks. For example,
f = inline('mean2(x)*ones(size(x))');
I2 = blkproc(I,[4 6],f);
Distinct Block Operations
4-9
The example below uses blkproc t o set ever y pixel in each 8-by-8 block of an
image mat r ix t o t he aver age of t he element s in t hat 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);
Not ice t hat t he inline funct ion comput es t he mean of t he block and t hen
mult iplies t he r esult by a mat r ix of ones, so t hat t he out put block is t he same
size as t he input block. As a r esult , t he out put image is t he same size as t he
input image. blkproc does not r equir e t hat t he images be t he same size;
however , if t his is t he r esult you want , you must make sur e t hat t he funct ion
you specify r et ur ns blocks of t he appr opr iat e size.
Overlap
When you call blkproc t o define dist inct blocks, you can specify t hat t he blocks
over lap each ot her , t hat is, you can specify ext r a r ows and columns of pixels
out side t he block whose values ar e t aken int o account when pr ocessing t he
block. When t her e is an over lap, blkproc passes t he expanded block (including
t he over lap) t o t he specified funct ion.
The following figur e shows t he over lap ar eas for some of t he blocks in a
15-by-30 mat r ix wit h 1-by-2 over laps. Each 4-by-8 block has a one-r ow over lap
above and below, and a t wo-column over lap on each side. In t he figur e, shading
4 Neighborhood and Block Operations
4-10
indicat es t he over lap. The 4-by-8 blocks over lay t he image mat r ix st ar t ing in
t he upper -left cor ner .
To specify t he over lap, you pr ovide an addit ional input ar gument t o blkproc.
To pr ocess t he blocks in t he figur e above wit h t he funct ion myfun, t he call is:
B = blkproc(A,[4 8],[1 2],'myfun')
Over lap oft en incr eases t he amount of zer o padding needed. For example, in
t he figur e on page 4-8, t he or iginal 15-by-30 mat r ix became a 16-by-32 mat r ix
wit h zer o padding. When t he 15-by-30 mat r ix includes a 1-by-2 over lap, t he
padded mat r ix becomes an 18-by-36 mat r ix. The out er most r ect angle in t he
figur e delineat es t he new boundar ies of t he image aft er padding has been
added t o accomodat e t he over lap plus block pr ocessing. Not ice t hat padding has
now been added t o t he left and t op of t he or iginal image, not just t o t he r ight
and bot t om, as in t he nonover lap block pr ocessing shown pr eviously.
Column Processing
4-11
Column Processing
The t oolbox pr ovides funct ions t hat you can use t o pr ocess sliding
neighbor hoods or dist inct blocks as columns. This appr oach is useful for
oper at ions t hat MATLAB per for ms columnwise; in many cases, column
pr ocessing can r educe t he execut ion t ime r equir ed t o pr ocess an image.
For example, suppose t he oper at ion you ar e per for ming involves comput ing t he
mean of each block. This comput at ion is much fast er if you fir st r ear r ange t he
blocks int o columns, because you can comput e t he mean of ever y column wit h
a single call t o t he mean funct ion, r at her t han calling mean for each block
individually.
You can use t he colfilt funct ion t o implement column pr ocessing. This
funct ion:
1 Reshapes each sliding or dist inct block of an image mat r ix int o a column in
a t empor ar y mat r ix
2 Passes t he t empor ar y mat r ix t o a funct ion you specify
3 Rear r anges t he r esult ing mat r ix back int o t he or iginal shape
Sliding Neighborhoods
For a sliding neighbor hood oper at ion, colfilt cr eat es a t empor ar y mat r ix t hat
has a separ at e column for each pixel in t he or iginal image. The column
cor r esponding t o a given pixel cont ains t he values of t hat pixels neighbor hood
fr om t he or iginal image.
The figur e below illust r at es t his pr ocess. In t his figur e, a 6-by-5 image mat r ix
is pr ocessed in 2-by-3 neighbor hoods. colfilt cr eat es one column for each
pixel in t he image, so t her e ar e a t ot al of 30 columns in t he t empor ar y mat r ix.
Each pixels column cont ains t he value of t he pixels in it s neighbor hood, so
t her e ar e six r ows. colfilt zer o pads t he input image as necessar y. For
4 Neighborhood and Block Operations
4-12
example, t he neighbor hood of t he upper left pixel in t he figur e has t wo
zer o-valued neighbor s, due t o zer o padding.
The t empor ar y mat r ix is passed t o a funct ion, which must r et ur n a single value
for each column. (Many MATLAB funct ions wor k t his way, for example, mean,
median, std, sum, et c.) The r esult ing values ar e t hen assigned t o t he
appr opr iat e pixels in t he out put image.
colfilt can pr oduce t he same r esult s as nlfilter wit h fast er execut ion t ime;
however , it may use mor e memor y. The example below set s each out put pixel
t o t he maximum value in t he input pixels neighbor hood, pr oducing t he same
r esult as t he nlfilter example on page 4-7. Not ice t hat t he funct ion is max(x)
r at her t han max(x(:)), because each neighbor hood in t he or iginal image is a
separ at e column in t he t empor ar y mat r ix.
f = inline('max(x)');
I2 = colfilt(I,[3 3],'sliding',f);
Distinct Blocks
For a dist inct block oper at ion, colfilt cr eat es a t empor ar y mat r ix by
r ear r anging each block in t he image int o a column. colfilt pads t he or iginal
image wit h 0s, if necessar y, befor e cr eat ing t he t empor ar y mat r ix.
The figur e below illust r at es t his pr ocess. In t his figur e, a 6-by-16 image mat r ix
is pr ocessed in 4-by-6 blocks. colfilt fir st zer o pads t he image t o make t he size
Column Processing
4-13
8-by-18 (six 4-by-6 blocks), and t hen r ear r anges t he blocks int o 6 columns of 24
element s each.
Aft er r ear r anging t he image int o a t empor ar y mat r ix, colfilt passes t his
mat r ix t o t he funct ion. The funct ion must r et ur n a mat r ix of t he same size as
t he t empor ar y mat r ix. If t he block size is m-by-n, and t he image is mm-by-nn, t he
size of t he t empor ar y mat r ix is (m*n)-by-(ceil(mm/m)*ceil(nn/n)). Aft er t he
funct ion pr ocesses t he t empor ar y mat r ix, t he out put is r ear r anged back int o
t he shape of t he or iginal image mat r ix.
This example set s all t he pixels in each 8-by-8 block of an image t o t he mean
pixel value for t he block, pr oducing t he same r esult as t he blkproc example on
page 4-9.
I = im2double(imread('tire.tif'));
f = inline('ones(64,1)*mean(x)');
I2 = colfilt(I,[8 8],'distinct',f);
4 Neighborhood and Block Operations
4-14
Not ice t hat t he inline funct ion comput es t he mean of t he block and t hen
mult iplies t he r esult by a vect or of ones, so t hat t he out put block is t he same
size as t he input block. As a r esult , t he out put image is t he same size as t he
input image.
Restrictions
You can use colfilt t o implement many of t he same dist inct block oper at ions
t hat blkproc per for ms. However , colfilt has cer t ain r est r ict ions t hat
blkproc does not :
The out put image must be t he same size as t he input image.
The blocks cannot over lap.
For sit uat ions t hat do not sat isfy t hese const r aint s, use blkproc.
5
Linear Filt er ing and Filt er
Design
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . 5-2
Li near Filteri ng . . . . . . . . . . . . . . . . . . 5-3
Convolut ion . . . . . . . . . . . . . . . . . . . . . 5-3
Padding of Bor der s . . . . . . . . . . . . . . . . . . 5-5
The filt er 2 Funct ion . . . . . . . . . . . . . . . . . 5-7
Separ abilit y . . . . . . . . . . . . . . . . . . . . . 5-8
Higher -Dimensional Convolut ion . . . . . . . . . . . . 5-9
Using Pr edefined Filt er Types . . . . . . . . . . . . . 5-9
Fi lter De si gn . . . . . . . . . . . . . . . . . . . . 5-13
FIR Filt er s . . . . . . . . . . . . . . . . . . . . . 5-13
Fr equency Tr ansfor mat ion Met hod . . . . . . . . . . . 5-14
Fr equency Sampling Met hod . . . . . . . . . . . . . . 5-15
Windowing Met hod . . . . . . . . . . . . . . . . . . 5-16
Cr eat ing t he Desir ed Fr equency Response Mat r ix . . . . . 5-18
Comput ing t he Fr equency Response of a Filt er . . . . . . 5-19
5 Linear Filtering and Filter Design
5-2
Overview
The Image Pr ocessing Toolbox pr ovides a number of funct ions for designing
and implement ing t wo-dimensional linear filt er s for image dat a. This chapt er
descr ibes t hese funct ions and how t o use t hem effect ively.
The mat er ial in t his chapt er is divided int o t wo par t s:
The fir st par t is an explanat ion of linear filt er ing and how it is implement ed
in t he t oolbox. This t opic descr ibes filt er ing in t er ms of t he spat ial domain,
and is accessible t o anyone doing image pr ocessing.
The second par t is a discussion about designing t wo-dimensional Finit e
Infinit e Response (FIR) filt er s. This sect ion assumes you ar e familiar wit h
wor king in t he fr equency domain.
Linear Filtering
5-3
Linear Filtering
Filt er ing is a t echnique for modifying or enhancing an image. For example, you
can filt er an image t o emphasize cer t ain feat ur es or r emove ot her feat ur es.
Filt er ing is a neighborhood operation, in which t he value of any given pixel in
t he out put image is det er mined by applying some algor it hm t o t he values of t he
pixels in t he neighbor hood of t he cor r esponding input pixel. A pixels
neighbor hood is some set of pixels, defined by t heir locat ions r elat ive t o t hat
pixel. (For a gener al discussion of neighbor hood oper at ions, see Chapt er 4,
Neighbor hood and Block Oper at ions.)
Linear filtering is filt er ing in which t he value of an out put pixel is a linear
combinat ion of t he values of t he pixels in t he input pixels neighbor hood. For
example, an algor it hm t hat comput es a weight ed aver age of t he neighbor hood
pixels is one t ype of linear filt er ing oper at ion.
This sect ion discusses linear filt er ing in MATLAB and t he Image Pr ocessing
Toolbox. It includes:
A descr ipt ion of how MATLAB per for ms linear filt er ing, using convolut ion
A discussion about using pr edefined filt er t ypes
For infor mat ion about how t o design filt er s, see page 5-13.
Convolution
In MATLAB, linear filt er ing of images is implement ed t hr ough
t wo-dimensional convolution. In convolut ion, t he value of an out put pixel is
comput ed by mult iplying element s of t wo mat r ices and summing t he r esult s.
One of t hese mat r ices r epr esent s t he image it self, while t he ot her mat r ix is t he
filt er . For example, a filt er might be:
k = [4 3 1
4 6 2]
This filt er r epr esent at ion is known as a convolution kernel. The MATLAB
funct ion conv2 implement s image filt er ing by applying your convolut ion ker nel
t o an image mat r ix. conv2 t akes as ar gument s an input image and a filt er , and
r et ur ns an out put image. For example, in t his call, k is t he convolut ion ker nel,
A is t he input image, and B is t he out put image.
B = conv2(A,k);
5 Linear Filtering and Filter Design
5-4
conv2 pr oduces t he out put image by per for ming t hese st eps:
1 Rot at e t he convolut ion ker nel 180 degr ees t o pr oduce a comput at ional
molecule.
2 Det er mine t he cent er pixel of t he comput at ional molecule.
3 Apply t he comput at ional molecule t o each pixel in t he input image.
Each of t hese st eps is explained below.
Rotating the Convolution Kernel
In t wo-dimensional convolut ion, t he comput at ions ar e per for med using a
computational molecule. This is simply t he convolut ion ker nel r ot at ed 180
degr ees, as in t his call:
h = rot90(k,2);
h =
2 6 4
1 3 4
Determining the Center Pixel
To apply t he comput at ional molecule, you must fir st det er mine t he center pixel.
The cent er pixel is defined as floor((size(h)+1)/2). For example, in a 5-by-5
molecule, t he cent er pixel is (3,3). The molecule h shown above is 2-by-3, so t he
cent er pixel is (1,2).
Applying the Computational Molecule
The value of any given pixel in B is det er mined by applying t he comput at ional
molecule h t o t he cor r esponding pixel in A. You can visualize t his by over laying
h on A, wit h t he cent er pixel of h over t he pixel of int er est in A. You t hen
mult iply each element of h by t he cor r esponding pixel in A, and sum t he r esult s.
Linear Filtering
5-5
For example, t o det er mine t he value of t he pixel (4,6) in B, over lay h on A, wit h
t he cent er pixel of h cover ing t he pixel (4,6) in A. The cent er pixel is cir cled in
t his figur e.
Now, look at t he six pixels cover ed by h. For each of t hese pixels, mult iply t he
value of t he pixel by t he value in h. Sum t he r esult s, and place t his sum in
B(4,6).
B(4,6) = 2*2 + 3*6 + 3*4 + 3*1 + 2*3 + 0*4 = 31
Per for m t his pr ocedur e for each pixel in A t o det er mine t he value of each
cor r esponding pixel in B.
Padding of Borders
When you apply a filt er t o pixels on t he bor der s of an image, some of t he
element s of t he comput at ional molecule may not over lap act ual image pixels.
For example, if t he molecule is 3-by-3 and you ar e comput ing t he r esult for a
pixel on t he t op r ow of t he image, some of t he element s of t he molecule ar e
out side t he bor der of t he image.
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 3 3 4 5
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
2 6 4
1 3 4
A
h
5 Linear Filtering and Filter Design
5-6
This figur e illust r at es a 3-by-3 comput at ional molecule being applied t o t he
pixel (1,3) of a 5-by-5 mat r ix. The cent er pixel is indicat ed by a filled cir cle.
In or der t o comput e out put values for t he bor der pixels, conv2 pads t he image
mat r ix wit h zer oes. In ot her wor ds, t he out put values ar e comput ed by
assuming t hat t he input image is sur r ounded by addit ional r ows and columns
of zer oes. In t he figur e shown above, t he element s in t he t op r ow of t he
comput at ional molecule ar e assumed t o over lap zer oes.
Depending on what you ar e t r ying t o accomplish, you may want t o discar d
out put pixels whose values depend on zer o padding. To indicat e what por t ion
of t he convolut ion t o r et ur n, conv2 t akes a t hir d input ar gument , called t he
shape par amet er , whose value is one of t hese t hr ee st r ings:
'valid' r et ur ns only t he pixels whose values can be comput ed wit hout
using zer o padding of t he input image. The r esult ing out put image is smaller
t han t he input image. In t his example, t he out put image is 3-by-3.
'same' r et ur ns t he set of pixels t hat can be comput ed by applying t he filt er
t o all pixels t hat ar e act ually par t of t he input image. Bor der pixels ar e
comput ed using zer o padding, but t he cent er pixel of t he comput at ional
ker nel is applied only t o pixels in t he image. This r esult s in an out put image
t hat is t he same size as t he input image.
'full' r et ur ns t he full convolut ion. This means conv2 r et ur ns all pixels for
which any of t he pixels in t he comput at ional molecule over lap pixels in t he
image, even when t he cent er pixel is out side t he input image. The r esult ing
out put image is lar ger t han t he input image. In t his example, t he out put
image is 7-by-7.
conv2 r et ur ns t he full convolut ion by default .
Linear Filtering
5-7
The figur e below illust r at es applying a comput at ional molecule t o t hr ee
differ ent places in an image mat r ix.
If you use t he full opt ion, t hen t he or der of t he fir st t wo input ar gument s is
int er changeable, because full convolut ion is commut at ive. In ot her wor ds, it
does not mat t er which mat r ix is consider ed t he convolut ion ker nel, because t he
r esult is t he same in eit her case. If you use t he valid or same opt ion, t he
oper at ion is not commut at ive, so t he convolut ion ker nel must be t he second
ar gument .
The filter2 Function
In addit ion t o t he conv2 funct ion, MATLAB also pr ovides t he filter2 funct ion
for t wo-dimensional linear filt er ing. filter2 can pr oduce t he same r esult s as
conv2, and differ s pr imar ily in t hat it t akes a comput at ional molecule as an
input ar gument , r at her t han a convolut ion ker nel. (filter2 oper at es by
for ming t he convolut ion ker nel fr om t he comput at ional molecule and t hen
calling conv2.) The oper at ion t hat filter2 per for ms is called correlation.
The computational molecule over-
laps only pixels that are in
the original image. The result is
included in the output matrix,
regardless of the shape parameter.
The computational molecule over-
laps pixels outside the original
image, but the center pixel overlaps
a pixel in the image. The result is
included in the output matrix if the
shape parameter is same or full.
The computational molecule over-
laps pixels at the edges only. The
center pixel is outside the image.
The result is included in the output
matrix if the shape parameter is
full.
5 Linear Filtering and Filter Design
5-8
If k is a convolut ion ker nel, h is t he cor r esponding comput at ional molecule, and
A is an image mat r ix, t he following calls pr oduce ident ical r esult s:
B = conv2(A,k,'same');
and
B = filter2(h,A,'same');
The funct ions in t he Image Pr ocessing Toolbox t hat pr oduce filt er s (fspecial,
fsample, et c.) all r et ur n comput at ional molecules. You can use t hese filt er s
dir ect ly wit h filter2, or you can r ot at e t hem 180 degr ees and call conv2.
Separability
Befor e calling conv2 t o per for m t wo-dimensional convolut ion, filter2 fir st
checks whet her t he filt er is separ able int o t wo one-dimensional filt er s (one
column vect or and one r ow vect or ). If t he filt er is separ able, filter2 uses
singular value decomposit ion t o find t he t wo vect or s. filter2 t hen calls conv2
wit h t his synt ax:
conv2(A,kcol,krow);
kcol and krow ar e t he column and r ow vect or s t hat t he t wo-dimensional
convolut ion ker nel k separ at es int o (t hat is, k = kcol*krow).
conv2 filt er s t he columns wit h t he column vect or , and t hen, using t he out put of
t his oper at ion, filt er s t he r ows using t he r ow vect or . The r esult is equivalent t o
t wo-dimensional convolut ion but is fast er because it r equir es fewer
comput at ions.
Linear Filtering
5-9
Determining Separability
A filt er is separ able if it s r ank is 1. For example, t his filt er is separ able:
k =
1 2 3
2 4 6
4 8 12
rank(k)
ans =
1
Higher-Dimensional Convolution
To per for m t wo-dimensional convolut ion, you use conv2 or filter2. To per for m
higher -dimensional convolut ion, you use t he convn funct ion. convn t akes as
ar gument s a dat a ar r ay and a convolut ion ker nel, bot h of which can be of any
dimension, and r et ur ns an ar r ay whose dimension is t he higher of t he t wo
input ar r ays dimensions. convn also t akes a shape par amet er ar gument t hat
accept s t he same values as in conv2 and filter2, and which has analogous
effect s in higher dimensions.
One impor t ant applicat ion for t he convn funct ion is t o filt er image ar r ays t hat
have mult iple planes or fr ames. For example, suppose you have an ar r ay A
cont aining five RGB images t hat you want t o filt er using a t wo-dimensional
convolut ion ker nel k. The image ar r ay is a four -dimensional ar r ay of size
m-by-n-by-3-by-5. To filt er t his ar r ay wit h conv2, you would need t o call t he
funct ion 15 t imes, once for each combinat ion of planes and fr ames, and
assemble t he r esult s int o a four -dimensional ar r ay. Using convn, you can filt er
t he ar r ay in a single call.
B = convn(A,k);
For mor e infor mat ion, see t he online r efer ence ent r y for convn.
Using Predefined Filter Types
The funct ion fspecial pr oduces sever al kinds of pr edefined filt er s, in t he for m
of comput at ional molecules. Aft er cr eat ing a filt er wit h fspecial, you can
5 Linear Filtering and Filter Design
5-10
apply it dir ect ly t o your image dat a using filter2, or you can r ot at e it 180
degr ees and use conv2 or convn.
One simple filt er fspecial can pr oduce is an aver aging filt er . This t ype of filt er
comput es t he value of an out put pixel by simply aver aging t he values of it s
neighbor ing pixels.
The default size of t he aver aging filt er fspecial cr eat es is 3-by-3, but you can
specify a differ ent size. The value of each element is 1/length(h(:)). For
example, a 5-by-5 aver aging filt er 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 t his filt er t o a pixel is equivalent t o adding up t he values of t hat
pixels 5-by-5 neighbor hood and dividing by 25. This has t he effect of smoot hing
out local highlight s and blur r ing edges in an image.
This example illust r at es applying a 5-by-5 aver aging filt er t o an int ensit y
image:
I = imread('blood1.tif');
h = fspecial('average',5);
I2 = uint8(round(filter2(h,I)));
imshow(I)
figure, imshow(I2)
Linear Filtering
5-11
Not e t hat t he out put fr om filter2 (and conv2 and convn) is always of class
double. In t he example above, t he input image is of class uint8, so t he out put
fr om filter2 consist s of double-pr ecision values in t he r ange [0,255]. The call
t o t he uint8 funct ion conver t s t he out put t o uint8; t he dat a is not in t he pr oper
r ange for an image of class double.
Anot her r elat ively simple filt er fspecial can pr oduce is a 3-by-3 Sobel filt er ,
which is effect ive at det ect ing t he hor izont al edges of object s in an image.
h = fspecial('sobel')
h =
1 2 1
0 0 0
1 2 1
Unlike an aver aging filt er , t he Sobel filt er pr oduces values out side t he r ange of
t he input dat a. For example, if t he input image is of class double, t he out put
ar r ay may include values out side t he r ange [0,1]. To display t he out put as an
image, you can use imshow and specify t he dat a r ange, or you can use t he
mat2gray funct ion t o conver t t he values t o t he r ange [0,1].
Not e t hat if t he input image is of class uint8 or uint16, you should not simply
conver t t he out put ar r ay t o t he same class as t he input image, because t he
out put may cont ain values out side t he r ange t hat t he class can r epr esent . For
example, if t he input image is of class uint8, t he out put may include values
t hat cannot be r epr esent ed as 8-bit int eger s. You can, however , r escale t he
out put and t hen conver t it . For example,
h = fspecial('sobel');
I2 = filter2(h,I);
J = uint8(round(mat2gray(I2)*255));
You can also use imshow t o display t he out put ar r ay wit hout fir st r escaling t he
dat a. The following example cr eat es a Sobel filt er and uses filter2 t o apply
t he filt er t o t he blood1 image. Not ice t hat in t he call t o imshow, t he int ensit y
r ange is specified as an empt y mat r ix ([]). This inst r uct s imshow t o display t he
minimum value in I2 as black, t he maximum value as whit e, and values in
5 Linear Filtering and Filter Design
5-12
bet ween as int er mediat e shades of gr ay, t hus enabling you t o display t he
filter2 out put wit hout conver t ing or r escaling it .
I = imread('blood1.tif');
h = fspecial('sobel');
I2 = filter2(h,I);
imshow(I2,[])
For a descr ipt ion of all t he filt er t ypes fspecial pr ovides, see t he r efer ence
ent r y for fspecial.
Filter Design
5-13
Filter Design
This sect ion descr ibes wor king in t he fr equency domain t o design filt er s. Topics
discussed include:
Finit e Impulse Response (FIR) filt er s, t he class of linear filt er t hat t he
t oolbox suppor t s
The fr equency t r ansfor mat ion met hod, which t r ansfor ms a one-dimensional
FIR filt er int o a t wo-dimensional FIR filt er
The fr equency sampling met hod, which cr eat es a filt er based on a desir ed
fr equency r esponse
The windowing met hod, which mult iplies t he ideal impulse r esponse wit h a
window funct ion t o gener at e t he filt er
Cr eat ing t he desir ed fr equency r esponse mat r ix
Comput ing t he fr equency r esponse of a filt er
This sect ion assumes you ar e familiar wit h wor king in t he fr equency domain.
This t opic is discussed in many signal pr ocessing and image pr ocessing
t ext books.
Note: Most of t he design met hods descr ibed in t his sect ion wor k by cr eat ing
a t wo-dimensional filt er fr om a one-dimensional filt er or window cr eat ed
using funct ions fr om t he S ignal Processing Toolbox. Alt hough t his t oolbox is
not r equir ed, you may find it difficult t o design filt er s in t he Image Pr ocessing
Toolbox if you do not have t he S ignal Processing Toolbox as well.
FIR Filters
The Image Pr ocessing Toolbox suppor t s one class of linear filt er , t he
t wo-dimensional Finit e Impulse Response (FIR) filt er . FIR filt er s have sever al
char act er ist ics t hat make t hem ideal for image pr ocessing in t he MATLAB
envir onment :
FIR filt er s ar e easy t o r epr esent as mat r ices of coefficient s.
Two-dimensional FIR filt er s ar e nat ur al ext ensions of one-dimensional FIR
filt er s.
5 Linear Filtering and Filter Design
5-14
Ther e ar e sever al well-known, r eliable met hods for FIR filt er design.
FIR filt er s ar e easy t o implement .
FIR filt er s can be designed t o have linear phase, which helps pr event
dist or t ion.
Anot her class of filt er , t he Infinit e Impulse Response (IIR) filt er , is not as
suit able for image pr ocessing applicat ions. It lacks t he inher ent st abilit y and
ease of design and implement at ion of t he FIR filt er . Ther efor e, t his t oolbox
does not pr ovide IIR filt er suppor t .
Frequency Transformation Method
The fr equency t r ansfor mat ion met hod t r ansfor ms a one-dimensional FIR filt er
int o a t wo-dimensional FIR filt er . The fr equency t r ansfor mat ion met hod
pr eser ves most of t he char act er ist ics of t he one-dimensional filt er , par t icular ly
t he t r ansit ion bandwidt h and r ipple char act er ist ics. This met hod uses a
transformation matrix, a set of element s t hat defines t he fr equency
t r ansfor mat ion.
The t oolbox funct ion ftrans2 implement s t he fr equency t r ansfor mat ion
met hod. This funct ions default t r ansfor mat ion mat r ix pr oduces filt er s wit h
near ly cir cular symmet r y. By defining your own t r ansfor mat ion mat r ix, you
can obt ain differ ent symmet r ies. (See J ae S. Lim, Two-Dimensional S ignal and
Image Processing, 1990, for det ails.)
The fr equency t r ansfor mat ion met hod gener ally pr oduces ver y good r esult s, as
it is easier t o design a one-dimensional filt er wit h par t icular char act er ist ics
t han a cor r esponding t wo-dimensional filt er . For inst ance, t he next example
designs an opt imal equir ipple one-dimensional FIR filt er and uses it t o cr eat e
a t wo-dimensional filt er wit h similar char act er ist ics. The shape of t he
Filter Design
5-15
one-dimensional fr equency r esponse is clear ly evident in t he t wo-dimensional
r esponse.
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/pi1,fftshift(abs(H)))
figure, freqz2(h,[32 32])
Frequency Sampling Method
The fr equency sampling met hod cr eat es a filt er based on a desir ed fr equency
r esponse. Given a mat r ix of point s t hat defines t he shape of t he fr equency
r esponse, t his met hod cr eat es a filt er whose fr equency r esponse passes t hr ough
t hose point s. Fr equency sampling places no const r aint s on t he behavior of t he
fr equency r esponse bet ween t he given point s; usually, t he r esponse r ipples in
t hese ar eas.
The t oolbox funct ion fsamp2 implement s fr equency sampling design for
t wo-dimensional FIR filt er s. fsamp2 r et ur ns a filt er h wit h a fr equency
r esponse t hat passes t hr ough t he point s in t he input mat r ix Hd. The example
below cr eat es an 11-by-11 filt er using fsamp2, and plot s t he fr equency r esponse
of t he r esult ing filt er . (The freqz2 funct ion in t his example calculat es t he
5 Linear Filtering and Filter Design
5-16
t wo-dimensional fr equency r esponse of a filt er . For mor e infor mat ion, 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])
Not ice t he r ipples in t he act ual fr equency r esponse, compar ed t o t he desir ed
fr equency r esponse. These r ipples ar e a fundament al pr oblem wit h t he
fr equency sampling design met hod. They occur wher ever t her e ar e shar p
t r ansit ions in t he desir ed r esponse.
You can r educe t he spat ial ext ent of t he r ipples by using a lar ger filt er .
However , a lar ger filt er does not r educe t he height of t he r ipples, and r equir es
mor e comput at ion t ime for filt er ing. To achieve a smoot her appr oximat ion t o
t he desir ed fr equency r esponse, consider using t he fr equency t r ansfor mat ion
met hod or t he windowing met hod.
Windowing Method
The windowing met hod involves mult iplying t he ideal impulse r esponse wit h a
window funct ion t o gener at e a cor r esponding filt er . Like t he fr equency
sampling met hod, t he windowing met hod pr oduces a filt er whose fr equency
r esponse appr oximat es a desir ed fr equency r esponse. The windowing met hod,
however , t ends t o pr oduce bet t er r esult s t han t he fr equency sampling met hod.
Filter Design
5-17
The t oolbox pr ovides t wo funct ions for window-based filt er design, fwind1 and
fwind2. fwind1 designs a t wo-dimensional filt er by using a t wo-dimensional
window t hat it cr eat es fr om one or t wo one-dimensional windows t hat you
specify. fwind2 designs a t wo-dimensional filt er by using a specified
t wo-dimensional window dir ect ly.
fwind1 suppor t s t wo differ ent met hods for making t he t wo-dimensional
windows it uses:
Tr ansfor ming a single one-dimensional window t o cr eat e a t wo-dimensional
window t hat is near ly cir cular ly symmet r ic, by using a pr ocess similar t o
r ot at ion
Cr eat ing a r ect angular , separ able window fr om t wo one-dimensional
windows, by comput ing t heir out er pr oduct
The example below uses fwind1 t o cr eat e an 11-by-11 filt er fr om t he desir ed
fr equency r esponse Hd. Her e, t he hamming funct ion fr om t he S ignal Processing
Toolbox is used t o cr eat e a one-dimensional window, which fwind1 t hen
ext ends t o a t wo-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])
5 Linear Filtering and Filter Design
5-18
Creating the Desired Frequency Response Matrix
The filt er design funct ions fsamp2, fwind1, and fwind2 all cr eat e filt er s based
on a desir ed fr equency r esponse magnit ude mat r ix. You can cr eat e an
appr opr iat e desir ed fr equency r esponse mat r ix using t he freqspace funct ion.
freqspace r et ur ns cor r ect , evenly spaced fr equency values for any size
r esponse. If you cr eat e a desir ed fr equency r esponse mat r ix using fr equency
point s ot her t han t hose r et ur ned by freqspace, you may get unexpect ed
r esult s, such as nonlinear phase.
For example, t o cr eat e a cir cular ideal lowpass fr equency r esponse wit h cut off
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)
Not e t hat for t his fr equency r esponse, t he filt er s pr oduced by fsamp2, fwind1,
and fwind2 ar e r eal. This r esult is desir able for most image pr ocessing
applicat ions. To achieve t his in gener al, t he desir ed fr equency r esponse should
be symmet r ic about t he fr equency or igin (f1 = 0, f2 = 0).
Filter Design
5-19
Computing the Frequency Response of a Filter
The freqz2 funct ion comput es t he fr equency r esponse for a t wo-dimensional
filt er . Wit h no out put ar gument s, freqz2 cr eat es a mesh plot of t he fr equency
r esponse. For example, consider t his FIR filt er :
h =[0.1667 0.6667 0.1667
0.6667 3.3333 0.6667
0.1667 0.6667 0.1667];
This command comput es and displays t he 64-by-64 point fr equency r esponse of
h:
freqz2(h)
To obt ain t he fr equency r esponse mat r ix H and t he fr equency point vect or s f1
and f2, use out put ar gument s:
[H,f1,f2] = freqz2(h);
freqz2 nor malizes t he fr equencies f1 and f2 so t hat t he value 1.0 cor r esponds
t o half t he sampling fr equency, or r adians.
For a simple m-by-n r esponse, as shown above, freqz2 uses t he
t wo-dimensional fast Four ier t r ansfor m funct ion fft2. You can also specify
vect or s of ar bit r ar y fr equency point s, but in t his case freqz2 uses a slower
algor it hm.
For mor e infor mat ion about t he fast Four ier t r ansfor m and it s applicat ion t o
linear filt er ing and filt er design, see Chapt er 6.
5 Linear Filtering and Filter Design
5-20
6
Tr ansfor ms
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . 6-2
Fouri er Transform . . . . . . . . . . . . . . . . . 6-3
Definit ion . . . . . . . . . . . . . . . . . . . . . . 6-3
The Discr et e Four ier Tr ansfor m . . . . . . . . . . . . 6-8
Applicat ions . . . . . . . . . . . . . . . . . . . . . 6-11
Di scre te Cosi ne Transform . . . . . . . . . . . . . 6-15
The DCT Tr ansfor m Mat r ix . . . . . . . . . . . . . . 6-16
The DCT and Image Compr ession . . . . . . . . . . . . 6-17
Radon Trans form . . . . . . . . . . . . . . . . . . 6-19
Using t he Radon Tr ansfor m t o Det ect Lines . . . . . . . . 6-23
The Inver se Radon Tr ansfor m . . . . . . . . . . . . . 6-25
6 Transforms
6-2
Overview
The usual mat hemat ical r epr esent at ion of an image is a funct ion of t wo spat ial
var iables: . The value of t he funct ion at a par t icular locat ion
r epr esent s t he int ensit y of t he image at t hat point . The t er m transform r efer s
t o an alt er nat ive mat hemat ical r epr esent at ion of an image.
For example, t he Four ier t r ansfor m is a r epr esent at ion of an image as a sum of
complex exponent ials of var ying magnit udes, fr equencies, and phases. This
r epr esent at ion is useful in a br oad r ange of applicat ions, including (but not
limit ed t o) image analysis, r est or at ion, and filt er ing.
The discr et e cosine t r ansfor m (DCT) also r epr esent s an image as a sum of
sinusoids of var ying magnit udes and fr equencies. The DCT is ext r emely useful
for image compr ession; it is t he basis of t he widely used J PEG image
compr ession algor it hm.
The Radon t r ansfor m r epr esent s an image as a collect ion of pr oject ions along
var ious dir ect ions. It is used in ar eas r anging fr om seismology t o comput er
vision.
This chapt er defines each of t hese t r ansfor ms, descr ibes r elat ed t oolbox
funct ions, and shows examples of r elat ed image pr ocessing applicat ions.
f x y , ( ) x y , ( )
Fourier Transform
6-3
Fourier Transform
The Four ier t r ansfor m plays a cr it ical r ole in a br oad r ange of image pr ocessing
applicat ions, including enhancement , analysis, r est or at ion, and compr ession.
This sect ion defines t he Four ier t r ansfor m and t he r elat ed discr et e Four ier
t r ansfor m, discusses t he fast Four ier t r ansfor m, and pr esent s some sample
applicat ions.
Definition
If is a funct ion of t wo discr et e spat ial var iables m and n, t hen we define
t he two-dimensional Fourier transform of by t he r elat ionship:
The var iables
1
and
2
ar e fr equency var iables; t heir unit s ar e r adians per
sample. is oft en called t he frequency-domain r epr esent at ion of
. is a complex-valued funct ion t hat is per iodic bot h in and
, wit h per iod . Because of t he per iodicit y, usually only t he r ange
is displayed. Not e t hat is t he sum of all t he values of
. For t his r eason, is oft en called t he constant component or DC
component of t he Four ier t r ansfor m. (DC st ands for dir ect cur r ent ; it is an
elect r ical engineer ing t er m t hat r efer s t o a const ant -volt age power sour ce, as
opposed t o a power sour ce whose volt age var ies sinusoidally.)
The inver se t wo-dimensional Four ier t r ansfor m is given by:
Roughly speaking, t his equat ion means t hat can be r epr esent ed as a
sum of an infinit e number of complex exponent ials (sinusoids) wit h differ ent
fr equencies. The magnit ude and phase of t he cont r ibut ion at t he fr equencies
ar e given by .
f m n , ( )
f m n , ( )
F
1

2
, ( ) f m n , ( )e
j
1
m
e
j
2
n
n =

m =

=
F
1

2
, ( )
f m n , ( ) F
1

2
, ( )
1

2
2

1

2
, F 0 0 , ( )
f m n , ( ) F 0 0 , ( )
f m n , ( )
1
2
------ F
1

2
, ( )e
j
1
m
e
j
2
n

1

2
d d

2
=

1
=

=
f m n , ( )

1

2
, ( ) F
1

2
, ( )
6 Transforms
6-4
Example
Consider a funct ion t hat equals 1 wit hin a r ect angular r egion and 0
ever ywher e else.
To simplify t he diagr am, is shown as a cont inuous funct ion, even
t hough t he var iables m and n ar e discr et e.
f m n , ( )
m
n
f(m,n)
f m n , ( )
Fourier Transform
6-5
The magnit ude of t he Four ier t r ansfor m, , is shown her e as a mesh
plot .
The peak at t he cent er of t he plot is , which is t he sum of all t he values
in . The plot also shows t hat has mor e ener gy at high
hor izont al fr equencies t han at high ver t ical fr equencies. This r eflect s t he fact
t hat hor izont al cr oss sect ions of ar e nar r ow pulses, while ver t ical cr oss
sect ions ar e br oad pulses. Nar r ow pulses have mor e high-fr equency cont ent
t han br oad pulses. For an example of how t o do t his, see t he example t hat
begins on page page 6-9.
F
1

2
, ( )
1
(h
o
r
iz
o
n
t
a
l
fr
e
q
u
e
n
c
y
)

2 (
v
e
r
t
i
c
a
l
f
r
e
q
u
e
n
c
y
)
F 0 0 , ( )
f m n , ( ) F
1

2
, ( )
f m n , ( )
6 Transforms
6-6
Anot her common way t o visualize t he Four ier t r ansfor m is t o display
as an image, as in:
Using t he logar it hm helps t o br ing out det ails of t he Four ier t r ansfor m in
r egions wher e is ver y close t o 0.
F
1

2
, ( ) log

2
F
1

2
, ( )
Fourier Transform
6-7
Examples of t he Four ier t r ansfor m for ot her simple shapes ar e shown below.
n
6 Transforms
6-8
The Discrete Fourier Transform
Wor king wit h t he Four ier t r ansfor m on a comput er usually involves a for m of
t he t r ansfor m known as t he discr et e Four ier t r ansfor m (DFT). Ther e ar e t wo
pr incipal r easons for using t his for m:
The input and out put of t he DFT ar e bot h discr et e, which makes it
convenient for comput er manipulat ions.
Ther e is a fast algor it hm for comput ing t he DFT known as t he fast Four ier
t r ansfor m (FFT).
The DFT is usually defined for a discr et e funct ion t hat is nonzer o only
over t he finit e r egion and . The t wo-dimensional
M-by-N DFT and inver se M-by-N DFT r elat ionships ar e given by:
The values ar e called t he DFT coefficient s of . In par t icular , t he
value is called t he DC coefficient . (Not e t hat mat r ix indices in
MATLAB always st ar t at 1 r at her t han 0; t her efor e, t he mat r ix element s
f(1,1) and F(1,1) cor r espond t o t he mat hemat ical quant it ies and
, r espect ively.)
The MATLAB funct ions fft, fft2, and fftn implement t he fast Four ier
t r ansfor m algor it hm for comput ing t he one-dimensional DFT, t wo-dimensional
DFT, and N-dimensional DFT, r espect ively. The funct ions ifft, ifft2, and
ifftn comput e t he inver se DFT.
f m n , ( )
0 m M 1 0 n N 1
F p q , ( ) f m n , ( )e
j 2 M ( )p m
e
j 2 N ( )q n
n 0 =
N 1

m 0 =
M 1

=
p 0 1 M 1 , , , =
q 0 1 N 1 , , , =
f m n , ( )
1
MN
---------- F p q , ( )e
j 2 M ( )p m
e
j 2 N ( )qn
q 0 =
N 1

p 0 =
M 1

=
m 0 1 M 1 , , , =
n 0 1 N 1 , , , =
F p q , ( ) f m n , ( )
F 0 0 , ( )
f 0 0 , ( )
F 0 0 , ( )
Fourier Transform
6-9
Relationship to the Fourier Transform
The DFT coefficient s ar e samples of t he Four ier t r ansfor m :
Example
Let s const r uct a mat r ix f t hat is similar t o t he funct ion f(m,n) in t he example
on page 6-4.
f = zeros(30,30);
f(5:24,13:17) = 1;
imshow(f,'notruesize')
F p q , ( ) F
1

2
, ( )
F p q , ( ) F
1

2
, ( )

1
2p M =

2
2q N =
=
p 0 1 M 1 , , , =
q 0 1 N 1 , , , =
6 Transforms
6-10
Comput e and visualize t he 30-by-30 DFT of f wit h t hese commands:
F = fft2(f);
F2 = log(abs(F));
imshow(F2,[1 5],'notruesize'); colormap(jet); colorbar
This plot differ s fr om t he Four ier t r ansfor m displayed on page 6-6. Fir st , t he
r esolut ion is much lower . Second, t he DC coefficient is displayed in t he
upper -left cor ner inst ead of t he t r adit ional locat ion in t he cent er .
The r esolut ion can be incr eased by zer o-padding f when comput ing it s DFT.
The zer o-padding and DFT comput at ion can be per for med in a single st ep wit h
t his command:
F = fft2(f,256,256);
Fourier Transform
6-11
This command zer o-pads f t o be 256-by-256 befor e comput ing t he DFT. The
r esult is t hat t he DCT coefficient s F sample t he Four ier t r ansfor m much mor e
finely.
imshow(log(abs(F)),[1 5]); colormap(jet); colorbar
The DC coefficient , however , is st ill displayed in t he upper -left cor ner r at her
t han t he cent er . You can fix t his pr oblem by using t he funct ion fftshift,
which swaps t he quadr ant s of F so t hat t he DC coefficient is in t he cent er .
F = fft2(f,256,256);
F2 = fftshift(F);
imshow(log(abs(F2)),[1 5]); colormap(jet); colorbar
The r esult ing plot is ident ical t o t he one on page 6-6.
Applications
This sect ion pr esent s a few of t he many image pr ocessing-r elat ed applicat ions
of t he Four ier t r ansfor m.
Frequency Response of Linear Filters
The Four ier t r ansfor m of t he impulse r esponse of a linear filt er gives t he
fr equency r esponse of t he filt er . The funct ion freqz2 comput es and displays a
filt er s fr equency r esponse. The fr equency r esponse of t he Gaussian
6 Transforms
6-12
convolut ion ker nel shows t hat t his filt er passes low fr equencies and at t enuat es
high fr equencies.
h = fspecial('gaussian');
freqz2(h)
See Chapt er 5, Linear Filt er ing and Filt er Design for mor e infor mat ion about
linear filt er ing, filt er design, and fr equency r esponses.
Fast Convolution
A key pr oper t y of t he Four ier t r ansfor m is t hat t he mult iplicat ion of t wo
Four ier t r ansfor ms cor r esponds t o t he convolut ion of t he associat ed spat ial
funct ions. This pr oper t y, t oget her wit h t he fast Four ier t r ansfor m, for ms t he
basis for a fast convolut ion algor it hm.
Suppose t hat A is an M-by-N mat r ix and B is a P-by-Q mat r ix. The convolut ion
of A and B can be comput ed using t he following st eps:
1 Zer o-pad A and B so t hat t hey ar e at least (M+P1)-by-(N+Q1). (Oft en A and
B ar e zer o-padded t o a size t hat is a power of 2 because fft2 is fast est for
t hese sizes.)
2 Comput e t he t wo-dimensional DFT of A and B using fft2.
Fourier Transform
6-13
3 Mult iply t he t wo DFTs t oget her .
4 Using ifft2, comput e t he inver se t wo-dimensional DFT of t he r esult fr om
st ep 3.
For example:
A = magic(3);
B = ones(3);
A(8,8) = 0; % zeropad A to be 8by8
B(8,8) = 0; % zeropad B to be 8by8
C = ifft2(fft2(A).*fft2(B));
C = C(1:5,1:5); % extract the nonzero portion
C = real(C) % remove imaginary part caused by roundoff error
C =
8.0000 9.0000 15.0000 7.0000 6.0000
11.0000 17.0000 30.0000 19.0000 13.0000
15.0000 30.0000 45.0000 30.0000 15.0000
7.0000 21.0000 30.0000 23.0000 9.0000
4.0000 13.0000 15.0000 11.0000 2.0000
The FFT-based convolut ion met hod is most oft en used for lar ge input s. For
small input s it is gener ally fast er t o use filter2 or conv2.
Locating Image Features
The Four ier t r ansfor m can also be used t o per for m cor r elat ion, which is closely
r elat ed t o convolut ion. Cor r elat ion can be used t o locat e feat ur es wit hin an
image; in t his cont ext cor r elat ion is oft en called template matching. For
inst ance, suppose you want t o locat e occur r ences of t he let t er a in t he image
6 Transforms
6-14
text.tif. The figur e below shows t he image and t he t emplat e you want t o
mat ch.
The cor r elat ion of t he image of t he let t er a wit h t he lar ger image can be
comput ed by fir st r ot at ing t he image of a by 180
o
and t hen using t he
FFT-based convolut ion t echnique descr ibed above. The left image below is t he
r esult of t he cor r elat ion; br ight peaks cor r espond t o occur r ences of t he let t er .
The locat ions of t hese peaks ar e indicat ed by t he whit e spot s in t he t hr esholded
cor r elat ion image shown on t he r ight .
Discrete Cosine Transform
6-15
Discrete Cosine Transform
The dct2 funct ion in t he Image Pr ocessing Toolbox comput es t he
t wo-dimensional discr et e cosine t r ansfor m (DCT) of an image. The DCT has t he
pr oper t y t hat , for a t ypical image, most of t he visually significant infor mat ion
about t he image is concent r at ed in just a few coefficient s of t he DCT. For t his
r eason, t he DCT is oft en used in image compr ession applicat ions. For example,
t he DCT is at t he hear t of t he int er nat ional st andar d lossy image compr ession
algor it hm known as J PEG. (The name comes fr om t he wor king gr oup t hat
developed t he st andar d: t he J oint Phot ogr aphic Exper t s Gr oup.)
The t wo-dimensional DCT of an M-by-N mat r ix A is defined as follows:
The values ar e called t he DCT coefficients of A. (Not e t hat mat r ix indices
in MATLAB always st ar t at 1 r at her t han 0; t her efor e, t he MATLAB mat r ix
element s A(1,1) and B(1,1) cor r espond t o t he mat hemat ical quant it ies
and , r espect ively.)
The DCT is an inver t ible t r ansfor m, and it s inver se is given by:
B
p q

p

q
A
m n
2m 1 + ( )p
2M
-------------------------------
2n 1 + ( )q
2N
-----------------------------,
0 p M 1
0 q N 1
cos cos
n 0 =
N 1

m 0 =
M 1

p
1 M, p 0 =
2 M , 1 p M 1
'

=
q
1 N , q 0 =
2 N , 1 q N 1
'

=
B
p q
A
00
B
00
A
m n

p

q
B
p q
2m 1 + ( )p
2M
-------------------------------
2n 1 + ( )q
2N
-----------------------------,
0 m M 1
0 n N 1
cos cos
q 0 =
N 1

p 0 =
M 1

p
1 M, p 0 =
2 M , 1 p M 1
'

=
q
1 N , q 0 =
2 N , 1 q N 1
'

=
6 Transforms
6-16
The inver se DCT equat ion can be int er pr et ed as meaning t hat any M-by-N
mat r ix A can be wr it t en as a sum of funct ions of t he for m:
These funct ions ar e called t he basis functions of t he DCT. The DCT coefficient s
, t hen, can be r egar ded as t he weights applied t o each basis funct ion. For
8-by-8 mat r ices, t he 64 basis funct ions ar e illust r at ed by t his image.
Hor izont al fr equencies incr ease fr om left t o r ight , and ver t ical fr equencies
incr ease fr om t op t o bot t om. The const ant -valued basis funct ion at t he upper
left is oft en called t he DC basis function, and t he cor r esponding DCT coefficient
B
00
is oft en called t he DC coefficient.
The DCT Transform Matrix
The Image Pr ocessing Toolbox offer s t wo differ ent ways t o comput e t he DCT.
The fir st met hod is t o use t he funct ion dct2. dct2 uses an FFT-based algor it hm
for speedy comput at ion wit h lar ge input s. The second met hod is t o use t he DCT
transform matrix, which is r et ur ned by t he funct ion bee dctmtx and may be
mor e efficient for small squar e input s, such as 8-by-8 or 16-by-16. The M-by-M
t r ansfor m mat r ix T is given by:
MN

q
2m 1 + ( )p
2M
-------------------------------
2n 1 + ( )q
2N
-----------------------------,
0 p M 1
0 q N 1
cos cos
B
p q
Discrete Cosine Transform
6-17
For an M-by-M mat r ix A, T*A is an M-by-M mat r ix whose columns cont ain t he
one-dimensional DCT of t he columns of A. The t wo-dimensional DCT of A can
be comput ed as B=T*A*T'. Since T is a r eal or t honor mal mat r ix, it s inver se is
t he same as it s t r anspose. Ther efor e, t he inver se t wo-dimensional DCT of B is
given by T'*B*T.
The DCT and Image Compression
In t he J PEG image compr ession algor it hm, t he input image is divided int o
8-by-8 or 16-by-16 blocks, and t he t wo-dimensional DCT is comput ed for each
block. The DCT coefficient s ar e t hen quant ized, coded, and t r ansmit t ed. The
J PEG r eceiver (or J PEG file r eader ) decodes t he quant ized DCT coefficient s,
comput es t he inver se t wo-dimensional DCT of each block, and t hen put s t he
blocks back t oget her int o a single image. For t ypical images, many of t he DCT
coefficient s have values close t o zer o; t hese coefficient s can be discar ded
wit hout ser iously affect ing t he qualit y of t he r econst r uct ed image.
The example code below comput es t he t wo-dimensional DCT of 8-by-8 blocks in
t he input image; discar ds (set s t o zer o) all but 10 of t he 64 DCT coefficient s in
T
p q
1
M
--------- p 0 0 q M 1 , =
2
M
-----
2q 1 + ( )p
2M
----------------------------- cos 1 p M 1 0 q M 1 ,

'

=
6 Transforms
6-18
each block; and t hen r econst r uct s t he image using t he t wo-dimensional inver se
DCT of each block. The t r ansfor m mat r ix comput at ion met hod is used.
I = imread('cameraman.tif');
I = im2double(I);
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)
Alt hough t her e is some loss of qualit y in t he r econst r uct ed image, it is clear ly
r ecognizable, even t hough almost 85% of t he DCT coefficient s wer e discar ded.
To exper iment wit h discar ding mor e or fewer coefficient s, and t o apply t his
t echnique t o ot her images, t r y r unning t he demo funct ion dctdemo.
Radon Transform
6-19
Radon Transform
The radon funct ion in t he Image Pr ocessing Toolbox comput es projections of an
image mat r ix along specified dir ect ions. A pr oject ion of a t wo-dimensional
funct ion f(x,y) is a line int egr al in a cer t ain dir ect ion. For example, t he line
int egr al of f(x,y) in t he ver t ical dir ect ion is t he pr oject ion of f(x,y) ont o t he
x-axis; t he line int egr al in t he hor izont al dir ect ion is t he pr oject ion of f(x,y) ont o
t he y-axis. This figur e shows hor izont al and ver t ical pr oject ions for a simple
t wo-dimensional funct ion.
Pr oject ions can be comput ed along any angle . In gener al, t he Radon
t r ansfor m of f(x,y) is t he line int egr al of f par allel t o t he y axis:
x
y
Pr oject ion ont o t he x-axis
P
r
o
j
e
c
t
i
o
n
o
n
t
o
t
h
e
y
-
a
x
i
s
f(x,y)
R

x ( ) f x cos y sin x sin y cos + ( , ) y d


=
6 Transforms
6-20
wher e
This figur e illust r at es t he geomet r y of t he Radon t r ansfor m.
This command comput es t he Radon t r ansfor m of I for t he angles specified in
t he vect or theta:
[R,xp] = radon(I,theta);
The columns of R cont ain t he Radon t r ansfor m for each angle in theta. xp
cont ains t he cor r esponding coor dinat es along t he x-axis. The cent er pixel of
x
y
cos sin
sin cos
x
y
=
x
y
x
y
x

f(x,y)
R

(x)
Radon Transform
6-21
I is defined t o be floor((size(I)+1)/2); t his is t he pixel on t he x-axis
cor r esponding t o .
The commands below comput e and plot t he Radon t r ansfor m at 0 and 45 of
an image cont aining a single squar e 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)')
x 0 =
R
0
x ( ) R
45
x ( )
6 Transforms
6-22
The Radon t r ansfor m for a lar ge number of angles is oft en displayed as an
image. In t his example, t he Radon t r ansfor m for t he squar e image is comput ed
at angles fr om 0 t o 180, in 1 incr ement s:
theta = 0:180;
[R,xp] = radon(I,theta);
imagesc(theta,xp,R);
title('R_{\theta} (X\prime)');
xlabel('\theta (degrees)');
ylabel('x''');
colormap(hot);
colorbar
R

x ( )
Radon Transform
6-23
Using the Radon Transform to Detect Lines
The Radon t r ansfor m is closely r elat ed t o a common comput er vision oper at ion
known as t he Hough t r ansfor m. You can use t he radon funct ion t o implement
a for m of t he Hough t r ansfor m used t o det ect st r aight lines. The st eps ar e:
1 Comput e a binar y edge image using t he edge funct ion.
I = imread('ic.tif');
BW = edge(I);
imshow(I)
figure, imshow(BW)
2 Comput e t he Radon t r ansfor m of t he edge image.
6 Transforms
6-24
theta = 0:179;
[R,xp] = radon(BW,theta);
imagesc(theta, xp, R); colormap(hot);
xlabel('\theta (degrees)'); ylabel('x''');
title('R_{\theta} (X\prime)');
colorbar
3 Find t he locat ions of st r ong peaks in t he Radon t r ansfor m mat r ix. The
locat ions of t hese peaks cor r espond t o t he locat ion of st r aight lines in t he
or iginal image.
In t his example, t he st r ongest peak in R cor r esponds t o and
. The line per pendicular t o t hat angle and locat ed at is
R

x ( )
94 =
x 101 = x 101 =
Radon Transform
6-25
shown below, super imposed in r ed on t he or iginal image. The Radon t r ansfor m
geomet r y is shown in black.
Not ice t hat t he ot her st r ong lines par allel t o t he r ed line also appear as peaks
at in t he t r ansfor m. Also, t he lines per pendicular t o t his line appear
as peaks at .
The Inverse Radon Transform
The iradon funct ion per for ms t he inver se Radon t r ansfor m, which is
commonly used in t omogr aphy applicat ions. This t r ansfor m inver t s t he Radon
t r ansfor m (which was int r oduced in t he pr evious sect ion), and can t her efor e be
used t o r econst r uct images fr om pr oject ion dat a.
As discussed in t he pr evious sect ion "Radon Tr ansfor m", given an image I and
a set of angles theta, t he funct ion radon can be used t o calculat e t he Radon
t r ansfor m:
R = radon(I,theta);
The funct ion iradon can t hen be called t o r econst r uct t he image I:
IR = iradon(R,theta);
In t he example above, pr oject ions ar e calculat ed fr om t he or iginal image I. In
most applicat ion ar eas, t her e is no original image fr om which pr oject ions ar e
for med. For example, in X-r ay absor pt ion t omogr aphy, pr oject ions ar e for med
x
x
= 94
x = 101
94 =
4 =
6 Transforms
6-26
by measur ing t he at t enuat ion of r adiat ion t hat passes t hr ough a physical
specimen at differ ent angles. The or iginal image can be t hought of as a cr oss
sect ion t hr ough t he specimen, in which int ensit y values r epr esent t he densit y
of t he specimen. Pr oject ions ar e collect ed using special pur pose har dwar e, and
t hen an int er nal image of t he specimen is r econst r uct ed by iradon. This allows
for noninvasive imaging of t he inside of a living body or anot her opaque object .
iradon r econst r uct s an image fr om par allel beam pr oject ions. In parallel beam
geometry, each pr oject ion is for med by combining a set of line int egr als t hr ough
an image at a specific angle, as was descr ibed in t he sect ion on t he Radon
t r ansfor m.
The figur e below illust r at es how par allel beam geomet r y is applied in X-r ay
absor pt ion t omogr aphy. Not e t hat t her e is an equal number of n emit t er s and
n det ect or s. Each det ect or measur es t he r adiat ion emit t ed fr om it s
cor r esponding emit t er , and t he at t enuat ion in t he r adiat ion gives a measur e of
t he int egr at ed densit y, or mass, of t he object . This cor r esponds t o t he line
int egr al t hat is calculat ed in t he Radon t r ansfor m.
The par allel beam geomet r y used in t he figur e is t he same as t he geomet r y t hat
was descr ibed under t he Radon Tr ansfor m sect ion. f(x,y) denot es t he
br ight ness of t he image and R

(x)

is t he pr oject ion at angle .
Radon Transform
6-27
Anot her geomet r y t hat is commonly used is fan beam geomet r y, in which t her e
is one emit t er and n det ect or s. Ther e ar e met hods for r esor t ing set s of fan beam
pr oject ions int o par allel beam pr oject ions which can t hen be used by iradon.
(For mor e infor mat ion on t hese met hods, see Kak & Slaney, Principles of
Computerized Tomographic Imaging, IEEE Pr ess, NY, 1988, pp. 92-93.)
x
y
x
x

f(x,y)
R

(x)
6 Transforms
6-28
iradon uses t he filtered backprojection algor it hm t o comput e t he inver se Radon
t r ansfor m. This algor it hm for ms an appr oximat ion t o t he image I based on t he
pr oject ions in t he columns of R. A mor e accur at e r esult can be obt ained by using
mor e pr oject ions in t he r econst r uct ion. As t he number of pr oject ions (t he lengt h
of theta) incr eases, t he r econst r uct ed image IR mor e accur at ely appr oximat es
t he or iginal image I. The vect or theta must cont ain monot onically incr easing
angular values wit h a const ant incr ement al angle . When t he scalar is
known, it can be passed t o iradon inst ead of t he ar r ay of t het a values. Her e is
an example:
IR = iradon(R,Dtheta);
The filt er ed backpr oject ion algor it hm filt er s t he pr oject ions in R and t hen
r econst r uct s t he image using t he filt er ed pr oject ions. In some cases, noise can
be pr esent in t he pr oject ions. To r emove high fr equency noise, apply a window
t o t he filt er t o at t enuat e t he noise. Many such windowed filt er s ar e available
in iradon. The example call t o iradon below applies a Hamming window t o t he
filt er . See t he r efer ence pages for mor e infor mat ion.
IR = iradon(R,theta,Hamming);
iradon also enables you t o specify a nor malized fr equency, D, above which t he
filt er has zer o r esponse. D must be a scalar in t he r ange [0,1]. Wit h t his opt ion,
t he fr equency axis is r escaled, so t hat t he whole filt er is compr essed t o fit int o
t he fr equency r ange [0,D]. This can be useful in cases wher e t he pr oject ions
cont ain lit t le high fr equency infor mat ion but t her e is high fr equency noise. In
t his case, t he noise can be complet ely suppr essed wit hout compr omising t he
r econst r uct ion. The following call t o iradon set s a nor malized fr equency value
of 0.85:
IR = iradon(R,theta,0.85);
Examples
The commands below illust r at e how t o use radon and iradon t o for m
pr oject ions fr om a sample image and t hen r econst r uct t he image fr om t he
pr oject ions. The t est image is t he Shepp-Logan head phant om, which can be
gener at ed by t he Image Pr ocessing Toolbox funct ion phantom. The phant om
image illust r at es many of t he qualit ies t hat ar e found in r eal-wor ld
t omogr aphic imaging of human heads. The br ight ellipt ical shell along t he
Radon Transform
6-29
ext er ior is analogous t o a skull, and t he many ellipses inside ar e analogous t o
br ain feat ur es or t umor s.
P = phantom(256);
imshow(P)
As a fir st st ep t he Radon t r ansfor m of t he phant om br ain is calculat ed for t hr ee
differ ent set s of t het a values. R1 has 18 pr oject ions, R2 has 36 pr oject ions, and
R3 had 90 pr oject ions.
theta1 = 0:10:170; R1 = radon(P,theta1);
theta2 = 0:5:175; R2 = radon(P,theta2);
theta3 = 0:2:178; R3 = radon(P,theta3);
The following command displays t he Radon t r ansfor m calculat ed using 90
pr oject ions (R3):
imagesc(R3); colormap(hot); colorbar
6 Transforms
6-30
Her e is t he Radon t r ansfor m of t he Shepp-Logan Head phant om, using 180
pr oject ions:
When we look at t he Radon t r ansfor m, we can see some of t he feat ur es of t he
input image. The fir st column in t he Radon t r ansfor m cor r esponds t o a
pr oject ion at 0 which is int egr at ing in t he ver t ical dir ect ion. The cent er most
column cor r esponds t o a pr oject ion at 90, which is int egr at ing in t he
hor izont al dir ect ion. The pr oject ion at 90 has a wider pr ofile t han t he
pr oject ion at 0 due t o t he lar ger ver t ical semi-axis of t he out er most ellipse of
t he phant om.
The next figur es show t he inver se Radon t r ansfor ms of R1, R2, and R3, which
wer e gener at ed above. Image I1 was r econst r uct ed wit h t he pr oject ions in R1,
and it is t he least accur at e r econst r uct ion, because it has t he fewest
pr oject ions. I2 was r econst r uct ed wit h t he 36 pr oject ions in R2, and t he qualit y
0
10
20
30
40
50
60

x
'
20 40 60 80 100 120 140 160 180
50
100
150
200
250
300
350
Radon Transform
6-31
of t he r econst r uct ion is bet t er , but it is st ill not clear enough t o discer n clear ly
t he t hr ee small ellipses in t he lower por t ion of t he t est image. I3 was
r econst r uct ed using t he 90 pr oject ions in R3, and t he r esult closely r esembles
t he or iginal image. Not ice t hat when t he number of pr oject ions is r elat ively
small (as in I1 and I2), t he r econst r uct ion may include some ar t ifact s fr om t he
back pr oject ion. To avoid t his, use a lar ger number of angles.
I1 = iradon(R1,10);
I2 = iradon(R2,5);
I3 = iradon(R3,2);
imshow(I1)
figure, imshow(I2)
figure, imshow(I3)
I1
I2
I3
6 Transforms
6-32
7
Analyzing and Enhancing
Images
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . 7-2
Pi xel Values and St ati sti cs . . . . . . . . . . . . . 7-3
Pixel Select ion . . . . . . . . . . . . . . . . . . . . 7-3
Int ensit y Pr ofile . . . . . . . . . . . . . . . . . . . 7-4
Image Cont our s . . . . . . . . . . . . . . . . . . . 7-7
Image Hist ogr am . . . . . . . . . . . . . . . . . . 7-8
Summar y St at ist ics . . . . . . . . . . . . . . . . . . 7-9
Feat ur e Measur ement . . . . . . . . . . . . . . . . 7-9
Image Analysi s . . . . . . . . . . . . . . . . . . . 7-10
Edge Det ect ion . . . . . . . . . . . . . . . . . . . 7-10
Quadt r ee Decomposit ion . . . . . . . . . . . . . . . . 7-11
Image Enhancement . . . . . . . . . . . . . . . . 7-14
Int ensit y Adjust ment . . . . . . . . . . . . . . . . . 7-14
Noise Removal . . . . . . . . . . . . . . . . . . . . 7-20
7 Analyzing and Enhancing Images
7-2
Overview
The Image Pr ocessing Toolbox suppor t s a r ange of st andar d image pr ocessing
oper at ions for analyzing and enhancing images. It s funct ions simplify sever al
cat egor ies of t asks, including:
Obt aining pixel values and st at ist ics, which ar e numer ical summar ies of
dat a in an image
Analyzing images t o ext r act infor mat ion about t heir essent ial st r uct ur e
Enhancing images t o make cer t ain feat ur es easier t o see or t o r educe noise
This sect ion descr ibes specific oper at ions wit hin each cat egor y, and shows how
t o implement each kind of oper at ion using t oolbox funct ions.
Pixel Values and Statistics
7-3
Pixel Values and Statistics
The Image Pr ocessing Toolbox pr ovides sever al funct ions t hat r et ur n
infor mat ion about t he dat a values t hat make up an image. These funct ions
r et ur n infor mat ion about image dat a in var ious for ms, including:
The dat a values for select ed pixels (pixval, impixel)
The dat a values along a pat h in an image (improfile)
A cont our plot of t he image dat a (imcontour)
A hist ogr am of t he image dat a (imhist)
Summar y st at ist ics for t he image dat a (mean2, std2, corr2)
Feat ur e measur ement s for image r egions (imfeature)
Pixel Selection
The t oolbox includes t wo funct ions t hat pr ovide infor mat ion about t he color
dat a values of image pixels you specify:
The pixval funct ion int er act ively displays t he dat a values for pixels as you
move t he cur sor over t he image. pixval can also display t he Euclidean
dist ance bet ween t wo pixels.
The impixel funct ion r et ur ns t he dat a values for a select ed pixel or set of
pixels. You can supply t he coor dinat es of t he pixels as input ar gument s, or
you can select pixels using a mouse.
To use pixval, you fir st display an image and t hen ent er t he pixval command.
pixval inst alls a black bar at t he bot t om of t he figur e, which displays t he
r ow-column coor dinat es for what ever pixel t he cur sor is cur r ent ly over , and t he
color dat a for t hat pixel.
If you click on t he image and hold down t he mouse but t on while you move t he
cur sor , pixval also displays t he Euclidean dist ance bet ween t he point you
clicked on and t he cur r ent cur sor locat ion. pixval dr aws a line bet ween t hese
point s t o indicat e t he dist ance being measur ed. When you r elease t he mouse
but t on, t he line and t he dist ance display disappear .
pixval gives you mor e immediat e r esult s t han impixel, but impixel has t he
advant age of r et ur ning it s r esult s in a var iable, and it can be called eit her
int er act ively or nonint er act ively. If you call impixel wit h no input ar gument s,
t he cur sor changes t o a cr osshair when it is over t he image. You can t hen click
7 Analyzing and Enhancing Images
7-4
on t he pixels of int er est ; impixel displays a small st ar over each pixel you
select . When you ar e done select ing pixels, pr ess Re turn. impixel r et ur ns t he
color values for t he select ed pixels, and t he st ar s disappear .
In t his example, you call impixel and click on t hr ee point s in t he displayed
image, and t hen pr ess Re turn.
imshow canoe.tif
vals = impixel
vals =
0.1294 0.1294 0.1294
0.5176 0 0
0.7765 0.6118 0.4196
Not ice t hat t he second pixel, which is par t of t he canoe, is pur e r ed; it s gr een
and blue values ar e bot h 0.
For indexed images, pixval and impixel bot h show t he RGB values st or ed in
t he color map, not t he index values. For mor e infor mat ion about t hese
funct ions, see t he r efer ence ent r ies.
Intensity Profile
The improfile funct ion calculat es and plot s t he int ensit y values along a line
segment or a mult iline pat h in an image. You can supply t he coor dinat es of t he
line segment s as input ar gument s, or you can define t he desir ed pat h using a
*
*
*
Pixel Values and Statistics
7-5
mouse. In eit her case, improfile uses int er polat ion t o det er mine t he values of
equally spaced point s along t he pat h. (By default , improfile uses near est
neighbor int er polat ion, but you can specify a differ ent met hod. See Chapt er 3,
Geomet r ic Oper at ions for a discussion of int er polat ion.) improfile wor ks
best wit h int ensit y and RGB images. (For indexed images, it displays t he index
values fr om t he image mat r ix, not t he int ensit y values fr om t he color map.)
For a single line segment , improfile plot s t he int ensit y values in a
t wo-dimensional view. For a mult iline pat h, improfile plot s t he int ensit y
values in a t hr ee-dimensional view.
If you call improfile wit h no ar gument s, t he cur sor changes t o a cr oss hair
when it is over t he image. You can t hen specify line segment s by clicking on t he
endpoint s; improfile dr aws a line bet ween each t wo consecut ive point s you
select . When you finish specifying t he pat h, pr ess Re turn. improfile displays
t he plot in a new figur e.
In t his example, you call improfile and specify a single line wit h t he mouse.
The line is shown in r ed, and is dr awn fr om left t o r ight .
imshow debye1.tif
improfile
7 Analyzing and Enhancing Images
7-6
improfile displays a plot of t he dat a along t he line.
Not ice t he peaks and valleys and how t hey cor r espond t o t he light and dar k
bands in t he image.
The example below shows how improfile wor ks wit h an RGB image. The r ed
line is dr awn fr om t op t o bot t om.
imshow flowers.tif
improfile
Pixel Values and Statistics
7-7
improfile displays a plot wit h separ at e lines for t he r ed, gr een, and blue
int ensit ies.
Not ice how t he lines cor r espond t o t he color s in t he image. For example, t he
cent r al r egion of t he plot shows high int ensit ies of gr een and r ed, while t he blue
int ensit y is 0. These ar e t he values for t he yellow flower .
Image Contours
You can use t he t oolbox funct ion imcontour t o display a cont our plot of t he dat a
in an int ensit y image. This funct ion is similar t o t he contour funct ion in
MATLAB, but it aut omat ically set s up t he axes so t heir or ient at ion and aspect
r at io mat ch t he image.
7 Analyzing and Enhancing Images
7-8
This example displays a gr ayscale image of gr ains of r ice and a cont our plot of
t he image dat a.
I = imread('rice.tif');
imshow(I)
figure, imcontour(I)
You can use t he clabel funct ion t o label t he levels of t he cont our s. See t he
descr ipt ion of clabel in t he online MATLAB Funct ion Refer ence for det ails.
Image Histogram
An image histogram is a char t t hat shows t he dist r ibut ion of int ensit ies in an
indexed or int ensit y image. The image hist ogr am funct ion imhist cr eat es t his
plot by making n equally spaced bins, each r epr esent ing a r ange of dat a values.
It t hen calculat es t he number of pixels wit hin each r ange. For example, t he
Pixel Values and Statistics
7-9
commands below display an image of gr ains of r ice, and a hist ogr am based on
64 bins.
I = imread('rice.tif');
imshow(I)
figure, imhist(I,64)
The hist ogr am shows a peak at ar ound 100, due t o t he dar k gr ay backgr ound
in t he image.
For infor mat ion about how t o modify an image by changing t he dist r ibut ion of
it s hist ogr am, see Int ensit y Adjust ment on page 7-14.
Summary Statistics
You can comput e st andar d image st at ist ics using t he mean2, std2, and corr2
funct ions. mean2 and std2 comput e t he mean and st andar d deviat ion of t he
element s of a mat r ix. corr2 comput es t he cor r elat ion coefficient bet ween t wo
mat r ices of t he same size.
These funct ions ar e t wo-dimensional ver sions of t he mean, std, and corrcoef
funct ions descr ibed in t he online MATLAB Funct ion Refer ence.
Feature Measurement
You can use t he imfeature funct ion t o comput e feat ur e measur ement s for
image r egions. For example, imfeature can measur e such feat ur es as t he ar ea,
cent er of mass, and bounding box for a r egion you specify. See t he r efer ence
ent r y for imfeature for mor e infor mat ion.
7 Analyzing and Enhancing Images
7-10
Image Analysis
Image analysis t echniques r et ur n infor mat ion about t he st r uct ur e of an image.
This sect ion descr ibes t oolbox funct ions t hat you can use for t hese image
analysis t echniques:
Edge det ect ion
Quadt r ee decomposit ion
The funct ions descr ibed in t his sect ion wor k only wit h gr ayscale int ensit y
images.
Edge Detection
You can use t he edge funct ion t o det ect edges, which ar e t hose places in an
image t hat cor r espond t o object boundar ies. To find edges, t his funct ion looks
for places in t he image wher e t he int ensit y changes r apidly, using one of t hese
t wo cr it er ia:
Places wher e t he fir st der ivat ive of t he int ensit y is lar ger in magnit ude t han
some t hr eshold
Places wher e t he second der ivat ive of t he int ensit y has a zer o cr ossing
edge pr ovides a number of der ivat ive est imat or s, each of which implement s one
of t he definit ions above. For some of t hese est imat or s, you can specify whet her
t he oper at ion should be sensit ive t o hor izont al or ver t ical edges, or bot h. edge
r et ur ns a binar y image cont aining 1s wher e edges ar e found and 0s elsewher e.
The most power ful edge-det ect ion met hod t hat edge pr ovides is t he Canny
met hod. The Canny met hod differ s fr om t he ot her edge-det ect ion met hods in
t hat it uses t wo differ ent t hr esholds (t o det ect st r ong and weak edges), and
includes t he weak edges in t he out put only if t hey ar e connect ed t o st r ong
edges. This met hod is t her efor e less likely t han t he ot her s t o be fooled by
noise, and mor e likely t o det ect t r ue weak edges.
Image Analysis
7-11
The example below illust r at es t he power of t he Canny edge det ect or . It shows
t he r esult s of applying t he Sobel and Canny edge det ect or s t o t he rice.tif
image.
I = imread('rice.tif');
BW1 = edge(I,'sobel');
BW2 = edge(I,'canny');
imshow(BW1)
figure, imshow(BW2)
For an int er act ive demonst r at ion of edge det ect ion, t r y r unning edgedemo.
Quadtree Decomposition
Quadt r ee decomposit ion is an analysis t echnique t hat involves subdividing an
image int o blocks t hat ar e mor e homogeneous t han t he image it self. This
t echnique r eveals infor mat ion about t he st r uct ur e of t he image. It is also useful
as t he fir st st ep in adapt ive compr ession algor it hms.
You can per for m quadt r ee decomposit ion using t he qtdecomp funct ion. This
funct ion wor ks by dividing a squar e image int o four equal-sized squar e blocks,
and t hen t est ing each block t o see if it meet s some cr it er ion of homogeneit y
(e.g., if all of t he pixels in t he block ar e wit hin a specific dynamic r ange). If a
block meet s t he cr it er ion, it is not divided any fur t her . If it does not meet t he
cr it er ion, it is subdivided again int o four blocks, and t he t est cr it er ion is applied
t o t hose blocks. This pr ocess is r epeat ed it er at ively unt il each block meet s t he
cr it er ion. The r esult may have blocks of sever al differ ent sizes.
7 Analyzing and Enhancing Images
7-12
For example, suppose you want t o per for m quadt r ee decomposit ion on a
128-by-128 gr ayscale image. The fir st st ep is t o divide t he image int o four
64-by-64 blocks. You t hen apply t he t est cr it er ion t o each block; for example,
t he cr it er ion might be:
max(block(:)) min(block(:)) <= 0.2
If one of t he blocks meet s t his cr it er ion, it is not divided any fur t her ; it is
64-by-64 in t he final decomposit ion. If a block does not meet t he cr it er ion, it is
t hen divided int o four 32-by-32 blocks, and t he t est is t hen applied t o each of
t hese blocks. The blocks t hat fail t o meet t he cr it er ion ar e t hen divided int o four
16-by-16 blocks, and so on, unt il all blocks pass. Some of t he blocks may be as
small as 1-by-1, unless you specify ot her wise.
The call t o qtdecomp for t his example would be:
S = qtdecomp(I,0.2)
S is r et ur ned as a spar se mat r ix whose nonzer o element s r epr esent t he
upper -left cor ner s of t he blocks; t he value of each nonzer o element indicat es t he
block size. S is t he same size as I.
Not e t hat t he t hr eshold value is specified as a value bet ween 0 and 1,
r egar dless of t he class of I. If I is uint8, t he t hr eshold value you supply is
mult iplied by 255 t o det er mine t he act ual t hr eshold t o use; if I is uint16, t he
t hr eshold value you supply is mult iplied by 65535.
The example below shows an image and a r epr esent at ion of it s quadt r ee
decomposit ion. Each black squar e r epr esent s a homogeneous block, and t he
whit e lines r epr esent t he boundar ies bet ween blocks. Not ice how t he blocks ar e
smaller in ar eas cor r esponding t o lar ge changes in int ensit y in t he image.
Image Analysis
7-13
You can also supply qtdecomp wit h a funct ion (r at her t han a t hr eshold value)
for deciding whet her t o split blocks; for example, you might base t he decision
on t he var iance of t he block. See t he r efer ence ent r y for qtdecomp for mor e
infor mat ion.
For an int er act ive demonst r at ion of quadt r ee decomposit ion, t r y r unning
qtdemo.
7 Analyzing and Enhancing Images
7-14
Image Enhancement
Image enhancement t echniques ar e used t o impr ove an image, wher e
impr ove is somet imes defined object ively (e.g., incr ease t he signal-t o-noise
r at io), and somet imes subject ively (e.g., make cer t ain feat ur es easier t o see by
modifying t he color s or int ensit ies).
This sect ion discusses t hese image enhancement t echniques:
Int ensit y adjust ment
Noise r emoval
The funct ions descr ibed in t his sect ion apply pr imar ily t o gr ayscale int ensit y
images. However , some of t hese funct ions can be applied t o color images as
well. For infor mat ion about how t hese funct ions wor k wit h color images, see
t he r efer ence ent r ies for t he individual funct ions.
Intensity Adjustment
Int ensit y adjust ment is a t echnique for mapping an images int ensit y values t o
a new r ange. For example, look at t he r ice image and it s hist ogr am on page 7-9.
Not e t hat t he image has r at her low cont r ast , and t hat t he hist ogr am indicat es
no values below 40 or above 255. If you r emap t he dat a values t o fill t he ent ir e
int ensit y r ange [0,255], you can incr ease t he cont r ast of t he image.
You can do t his kind of adjust ment wit h t he imadjust funct ion. For example,
t his code per for ms t he adjust ment descr ibed above:
I = imread('rice.tif');
J = imadjust(I,[0.15 0.9],[0 1]);
Not ice t hat t he int ensit ies ar e specified as values bet ween 0 and 1, r egar dless
of t he class of I. If I is uint8, t he values you supply ar e mult iplied by 255 t o
det er mine t he act ual values t o use; if I is uint16, t he values ar e mult iplied by
65535.
Image Enhancement
7-15
Now display t he adjust ed image and it s hist ogr am.
imshow(J)
figure, imhist(J,64)
Not ice t he incr eased cont r ast in t he image, and t hat t he hist ogr am now fills t he
ent ir e r ange.
Similar ly, you can decr ease t he cont r ast of an image by nar r owing t he r ange of
t he dat a, as in t his call:
J = imadjust(I,[0 1],[0.3 0.8]);
The gener al synt ax is,
J = imadjust(I,[low high],[bottom top])
wher e low and high ar e t he int ensit ies in t he input image, which ar e mapped
t o bottom and top in t he out put image.
In addit ion t o incr easing or decr easing cont r ast , you can per for m a wide var iet y
of ot her image enhancement s wit h imadjust. In t he example below, t he mans
coat is t oo dar k t o r eveal any det ail. The call t o imadjust maps t he r ange [0,51]
in t he uint8 input image t o [128,255] in t he out put image. This br ight ens t he
7 Analyzing and Enhancing Images
7-16
image consider ably, and also widens t he dynamic r ange of t he dar k por t ions of
t he or iginal image, making it much easier t o see t he det ails in t he coat .
I = imread('cameraman.tif');
J = imadjust(I,[0 0.2],[0.5 1]);
imshow(I)
figure, imshow(J)
Not ice t hat t his oper at ion r esult s in much of t he image being washed out . This
is because all values above 51 in t he or iginal image get mapped t o 255 in t he
adjust ed image.
Gamma Correction
imadjust maps low t o bottom, and high t o top. By default , t he values bet ween
low and high ar e mapped linear ly t o values bet ween bottom and top. For
example, t he value halfway bet ween low and high cor r esponds t o t he value
halfway bet ween bottom and top.
imadjust can accept an addit ional ar gument which specifies t he gamma
correction fact or . Depending on t he value of gamma, t he mapping bet ween
values in t he input and out put images may be nonlinear . For example, t he
value halfway bet ween low and high may map t o a value eit her gr eat er t han
or less t han t he value halfway bet ween bottom and top.
Gamma can be any value bet ween 0 and infinit y. If gamma is 1 (t he default ),
t he mapping is linear . If gamma is less t han 1, t he mapping is weight ed t owar d
higher (br ight er ) out put values. If gamma is gr eat er t han 1, t he mapping is
weight ed t owar d lower (dar ker ) out put values.
Image Enhancement
7-17
The figur e below illust r at es t his r elat ionship. The t hr ee t r ansfor mat ion cur ves
show how values ar e mapped when gamma is less t han, equal t o, and gr eat er
t han 1. (In each gr aph, t he x-axis r epr esent s t he int ensit y values in t he input
image, and t he y-axis r epr esent s t he int ensit y values in t he out put image.)
The example below illust r at es gamma cor r ect ion. Not ice t hat in t he call t o
imadjust, t he dat a r anges of t he input and out put images ar e specified as
empt y mat r ices. When you specify an empt y mat r ix, imadjust uses t he default
r ange of [0,1]. In t he example, bot h r anges ar e left empt y; t his means t hat
gamma cor r ect ion is applied wit hout any ot her adjust ment of t he dat a.
[X,map] = imread('forest.tif')
I = ind2gray(X,map);
J = imadjust(I,[],[],0.5);
imshow(I)
figure, imshow(J)
low high
bottom
top
> 1
low high
bottom
top
1
low high
bottom
top
< 1
7 Analyzing and Enhancing Images
7-18
Histogram Equalization
The pr ocess of adjust ing int ensit y values can be done aut omat ically by t he
histeq funct ion. histeq per for ms histogram equalization, which involves
t r ansfor ming t he int ensit y values so t hat t he hist ogr am of t he out put image
appr oximat ely mat ches a specified hist ogr am. (By default , histeq t r ies t o
mat ch a flat hist ogr am wit h 64 bins, but you can specify a differ ent hist ogr am
inst ead; see t he r efer ence ent r y for histeq.)
This example illust r at es using histeq t o adjust an int ensit y image. The
or iginal image has low cont r ast , wit h most values in t he middle of t he int ensit y
r ange. histeq pr oduces an out put image having values evenly dist r ibut ed
t hr oughout t he r ange.
I = imread('pout.tif');
J = histeq(I);
imshow(I)
figure, imshow(J)
Image Enhancement
7-19
The example below shows t he hist ogr ams for t he t wo images.
imhist(I)
figure, imhist(J)
histeq can r et ur n an addit ional 1-by-256 vect or t hat shows, for each possible
input value, t he r esult ing out put value. (The values in t his vect or ar e in t he
7 Analyzing and Enhancing Images
7-20
r ange [0,1], r egar dless of t he class of t he input image.) You can plot t his dat a
t o get t he t r ansfor mat ion cur ve. For example,
I = imread('pout.tif');
[J,T] = histeq(I);
plot((0:255)/255,T);
Not ice how t his cur ve r eflect s t he hist ogr ams in t he pr evious figur e, wit h t he
input values being most ly bet ween 0.3 and 0.6, while t he out put values ar e
dist r ibut ed evenly bet ween 0 and 1.
For an int er act ive demonst r at ion of int ensit y adjust ment , t r y r unning
imadjdemo.
Noise Removal
Digit al images ar e pr one t o a var iet y of t ypes of noise. Ther e ar e sever al ways
t hat noise can be int r oduced int o an image, depending on how t he image is
cr eat ed. For example:
If t he image is scanned fr om a phot ogr aph made on film, t he film gr ain is a
sour ce of noise. Noise can also be t he r esult of damage t o t he film, or be
int r oduced by t he scanner it self.
If t he image is acquir ed dir ect ly in a digit al for mat , t he mechanism for
gat her ing t he dat a (such as a CCD det ect or ) can int r oduce noise.
Elect r onic t r ansmission of image dat a can int r oduce noise.
Image Enhancement
7-21
The t oolbox pr ovides a number of differ ent ways t o r emove or r educe noise in
an image. Differ ent met hods ar e bet t er for differ ent kinds of noise. The
met hods available include:
Linear filt er ing
Median filt er ing
Adapt ive filt er ing
Also, in or der t o simulat e t he effect s of some of t he pr oblems list ed above, t he
t oolbox pr ovides t he imnoise funct ion, which you can use t o add var ious t ypes
of noise t o an image. The examples in t his sect ion use t his funct ion.
Linear Filtering
You can use linear filt er ing t o r emove cer t ain t ypes of noise. Cer t ain filt er s,
such as aver aging or Gaussian filt er s, ar e appr opr iat e for t his pur pose. For
example, an aver aging filt er is useful for r emoving gr ain noise fr om a
phot ogr aph. Because each pixel get s set t o t he aver age of t he pixels in it s
neighbor hood, local var iat ions caused by gr ain ar e r educed.
For mor e infor mat ion about linear filt er ing, see Chapt er 5.
Median Filtering
Median filt er ing is similar t o using an aver aging filt er , in t hat each out put
pixel is set t o an aver age of t he pixel values in t he neighbor hood of t he
cor r esponding input pixel. However , wit h median filt er ing, t he value of an
out put pixel is det er mined by t he median of t he neighbor hood pixels, r at her
t han t he mean. The median is much less sensit ive t han t he mean t o ext r eme
values (called outliers). Median filt er ing is t her efor e bet t er able t o r emove
t hese out lier s wit hout r educing t he shar pness of t he image.
The medfilt2 funct ion implement s median filt er ing. The example below
compar es using an aver aging filt er and medfilt2 t o r emove salt and pepper
noise. This t ype of noise consist s of r andom pixels being set t o black or whit e
(t he ext r emes of t he dat a r ange). In bot h cases t he size of t he neighbor hood
used for filt er ing is 3-by-3.
7 Analyzing and Enhancing Images
7-22
Fir st , r ead in t he image and add noise t o it .
I = imread('eight.tif');
J = imnoise(I,'salt & pepper',0.02);
imshow(I)
figure, imshow(J)
Now filt er t he noisy image and display t he r esult s. Not ice t hat medfilt2 does
a bet t er job of r emoving noise, wit h less blur r ing of edges.
K = filter2(fspecial('average',3),J)/255;
L = medfilt2(J,[3 3]);
imshow(K)
figure, imshow(L)
Median filt er ing is a specific case of order-statistic filtering. For infor mat ion
about or der -st at ist ic filt er ing, see t he r efer ence ent r y for t he ordfilt2
funct ion.
Image Enhancement
7-23
Adaptive Filtering
The wiener2 funct ion applies a Wiener filt er (a t ype of linear filt er ) t o an image
adaptively, t ailor ing it self t o t he local image var iance. Wher e t he var iance is
lar ge, wiener2 per for ms lit t le smoot hing. Wher e t he var iance is small, wiener2
per for ms mor e smoot hing.
This appr oach oft en pr oduces bet t er r esult s t han linear filt er ing. The adapt ive
filt er is mor e select ive t han a compar able linear filt er , pr eser ving edges and
ot her high fr equency par t s of an image. In addit ion, t her e ar e no design t asks;
t he wiener2 funct ion handles all pr eliminar y comput at ions, and implement s
t he filt er for an input image. wiener2, however , does r equir e mor e comput at ion
t ime t han linear filt er ing.
wiener2 wor ks best when t he noise is const ant -power (whit e) addit ive noise,
such as Gaussian noise. The example below applies wiener2 t o an image of
Sat ur n t hat 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 int er act ive demonst r at ion of filt er ing t o r emove noise, t r y r unning
nrfiltdemo.
7 Analyzing and Enhancing Images
7-24
8
Binar y Image Oper at ions
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . 8-2
Neighbor hoods . . . . . . . . . . . . . . . . . . . . 8-2
Padding of Bor der s . . . . . . . . . . . . . . . . . . 8-2
Displaying Binar y Images . . . . . . . . . . . . . . . 8-3
Morphologi cal Ope rations . . . . . . . . . . . . . . 8-4
Dilat ion and Er osion . . . . . . . . . . . . . . . . . 8-4
Relat ed Oper at ions . . . . . . . . . . . . . . . . . . 8-7
Obje ct -Base d Ope rations . . . . . . . . . . . . . . 8-10
4- and 8-Connect ed Neighbor hoods . . . . . . . . . . . 8-10
Per imet er Det er minat ion . . . . . . . . . . . . . . . 8-12
Flood Fill . . . . . . . . . . . . . . . . . . . . . . 8-13
Connect ed-Component s Labeling . . . . . . . . . . . . 8-15
Object Select ion . . . . . . . . . . . . . . . . . . . 8-16
Feature Measurement . . . . . . . . . . . . . . . 8-18
Image Ar ea . . . . . . . . . . . . . . . . . . . . . 8-18
Euler Number . . . . . . . . . . . . . . . . . . . . 8-19
Lookup-Table Operati ons . . . . . . . . . . . . . . 8-20
8 Binary Image Operations
8-2
Overview
A binar y image is an image in which each pixel assumes one of only t wo
discr et e values. Essent ially, t hese t wo values cor r espond t o on and off.
Looking at an image in t his way makes it easier t o dist inguish st r uct ur al
feat ur es. For example, in a binar y image, it is easy t o dist inguish object s fr om
t he backgr ound.
In t he Image Pr ocessing Toolbox, a binar y image is st or ed as a t wo-dimensional
mat r ix of 0s (which r epr esent off pixels) and 1s (which r epr esent on pixels).
The on pixels ar e t he for egr ound of t he image, and t he off pixels ar e t he
backgr ound.
Binar y image oper at ions r et ur n infor mat ion about t he for m or st r uct ur e of
binar y images only. To per for m t hese oper at ions on anot her t ype of image, you
must fir st conver t it t o binar y (using, for example, t he im2bw funct ion).
Neighborhoods
Most binar y image algor it hms wor k wit h gr oups of pixels called neighborhoods.
A pixels neighbor hood is some set of pixels, defined by t heir locat ions r elat ive
t o t hat pixel. The neighbor hood can include or omit t he pixel it self, and t he
pixels included in t he neighbor hood ar e not necessar ily adjacent t o t he pixel of
int er est . Differ ent t ypes of neighbor hoods ar e used for differ ent binar y
oper at ions.
Padding of Borders
If a pixel is near t he bor der of an image, some of t he pixels in it s neighbor hood
may be missing. For example, if t he neighbor hood is defined t o include t he pixel
dir ect ly above t he pixel of int er est , t hen a pixel in t he t op r ow of an image will
be missing t his neighbor .
In or der t o det er mine how t o pr ocess t hese pixels, t he binar y image funct ions
pad t he bor der s of t he image, usually wit h 0s. In ot her wor ds, t hese funct ions
pr ocess t he bor der pixels by assuming t hat t he image is sur r ounded by
addit ional r ows and columns of 0s. These r ows and columns do not become par t
of t he out put image and ar e used only as par t s of t he neighbor hoods of t he
act ual pixels in t he image. However , t he padding can in some cases pr oduce
border effects, in which t he r egions near t he bor der s of t he out put image do not
appear t o be homogeneous wit h t he r est of t he image.
Overview
8-3
Displaying Binary Images
When you display a binar y image wit h imshow, by default t he for egr ound (i.e.,
t he on pixels) is whit e and t he backgr ound is black. You may pr efer t o inver t
t hese images when you display or pr int t hem, or else display t hem using a
color map. See Chapt er 2, Displaying Images for mor e infor mat ion about
displaying binar y images.
The r emainder of t his chapt er descr ibes t he funct ions in t he Image Pr ocessing
Toolbox t hat per for m var ious t ypes of binar y image oper at ions. These
oper at ions include:
Mor phological oper at ions
Object -based oper at ions
Feat ur e measur ement
Lookup t able oper at ions
8 Binary Image Operations
8-4
Morphological Operations
Mor phological oper at ions ar e met hods for pr ocessing binar y images based on
shapes. These oper at ions t ake a binar y image as input , and r et ur n a binar y
image as out put . The value of each pixel in t he out put image is based on t he
cor r esponding input pixel and it s neighbor s. By choosing t he neighbor hood
shape appr opr iat ely, you can const r uct a mor phological oper at ion t hat is
sensit ive t o specific shapes in t he input image.
Dilation and Erosion
The main mor phological oper at ions ar e dilation and erosion. Dilat ion and
er osion ar e r elat ed oper at ions, alt hough t hey pr oduce ver y differ ent r esult s.
Dilat ion adds pixels t o t he boundar ies of object s (i.e., changes t hem fr om off t o
on), while er osion r emoves pixels on object boundar ies (changes t hem fr om on
t o off).
Each dilat ion or er osion oper at ion uses a specified neighbor hood. The st at e of
any given pixel in t he out put image is det er mined by applying a r ule t o t he
neighbor hood of t he cor r esponding pixel in t he input image. The r ule used
defines t he oper at ion as a dilat ion or an er osion:
For dilat ion, if any pixel in t he input pixels neighbor hood is on, t he out put
pixel is on. Ot her wise, t he out put pixel is off.
For er osion, if every pixel in t he input pixels neighbor hood is on, t he out put
pixel is on. Ot her wise, t he out put pixel is off.
The neighbor hood for a dilat ion or er osion oper at ion can be of ar bit r ar y shape
and size. The neighbor hood is r epr esent ed by a structuring element, which is a
mat r ix consist ing of only 0s and 1s. The center pixel in t he st r uct ur ing element
r epr esent s t he pixel of int er est , while t he element s in t he mat r ix t hat ar e on
(i.e., = 1) define t he neighbor hood.
The cent er pixel is defined as floor((size(SE)+1)/2), wher e SE is t he
st r uct ur ing element . For example, in a 4-by-7 st r uct ur ing element , t he cent er
pixel is (2,4). When you const r uct t he st r uct ur ing element , you should make
sur e t hat t he pixel of int er est is act ually t he cent er pixel. You can do t his by
adding r ows or columns of 0s, if necessar y. For example, suppose you want t he
neighbor hood t o consist of a 3-by-3 block of pixels, wit h t he pixel of int er est in
t he upper -left cor ner of t he block. The st r uct ur ing element would not be
Morphological Operations
8-5
ones(3), because t his mat r ix has t he wr ong cent er pixel. Rat her , you could use
t his mat r ix as t he st r uct ur ing element :
0 0 0 0
0 1 1 1
0 1 1 1
0 1 1 1
For er osion, t he neighbor hood consist s of t he on pixels in t he st r uct ur ing
element . For dilat ion, t he neighbor hood consist s of t he on pixels in t he
st r uct ur ing element r ot at ed 180 degr ees. (The cent er pixel is st ill select ed
befor e t he r ot at ion.)
Suppose you want t o per for m an er osion oper at ion. The figur e below shows a
sample neighbor hood you might use. Each neighbor hood pixel is indicat ed by
an x, and t he cent er pixel is t he one wit h a cir cle:
The st r uct ur ing element is t her efor e:
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
x
x
x
x
x
8 Binary Image Operations
8-6
The st at e (i.e., on or off) of any given pixel in t he out put image is det er mined
by applying t he er osion r ule t o t he neighbor hood pixels for t he cor r esponding
pixel in t he input image. For example, t o det er mine t he st at e of t he pixel (4,6)
in t he out put image:
Over lay t he st r uct ur ing element on t he input image, wit h t he cent er pixel of
t he st r uct ur ing element cover ing t he pixel (4,6).
Look at t he pixels in t he neighbor hood of t he input pixel. These ar e t he five
pixels cover ed by 1s in t he st r uct ur ing element . In t his case t he pixels ar e:
(2,4), (3,5), (4,6), (5,7), (6,8). If all of t hese pixels ar e on, t hen set t he pixel in
t he out put image (4,6) t o on. If any of t hese pixels is off, t hen set t he pixel
(4,6) in t he out put image t o off.
You per for m t his pr ocedur e for each pixel in t he input image t o det er mine t he
st at e of each cor r esponding pixel in t he out put image.
Not e t hat for pixels on bor der s of t he image, some of t he 1s in t he st r uct ur ing
element ar e act ually out side t he image. These element s ar e assumed t o cover
off pixels. As a r esult , t he out put image will usually have a black bor der , as in
t he example below.
The Image Pr ocessing Toolbox per for ms dilat ion t hr ough t he dilate funct ion,
and er osion t hr ough t he erode funct ion. Each of t hese funct ions t akes an input
image and a st r uct ur ing element as input , and r et ur ns an out put image.
Morphological Operations
8-7
This example illust r at es t he er osion oper at ion descr ibed above.
BW1 = imread('circbw.tif');
SE = eye(5);
BW2 = erode(BW1,SE);
imshow(BW1)
figure, imshow(BW2)
Not ice t he diagonal st r eaks in t he out put image (on t he r ight ). These ar e due
t o t he shape of t he st r uct ur ing element .
Related Operations
Ther e ar e many ot her t ypes of mor phological oper at ions in addit ion t o dilat ion
and er osion. However , many of t hese oper at ions ar e just modified dilat ions or
er osions, or combinat ions of dilat ion and er osion. For example, closure consist s
of a dilat ion oper at ion followed by er osion wit h t he same st r uct ur ing element .
A r elat ed oper at ion, opening, is t he r ever se of closur e; it consist s of er osion
followed by dilat ion.
For example, suppose you want t o r emove all t he cir cuit lines fr om t he or iginal
cir cuit image, leaving only t he r ect angular out lines of micr ochips. You can
accomplish t his t hr ough opening.
To per for m t he opening, you begin by choosing a st r uct ur ing element . This
st r uct ur ing element should be lar ge enough t o r emove t he lines when you er ode
t he image, but not lar ge enough t o r emove t he r ect angles. It should consist of
8 Binary Image Operations
8-8
all 1s, so it r emoves ever yt hing but lar ge cont inuous pat ches of for egr ound
pixels. Ther efor e, you cr eat e t he st r uct ur ing element like t his:
SE = ones(40,30);
Next , you per for m t he er osion. This r emoves all of t he lines, but also shr inks
t he r ect angles.
BW2 = erode(BW1,SE);
imshow(BW2)
Finally, you per for m dilat ion, using t he same st r uct ur ing element , t o r est or e
t he r ect angles t o t heir or iginal sizes.
BW3 = dilate(BW2,SE);
imshow(BW3)
Morphological Operations
8-9
Predefined Operations
You can use dilate and erode t o implement any mor phological oper at ion t hat
can be defined as a set of dilat ions and er osions. However , t her e ar e cer t ain
oper at ions t hat ar e so common t hat t he t oolbox pr ovides t hem as pr edefined
pr ocedur es. These oper at ions ar e available t hr ough t he bwmorph funct ion.
bwmorph pr ovides eight een pr edefined oper at ions, including opening and
closur e.
For example, suppose you want t o r educe all object s in t he cir cuit image t o
lines, wit hout changing t he essent ial st r uct ur e (t opology) of t he image. This
pr ocess is known as skeletonization. You can use bwmorph t o do t his.
BW1 = imread('circbw.tif');
BW2 = bwmorph(BW1,'skel',Inf);
imshow(BW1)
figure, imshow(BW2)
The t hir d ar gument t o bwmorph indicat es t he number of t imes t o per for m t he
oper at ion. For example, if t his value is 2, t he oper at ion is per for med t wice, wit h
t he r esult of t he fir st oper at ion being used as t he input for t he second
oper at ion. In t he example above, t he value is Inf. In t his case bwmorph
per for ms t he oper at ion r epeat edly unt il it no longer changes.
For mor e infor mat ion about t he pr edefined oper at ions available, see t he
r efer ence ent r y for bwmorph.
8 Binary Image Operations
8-10
Object-Based Operations
In a binar y image, an object is any set of connect ed pixels wit h t he value 1.
(meaning t hat t hey ar e on). For example, t his mat r ix r epr esent s a binar y
image cont aining a single object , a 3-by-3 squar e. The r est of t he image is
backgr ound.
0 0 0 0 0 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
This sect ion discusses t he t ypes of neighbor hoods used for object -based
oper at ions, and descr ibes how t o use t oolbox funct ions t o per for m:
Per imet er det er minat ion
Binar y flood fill
Connect ed-component s labeling
Object select ion
4- and 8-Connected Neighborhoods
For many oper at ions, dist inguishing object s depends on t he convent ion used t o
decide whet her pixels ar e connect ed. Ther e ar e t wo differ ent convent ions
t ypically used: 4-connect ed or 8-connect ed neighbor hoods.
In an 8-connect ed neighbor hood, all of t he pixels t hat t ouch t he pixel of int er est
ar e consider ed, including t hose on t he diagonals. This means t hat if t wo
adjoining pixels ar e on, t hey ar e par t of t he same object , r egar dless of whet her
t hey ar e connect ed along t he hor izont al, ver t ical, or diagonal dir ect ion.
Object-Based Operations
8-11
This figur e illust r at es an 8-connect ed neighbor hood.
In a 4-connect ed neighbor hood, t he pixels along t he diagonals ar e not
consider ed. This means t hat t wo adjoining pixels ar e par t of t he same object
only if t hey ar e bot h on and ar e connect ed along t he hor izont al or ver t ical
dir ect ion.
This figur e illust r at es a 4-connect ed neighbor hood.
r, c1 r, c
r+1, c
r, c+1
r1, c r1, c1
r+1, c+1
r1, c+1
r+1, c1
r, c1 r, c
r+1, c
r, c+1
r1, c
8 Binary Image Operations
8-12
The t ype of neighbor hood you choose affect s t he number of object s t her e ar e in
an image and t he boundar ies of t hose object s. Ther efor e, t he r esult s of t he
object -based oper at ions oft en differ for t he t wo t ypes of neighbor hoods.
For example, t his mat r ix r epr esent s a binar y image t hat has one 8-connect ed
object or t wo 4-connect ed object s.
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
Perimeter Determination
The bwperim funct ion det er mines t he per imet er pixels of t he object s in a binar y
image. You can use eit her a 4- or 8-connect ed neighbor hood for per imet er
det er minat ion. A pixel is consider ed a per imet er pixel if it sat isfies bot h of
t hese cr it er ia:
It is an on pixel.
One (or mor e) of t he pixels in it s neighbor hood is off.
This example finds t he per imet er pixels in t he cir cuit image:
BW1 = imread('circbw.tif');
BW2 = bwperim(BW1);
imshow(BW1)
figure, imshow(BW2)
Object-Based Operations
8-13
Flood Fill
The bwfill funct ion per for ms a flood-fill oper at ion on a binar y image. You
specify a backgr ound pixel as a st ar t ing point , and bwfill changes connect ed
backgr ound pixels (0s) t o for egr ound pixels (1s), st opping when it r eaches
object boundar ies. The boundar ies ar e det er mined based on t he t ype of
neighbor hood you specify.
This oper at ion can be useful in r emoving ir r elevant ar t ifact s fr om images. For
example, suppose you have a binar y image, der ived fr om a phot ogr aph, in
which t he for egr ound object s r epr esent spher es. In t he binar y image, t hese
object s should appear as cir cles, but inst ead ar e donut shaped because of
r eflect ions in t he or iginal phot ogr aph. Befor e doing any fur t her pr ocessing of
t he image, you may want t o fir st fill in t he donut holes using bwfill.
bwfill differ s fr om t he ot her object -based oper at ions in t hat it oper at es on
backgr ound pixels, r at her t han t he for egr ound. If t he for egr ound is
8-connect ed, t he backgr ound is 4-connect ed, and vice ver sa. Not e, however ,
t hat as wit h t he ot her object -based funct ions, you specify t he connect edness of
t he for egr ound when you call bwfill.
The implicat ions of 4- vs. 8-connect ed for egr ound can be illust r at ed wit h t his
mat r ix:
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
Regar dless of whet her t he for egr ound is 4-connect ed or 8-connect ed, t his image
cont ains a single object . However , t he t opology of t he object differ s depending
on t he t ype of neighbor hood. If t he for egr ound is 8-connect ed, t he object is a
closed cont our , and t her e ar e t wo separ at e backgr ound element s (t he par t
inside t he loop and t he par t out side). If t he for egr ound is 4-connect ed, t he
cont our is open, and t her e is only one backgr ound element .
8 Binary Image Operations
8-14
Suppose you call bwfill, specifying t he pixel BW1(4,3) as t he st ar t ing 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 t he inside of t he loop, because bwfill uses an 8-connect ed
for egr ound by default . If you specify a 4-connect ed for egr ound inst ead, bwfill
fills in t he ent ir e image, because t he ent ir e backgr ound is a single 8-connect ed
element . For example,
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
Not e t hat unlike ot her binar y image oper at ions, bwfill pads wit h 1s r at her
t han 0s along t he image bor der . This pr event s t he fill oper at ion fr om wr apping
ar ound t he bor der .
You can also use bwfill int er act ively, select ing st ar t ing pixels wit h a mouse.
See t he r efer ence ent r y for bwfill for mor e infor mat ion.
Object-Based Operations
8-15
Connected-Components Labeling
You can use t he bwlabel funct ion t o per for m connected-components labeling,
which is a met hod for indicat ing each discr et e object in a binar y image. You
specify t he input binar y image and t he t ype of neighbor hood, and bwlabel
r et ur ns a mat r ix of t he same size as t he input image. The differ ent object s in
t he input image ar e dist inguished by differ ent int eger values in t he out put
mat r ix.
For example, suppose you have t his binar y image:
BW1 =
0 0 0 0 0 0 0 0
0 1 1 0 0 1 1 1
0 1 1 0 0 0 1 1
0 1 1 0 0 0 0 0
0 0 0 1 1 0 0 0
0 0 0 1 1 0 0 0
0 0 0 1 1 0 0 0
0 0 0 0 0 0 0 0
You call bwlabel, specifying 4-connect ed neighbor hoods.
bwlabel(BW1,4)
ans =
0 0 0 0 0 0 0 0
0 1 1 0 0 3 3 3
0 1 1 0 0 0 3 3
0 1 1 0 0 0 0 0
0 0 0 2 2 0 0 0
0 0 0 2 2 0 0 0
0 0 0 2 2 0 0 0
0 0 0 0 0 0 0 0
In t he out put mat r ix, t he 1s r epr esent one object , t he 2s a second object , and
t he 3s a t hir d. Not ice t hat if you had used 8-connect ed neighbor hoods (t he
default ), t her e would be only t wo object s, because t he fir st and second object s
would be a single object , connect ed along t he diagonal.
8 Binary Image Operations
8-16
The out put mat r ix is not a binar y image, and it s class is double. A useful
appr oach t o viewing it is t o display it as a pseudocolor indexed image, fir st
adding 1 t o each element , so t hat t he dat a is in t he pr oper r ange. Each object
displays in a differ ent color , so t he object s ar e easier t o dist inguish t han in t he
or iginal image.
The example below illust r at es t his t echnique. Not ice t hat t his example uses a
color map in which t he fir st color (t he backgr ound) is black and t he ot her color s
ar e easily dist inguished.
X = bwlabel(BW1,4);
map = [0 0 0;jet(3)];
imshow(X+1,map,'notruesize')
Object Selection
You can use t he bwselect funct ion t o select individual object s in a binar y
image. You specify pixels in t he input image, and bwselect r et ur ns a binar y
image t hat includes only t hose object s fr om t he input image t hat cont ain one of
t he specified pixels.
You can specify t he pixels eit her nonint er act ively or wit h a mouse. For
example, suppose you want t o select 8-connect ed object s in t he image displayed
in t he cur r ent axes. You t ype:
BW2 = bwselect(8);
The cur sor changes t o a cr oss-hair when it is over t he image. Click on t he
object s you want t o select ; bwselect displays a small st ar over each pixel you
click on. When you ar e done, pr ess Return. bwselect r et ur ns a binar y image
consist ing of t he object s you select ed, and r emoves t he st ar s.
Object-Based Operations
8-17
See t he r efer ence ent r y for bwselect for mor e infor mat ion.
8 Binary Image Operations
8-18
Feature Measurement
When you pr ocess an image, you may want t o obt ain infor mat ion about how
cer t ain feat ur es of t he image change. For example, when you per for m dilat ion,
you may want t o det er mine how many pixels ar e changed fr om off t o on by t he
oper at ion, or t o see if t he number of object s in t he image changes. This sect ion
descr ibes t wo funct ions, bwarea and bweuler, t hat r et ur n t wo common
measur es of binar y images: t he image ar ea and t he Euler number .
In addit ion, you can use t he imfeature funct ion, in combinat ion wit h bwlabel,
t o comput e measur ement s of var ious feat ur es in a binar y image. See t he
r efer ence ent r y for imfeature for mor e infor mat ion.
Image Area
The bwarea funct ion r et ur ns t he ar ea of a binar y image. The ar ea is a measur e
of t he size of t he for egr ound of t he image. Roughly speaking, t he ar ea is t he
number of on pixels in t he image.
bwarea does not simply count t he number of on pixels, however . Rat her , bwarea
weight s differ ent pixel pat t er ns unequally when comput ing t he ar ea. This
weight ing compensat es for t he dist or t ion t hat is inher ent in r epr esent ing a
cont inuous image wit h discr et e pixels. For example, a diagonal line of 50 pixels
is longer t han a hor izont al line of 50 pixels. As a r esult of t he weight ing bwarea
uses, t he hor izont al line has ar ea of 50, but t he diagonal line has ar ea of 62.5.
This example uses bwarea t o det er mine how much t he ar ea of t he cir cuit image
incr eases aft er a dilat ion oper at ion:
BW1 = imread('circbw.tif');
SE = ones(5);
BW2 = dilate(BW1,SE);
increase = (bwarea(BW2) bwarea(BW1))/bwarea(BW1);
increase =
0.3456
The dilat ion incr eases t he ar ea by about 35 per cent .
See t he r efer ence ent r y for bwarea for mor e infor mat ion about t he weight ing
pat t er n.
Feature Measurement
8-19
Euler Number
The bweuler funct ion r et ur ns t he Euler number for a binar y image. The Euler
number is a measur e of t he t opology of an image. It is defined as t he t ot al
number of object s in t he image minus t he number of holes in t hose object s. You
can use eit her 4- or 8-connect ed neighbor hoods.
This example comput es t he Euler number for t he cir cuit image, using
8-connect ed neighbor hoods:
BW1 = imread('circbw.tif');
eul = bweuler(BW1,8)
eul =
85
In t his example, t he Euler number is negat ive, indicat ing t hat t he number of
holes is gr eat er t han t he number of object s.
8 Binary Image Operations
8-20
Lookup-Table Operations
Cer t ain binar y image oper at ions can be implement ed most easily t hr ough
lookup t ables. A lookup t able is a column vect or in which each element
r epr esent s t he value t o r et ur n for one possible combinat ion of pixels in a
neighbor hood.
You can use t he makelut funct ion t o cr eat e lookup t ables for var ious
oper at ions. makelut cr eat es lookup t ables for 2-by-2 and 3-by-3 neighbor hoods.
This figur e illust r at es t hese t ypes of neighbor hoods. Each neighbor hood pixel
is indicat ed by an x, and t he cent er pixel is t he one wit h a cir cle.
For a 2-by-2 neighbor hood, t her e ar e 16 possible per mut at ions of t he pixels in
t he neighbor hood. Ther efor e, t he lookup t able for t his oper at ion is a 16-element
vect or . For a 3-by-3 neighbor hood, t her e ar e 512 per mut at ions, so t he lookup
t able is a 512-element vect or .
Once you cr eat e a lookup t able, you can use it t o per for m t he desir ed oper at ion
by using t he applylut funct ion.
The example below illust r at es using lookup-t able oper at ions t o modify an
image cont aining t ext . You begin by wr it ing a funct ion t hat r et ur ns 1 if t hr ee
or mor e pixels in t he 3-by-3 neighbor hood ar e 1, and 0 ot her wise. You t hen call
makelut, passing in t his funct ion as t he fir st ar gument , and using t he second
ar gument t o specify a 3-by-3 lookup t able.
f = inline('sum(x(:)) >= 3');
lut = makelut(f,3);
lut is r et ur ned as a 512-element vect or of 1s and 0s. Each value is t he out put
fr om t he funct ion for one of t he 512 possible per mut at ions.
x
x x
x
x x
x
x
x x
x x x
2-by-2 neighborhood 3-by-3 neighborhood
Lookup-Table Operations
8-21
You t hen per for m t he oper at ion using applylut.
BW1 = imread('text.tif');
BW2 = applylut(BW1,lut);
imshow(BW1)
figure, imshow(BW2)
For infor mat ion about how applylut maps pixel combinat ions in t he image t o
ent r ies in t he lookup t able, see t he r efer ence ent r y for applylut.
Not e t hat you cannot use makelut and applylut for neighbor hoods of sizes
ot her t han 2-by-2 or 3-by-3. These funct ions suppor t only 2-by-2 and 3-by-3
neighbor hoods, because lookup t ables ar e not pr act ical for neighbor hoods
lar ger t han 3-by-3. For example, a lookup t able for a 4-by-4 neighbor hood
would have 65,536 ent r ies.
8 Binary Image Operations
8-22
9
Region-Based Pr ocessing
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . 9-2
Speci fyi ng a Regi on of Interest . . . . . . . . . . . 9-3
Select ing a Polygon . . . . . . . . . . . . . . . . . . 9-3
Ot her Select ion Met hods . . . . . . . . . . . . . . . 9-5
Fi lteri ng a Region . . . . . . . . . . . . . . . . . 9-6
Fi lli ng a Regi on . . . . . . . . . . . . . . . . . . 9-8
9 Region-Based Processing
9-2
Overview
This chapt er descr ibes oper at ions t hat you can per for m on a select ed r egion of
an image. It discusses t hese t opics:
Specifying a r egion
Filt er ing a r egion
Filling a r egion
For an int er act ive demonst r at ion of r egion-based pr ocessing, t r y r unning
roidemo.
Specifying a Region of Interest
9-3
Specifying a Region of Interest
A region of interest is a por t ion of an image t hat you want t o filt er or per for m
some ot her oper at ion on. You define a r egion of int er est by cr eat ing a binary
mask, which is a binar y image wit h t he same size as t he image you want t o
pr ocess. The mask cont ains 1s for all pixels t hat ar e par t of t he r egion of
int er est , and 0s ever ywher e else.
This sect ion discusses met hods for cr eat ing binar y masks.
Selecting a Polygon
You can use t he roipoly funct ion t o specify a polygonal r egion of int er est . If
you call roipoly wit h no input ar gument s, t he cur sor changes t o a cr oss hair
when it is over t he image displayed in t he cur r ent axes. You can t hen specify
t he ver t ices of t he polygon by clicking on point s in t he image wit h t he mouse.
When you ar e done select ing ver t ices, pr ess Return; roipoly r et ur ns a binar y
image of t he same size as t he input image, cont aining 1s inside t he specified
polygon, and 0s ever ywher e else.
9 Region-Based Processing
9-4
The example below illust r at es using roipoly t o cr eat e a binar y mask. The
bor der of t he select ed r egion is shown in r ed on t he or iginal image.
I = imread('pout.tif');
imshow(I)
BW = roipoly;
imshow(BW)
You can also use roipoly nonint er act ively. See t he r efer ence ent r y for roipoly
for mor e infor mat ion.
Specifying a Region of Interest
9-5
Other Selection Methods
roipoly pr ovides an easy way t o cr eat e a binar y mask. However , you can use
any binar y image as a mask, pr ovided t hat t he binar y image is t he same size
as t he image being filt er ed.
For example, suppose you want t o filt er t he int ensit y image I, filt er ing only
t hose pixels whose values ar e gr eat er t han 0.5. You can cr eat e t he appr opr iat e
mask wit h t his command:
BW = (I > 0.5);
You can also use t he roicolor funct ion t o define t he r egion of int er est based on
a color or int ensit y r ange. For mor e infor mat ion, see t he r efer ence ent r y for
roicolor.
9 Region-Based Processing
9-6
Filtering a Region
You can use t he roifilt2 funct ion t o pr ocess a r egion of int er est . When you call
roifilt2, you specify an int ensit y image, a binar y mask, and a filt er . roifilt2
filt er s t he input image and r et ur ns an image t hat consist s of filt er ed values for
pixels wher e t he binar y mask cont ains 1s, and unfilt er ed values for pixels
wher e t he binar y mask cont ains 0s. This t ype of oper at ion is called masked
filtering.
This example uses t he mask cr eat ed on page 9-4 t o incr ease t he cont r ast of t he
logo on t he gir ls coat .
h = fspecial('unsharp');
I2 = roifilt2(h,I,BW);
imshow(I)
figure, imshow(I2)
roifilt2 also enables you t o specify your own funct ion t o oper at e on t he r egion
of int er est . In t he example below, t he imadjust funct ion is used t o light en par t s
Filtering a Region
9-7
of an image. The mask in t he example is a binar y image cont aining t ext . The
r esult ing image has t he t ext impr int ed on it .
BW = imread('text.tif');
I = imread('cameraman.tif');
f = inline('imadjust(x,[],[],0.3)');
I2 = roifilt2(I,BW,f);
imshow(I2)
Not e t hat roifilt2 is best suit ed t o oper at ions t hat r et ur n dat a in t he same
r ange as in t he or iginal image because t he out put image t akes some of it s dat a
dir ect ly fr om t he input image. Cer t ain filt er ing oper at ions can r esult in values
out side t he nor mal image dat a r ange (i.e., [0,1] for images of class double,
[0,255] for images of class uint8, [0,65535] for images of class uint16). For
mor e infor mat ion about roifilt2, see t he r efer ence ent r y.
9 Region-Based Processing
9-8
Filling a Region
You can use t he roifill funct ion t o fill a r egion of int er est , int er polat ing fr om
t he bor der s of t he r egion. This funct ion is useful for image edit ing, including
r emoval of ext r aneous det ails or ar t ifact s.
roifill per for ms t he fill oper at ion using an int er polat ion met hod based on
Laplaces equat ion. This met hod r esult s in t he smoot hest possible fill, given t he
values on t he boundar y of t he r egion.
As wit h roipoly, you select t he r egion of int er est wit h t he mouse. When you
complet e t he select ion, roifill r et ur ns an image wit h t he select ed r egion filled
in.
Filling a Region
9-9
This example uses roifill t o modify t he trees image. The bor der of t he
select ed r egion is shown in r ed on t he or iginal image.
load trees
I = ind2gray(X,map);
imshow(I)
I2 = roifill;
imshow(I2)
9 Region-Based Processing
9-10
10
Color
Ove rvi ew . . . . . . . . . . . . . . . . . . . . . 10-2
Worki ng wi th Di ffe re nt Color De pths . . . . . . . . 10-3
Reduci ng the Number of Colors in an Image . . . . . 10-5
Using r gb2ind . . . . . . . . . . . . . . . . . . . . 10-6
Using imappr ox . . . . . . . . . . . . . . . . . . . 10-8
Dit her ing . . . . . . . . . . . . . . . . . . . . . . 10-8
Convert i ng t o Ot her Color Spaces . . . . . . . . . . 10-9
NTSC For mat . . . . . . . . . . . . . . . . . . . . 10-9
YCbCr For mat . . . . . . . . . . . . . . . . . . . 10-10
HSV For mat . . . . . . . . . . . . . . . . . . . 10-10
10 Color
10-2
Overview
This chapt er descr ibes t oolbox funct ions t hat help you wor k wit h color image
dat a. It discusses t hese t opics:
Wor king on syst ems wit h differ ent color dept hs
Reducing t he number of color s in an image
Conver t ing an image t o a differ ent color space
Not e t hat color includes shades of gr ay; t her efor e much of t he discussion in
t his chapt er applies t o gr ayscale images as well as color images.
For addit ional infor mat ion about how MATLAB handles color , see t he Using
MATLAB Graphics manual.
Working with Different Color Depths
10-3
Working with Different Color Depths
Most comput er displays use eit her 8, 16, or 24 bit s per scr een pixel. The
number of bit s per pixel det er mines how many differ ent color s t he syst em can
display.
A 24-bit display pr ovides opt imal color r esolut ion. It uses 8 bit s for each of t he
t hr ee color component s; t her efor e, t her e ar e 256 levels each of r ed, gr een, and
blue. This makes it possible t o suppor t 16,777,216 (i.e., 2
24
) dist inct color s. Of
t hese color s, 256 ar e shades of gr ay. (These ar e t he color s wher e R=G=B.)
16-bit displays also pr ovide a lar ge number of color s.They use 5 bit s for each
color component , r esult ing in 32 shades each of r ed, gr een, and blue. (Some
16-bit displays use t he r emaining bit t o incr ease t he number of shades of gr een
t o 64.) 16-bit displays suppor t 32,768 (i.e., 2
15
) dist inct color s (or t wice t his
number if all 16 bit s ar e used). Of t hese color s, 32 ar e shades of gr ay. (The
number of color s used is syst em dependent .)
8-bit displays suppor t a much mor e limit ed number of color s. An 8-bit display
can pr oduce any of t he color s available on a 24-bit display, but only 256 dist inct
color s can appear at one t ime. Ther e ar e 256 shades of gr ay available, but using
all of t hem t akes up all of t he available color slot s.
To det er mine your syst ems color dept h, ent er t his command at t he MATLAB
pr ompt :
get(0,'ScreenDepth')
MATLAB will r et ur n an int eger r epr esent ing t he number of bit s per pixel. Not e
t hat on some syst ems, MATLAB may r et ur n 32. These syst ems pr oduce 24-bit
color ; t he r emaining 8 bit s ar e for an alpha (t r anspar ency) channel t hat
MATLAB does not cur r ent ly use.
10 Color
10-4
Depending on your syst em, you may be able t o choose t he color dept h you want
t o use. (Ther e may be t r ade-offs bet ween color dept h and scr een r esolut ion.) In
gener al, 24-bit display mode pr oduces t he best r esult s. If you need t o use a
lower color dept h, 16-bit is gener ally pr efer able t o 8-bit . However , keep in mind
t hat 16-bit color has cer t ain limit at ions:
An image may have finer gr adat ions of color t han a 16-bit display can
r epr esent . If a color is unavailable, MATLAB uses t he closest appr oximat ion.
Ther e ar e only 32 shades of gr ay available. If you ar e wor king pr imar ily wit h
gr ayscale images, you may get bet t er display r esult s using 8-bit display
mode.
Regar dless of t he number of color s your syst em can display, MATLAB can st or e
and pr ocess images wit h up t o 2
24
color s (or even mor e, for RGB images of class
uint16 or double). These images display best on syst ems wit h 24-bit color , and
usually look fine on 16-bit syst ems as well.
Somet imes gr ayscale images do not display well on 16-bit syst ems, because
only 32 dist inct shades of gr ay will be available. And, if your display suppor t s
only 8-bit color , you may r un int o pr oblems due t o t he limit ed number of color
slot s. See Chapt er 2 for infor mat ion about wor king ar ound t hese pr oblems.
Also, see t he next sect ion for infor mat ion about r educing t he number of color s
used by an image.
Reducing the Number of Colors in an Image
10-5
Reducing the Number of Colors in an Image
On syst ems wit h 24-bit color , RGB (t r uecolor ) images can display up t o 2
24
(i.e.,
16,777,216) color s. On syst ems wit h lower color dept hs, RGB images display
r easonably well, because MATLAB aut omat ically uses color appr oximat ion
and dit her ing if needed. MATLAB can also r ead and wr it e t hese images using
imread and imwrite, wit hout any loss of color r esolut ion.
Indexed images, however , may cause pr oblems if t hey have a lar ge number of
color s. In gener al, you should limit indexed images t o 256 color s, because:
On syst ems wit h 8-bit color , indexed images wit h mor e t han 256 color s may
not display well.
If an indexed image has mor e t han 256 color s, MATLAB cannot st or e t he
image dat a in a uint8 ar r ay, but will gener ally use an ar r ay of class double
inst ead.
Most image file for mat s limit indexed images t o 256 color s. imwrite pr oduces
an er r or if you t r y t o wr it e an indexed image wit h mor e t han 256 color s t o one
of t hese for mat s.
This sect ion descr ibes how t o r educe t he number of color s in an indexed or RGB
image:
The rgb2ind funct ion conver t s an RGB image t o an indexed image, and
pr ovides a number of met hods for appr oximat ing t he or iginal image wit h
fewer color s.
The imapprox funct ion uses t he same color -appr oximat ion met hods t hat
rgb2ind uses on an indexed image, and r et ur ns a new indexed image t hat
uses fewer color s.
In addit ion, t his sect ion includes a discussion of dit her ing, which is used by
t hese funct ions t o incr ease t he appar ent color r esolut ion of an image.
10 Color
10-6
Using rgb2ind
rgb2ind conver t s an RGB image t o an indexed image, r educing t he number of
color s in t he pr ocess. This funct ion pr ovides t hese met hods for appr oximat ing
t he color s in t he or iginal image:
Quant izat ion
Color map mapping
The qualit y of t he r esult ing image depends on t he appr oximat ion met hod you
use, t he r ange of color s in t he input image, and whet her or not you use
dit her ing. Not e t hat differ ent met hods wor k bet t er for differ ent images. See
page 10-8 for infor mat ion about dit her ing.
Quantization
In gener al, t he most effect ive appr oach t o r educing t he number of color s in an
image is quantization. This appr oach involves cut t ing t he RGB color cube int o
a number of smaller r egions, and t hen mapping all color s t hat fall wit hin a
given r egion t o t he value at t he cent er of t hat r egion. Quant izat ion ensur es t hat
t he color s in t he out put image do not deviat e t oo much fr om t hose in t he input
image, and also enables you t o cont r ol t he maximum number of out put color s.
rgb2ind suppor t s t wo quant izat ion met hods: uniform quantization and
minimum variance quantization. These met hods differ in t he appr oach used t o
divide up t he RGB cube. Wit h unifor m quant izat ion, t he color cube is cut up
int o equal-sized cubes. Wit h minimum var iance quant izat ion, t he color cube is
cut up int o smaller boxes (not necessar ily cubes) of differ ent sizes; t he sizes of
t he boxes depend on how t he color s ar e dist r ibut ed in t he image.
For a given number of color s, minimum var iance quant izat ion pr oduces bet t er
r esult s t han unifor m quant izat ion, because it t akes int o account t he act ual
dat a. Minimum var iance quant izat ion allocat es mor e of t he color map ent r ies t o
color s t hat appear fr equent ly in t he input image, and fewer ent r ies t o color s
t hat appear infr equent ly. For example, if t he input image has many shades of
gr een and few shades of r ed, t her e will be many mor e gr eens t han r eds in t he
out put color map. The r esult ing color r esolut ion is higher t han wit h unifor m
quant izat ion. However , t he comput at ion t akes longer .
To per for m unifor m quant izat ion, you call rgb2ind and specify a t oler ance. The
t oler ance det er mines t he size of t he cubes int o which t he RGB color cube is cut .
Reducing the Number of Colors in an Image
10-7
For example, if you specify a t oler ance of 0.1, t he edges of t he cubes ar e
one-t ent h t he lengt h of t he RGB cube. The t ot al number of small cubes is:
n = (floor(1/tol)+1)^3
Each cube r epr esent s a single color in t he out put image. Ther efor e, t he
maximum lengt h of t he color map is n. rgb2ind r emoves any color s t hat do not
appear in t he input image, so t he act ual color map may be much smaller t han n.
To per for m minimum var iance quant izat ion, you call rgb2ind and specify t he
maximum number of color s in t he out put images color map. The number you
specify det er mines how many cubes int o which t he RGB color cube is divided.
The r esult ing color map usually has t he number of ent r ies you specify, because
t he color cube is divided so t hat each r egion cont ains at least one color t hat
appear s in t he input image. If t he input image act ually uses fewer color s t han
t he number you specify, t he out put color map is also smaller . In t his case, t he
out put image has all of t he color s of t he input image, and t her e is no loss of color
r esolut ion in t he conver sion.
These commands use minimum var iance quant izat ion t o cr eat e an indexed
image wit h 185 color s:
RGB = imread('flowers.tif');
[X,map] = rgb2ind(RGB,185);
Colormap Mapping
If you specify t he act ual color map t o use, rgb2ind uses colormap mapping t o
find t he color s in t he specified color map t hat best mat ch t he color s in t he RGB
image. This met hod is useful if you need t o cr eat e images t hat use a fixed
color map. For example, if you want t o display mult iple indexed images on an
8-bit display, you can avoid color pr oblems by having t hem all use t he same
color map. Color map mapping pr oduces a good appr oximat ion if t he specified
color map has similar color s t o t hose in t he RGB image. If t he color map does not
have similar color s t o t hose in t he RGB image, t his met hod pr oduces poor
r esult s.
10 Color
10-8
This example illust r at es mapping t wo images t o t he same color map. The
color map specified includes color s all t hr oughout t he RGB cube, so t he out put
images ar e able t o r easonably appr oximat e t he input images.
RGB1 = imread('autumn.tif');
RGB2 = imread('flowers.tif');
X1 = rgb2ind(RGB1,colorcube(128));
X2 = rgb2ind(RGB2,colorcube(128));
Using imapprox
imapprox is based on rgb2ind, and pr ovides t he same appr oximat ion met hods.
Use imapprox when you need t o r educe t he number of color s in an indexed
image. Essent ially, imapprox fir st calls ind2rgb t o conver t t he image t o RGB
for mat , and t hen calls rgb2ind t o r et ur n a new indexed image wit h fewer
color s.
For example, t hese commands cr eat e a ver sion of t he trees image wit h 64
color s, r at her t han t he or iginal 128:
load trees
[Y,newmap] = imapprox(X,map,64);
image(Y), colormap(newmap);
Dithering
When you use rgb2ind or imapprox t o r educe t he number of color s in an image,
t he r esult ing image may look infer ior t o t he or iginal, because some of t he color s
ar e lost . rgb2ind and imapprox bot h per for m dithering t o incr ease t he
appar ent color r esolut ion of t he out put image. Dit her ing changes t he color s of
pixels in a neighbor hood, so t hat t he aver age color ar ound each pixel
appr oximat es t he or iginal RGB color . Dit her ing pr ovides t his ext r a color
r esolut ion at t he expense of spat ial r esolut ion. It adds high fr equency noise, but
it t ypically r esult s in a mor e visually pleasing appr oximat ion.
If you do not want t he out put image t o be dit her ed, you can specify t his when
you call rgb2ind or imapprox. For example,
[X,map] = rgb2ind(RGB,128,'nodither');
Converting to Other Color Spaces
10-9
Converting to Other Color Spaces
The Image Pr ocessing Toolbox r epr esent s color s as RGB values, eit her dir ect ly
(in an RGB image) or indir ect ly (in an indexed image). However , t her e ar e
ot her models besides RGB for r epr esent ing color s numer ically. For example, a
color can be r epr esent ed by it s hue, sat ur at ion, and value component s (HSV)
inst ead. The var ious models for color dat a ar e called color spaces.
The funct ions in t he Image Pr ocessing Toolbox t hat wor k wit h color assume
t hat images use t he RGB color space. The t oolbox pr ovides suppor t for ot her
color spaces t hough a set of conver sion funct ions. You can use t hese funct ions
t o conver t bet ween RGB and t hese color spaces:
Nat ional Television Syst ems Commit t ee (NTSC) for mat
YCbCr for mat
Hue, sat ur at ion, value (HSV) for mat
This sect ion descr ibes t hese color spaces and t he conver sion r out ines for
wor king wit h t hem.
NTSC Format
The NTSC for mat is used in t elevisions in t he Unit ed St at es. One of t he main
advant ages of t his for mat is t hat gr ayscale infor mat ion is separ at ed fr om color
dat a, so t he same signal can be used for bot h color and black and whit e set s. In
t his NTSC for mat , image dat a consist s of t hr ee component s: luminance (Y),
hue (I), and sat ur at ion (Q). The fir st component , luminance, r epr esent s
gr ayscale infor mat ion, while t he last t wo component s make up chr ominance
(color infor mat ion).
The funct ion rgb2ntsc conver t s color maps or RGB images t o t he NTSC color
space. ntsc2rgb per for ms t he r ever se oper at ion.
For example, t hese commands conver t t he flowers image t o NTSC for mat :
RGB = imread('flowers.tif');
YIQ = rgb2ntsc(RGB);
Because luminance is one of t he component s of t he NTSC for mat , t he RGB t o
NTSC conver sion is also useful for isolat ing t he gr ay level infor mat ion in an
image. The t oolbox funct ions rgb2gray and ind2gray use t he rgb2ntsc
funct ion t o ext r act t he gr ayscale infor mat ion fr om a color image.
10 Color
10-10
For example, t hese commands ar e equivalent t o calling rgb2gray:
YIQ = rgb2ntsc(RGB);
I = YIQ(:,:,1);
(In YIQ color space, I is one of t he t wo color component s, not t he gr ayscale
component .)
YCbCr Format
The YCbCr for mat is widely used for digit al video. In t his for mat , luminance
infor mat ion is st or ed as a single component (Y), and chr ominance infor mat ion
is st or ed as t wo color differ ence component s (Cb and Cr ). Cb r epr esent s t he
differ ence bet ween t he blue component and a r efer ence value, and Cr
r epr esent s t he differ ence bet ween t he r ed component and a r efer ence value.
YCbCr dat a can be double pr ecision, but t he color space is par t icular ly well
suit ed t o uint8 dat a. For uint8 images, t he dat a r ange for Y is [16,235], and
t he r ange for Cb and Cr is [16,240]. YCbCr leaves r oom at t he t op and bot t om
of t he full uint8 r ange so t hat addit ional (non-image) infor mat ion can be
included in a video st r eam.
The funct ion rgb2ycbcr conver t s color maps or RGB images t o t he YCbCr color
space. ycbcr2rgb per for ms t he r ever se oper at ion.
For example, t hese commands conver t t he flowers image t o YCbCr for mat :
RGB = imread('flowers.tif');
YCBCR = rgb2ycbcr(RGB);
HSV Format
The funct ions rgb2hsv and hsv2rgb conver t images bet ween t he RGB and hue,
sat ur at ion, value (HSV) color spaces. The HSV color space is oft en used for
picking color s (e.g., of paint s or inks) fr om a color wheel or palet t e, because it
cor r esponds bet t er t o how people exper ience color t han t he RGB color space
does.
As hue var ies fr om 0 t o 1.0, t he cor r esponding color s var y fr om r ed, t hr ough
yellow, gr een, cyan, blue, and magent a, back t o r ed. As sat ur at ion var ies fr om
0 t o 1.0, t he cor r esponding color s var y fr om unsat ur at ed (shades of gr ay) t o
fully sat ur at ed (no whit e component ). As value, or br ight ness, var ies fr om 0 t o
1.0, t he cor r esponding color s become incr easingly br ight er .
Converting to Other Color Spaces
10-11
The figur e below illust r at es t he HSV color space.
These commands conver t an RGB image t o HSV color space:
RGB = imread('flowers.tif');
HSV = rgb2hsv(RGB);
0
0.5
1
0
.5
Hue
Sat ur at ion
Value
0
1
1
Hue
0
10 Color
10-12
11
Refer ence
11 Reference
11-2
This chapt er pr ovides det ailed descr ipt ions of t he funct ions in t he Image
Pr ocessing Toolbox. It begins wit h a list of funct ions gr ouped by subject ar ea
and cont inues wit h t he r efer ence ent r ies in alphabet ical or der .
The list of funct ions includes all funct ions in t he Image Pr ocessing Toolbox
it self, plus a few funct ions in MATLAB t hat ar e especially useful for image
pr ocessing. All of t he funct ions list ed have r efer ence ent r ies, wit h t hese
except ions:
The MATLAB funct ions image, imagesc, and interp2. For infor mat ion about
t hese funct ions, see t he online MATLAB Funct ion Refer ence.
The Image Pr ocessing Toolbox demo funct ions and slideshow funct ions. For
infor mat ion about any of t hese funct ions, r un t he demo or slideshow and
click t he Info but t on.
Image Display
colorbar Display color bar (MATLAB)
getimage Get image dat a fr om axes
image Cr eat e and display image object (MATLAB)
imagesc Scale dat a and display as image (MATLAB)
immovie Make movie fr om mult ifr ame indexed image
imshow Display image
montage Display mult iple image fr ames as r ect angular mont age
subimage Display mult iple images in single figur e
truesize Adjust display size of image
warp Display image as t ext ur e-mapped sur face
zoom Zoom in and out of image or 2-D plot (MATLAB)
11-3
Image File I/O
imfinfo Ret ur n infor mat ion about image file (MATLAB)
imread Read image file (MATLAB)
imwrite Wr it e image file (MATLAB)
Geometric Operations
imcrop Cr op image
imresize Resize image
imrotate Rot at e image
interp2 2-D dat a int er polat ion (MATLAB)
Pixel Values and Statistics
corr2 Comput e 2-D cor r elat ion coefficient
imcontour Cr eat e cont our plot of image dat a
imfeature Comput e feat ur e measur ement s for image r egions
imhist Display hist ogr am of image dat a
impixel Det er mine pixel color values
improfile Comput e pixel-value cr oss-sect ions along line segment s
mean2 Comput e mean of mat r ix element s
pixval Display infor mat ion about image pixels
std2 Comput e st andar d deviat ion of mat r ix element s
11 Reference
11-4
Image Analysis
edge Find edges in int ensit y image
qtdecomp Per for m quadt r ee decomposit ion
qtgetblk Get block values in quadt r ee decomposit ion
qtsetblk Set block values in quadt r ee decomposit ion
Image Enhancement
histeq Enhance cont r ast using hist ogr am equalizat ion
imadjust Adjust image int ensit y values or color map
imnoise Add noise t o an image
medfilt2 Per for m 2-D median filt er ing
ordfilt2 Per for m 2-D or der-st at ist ic filt er ing
wiener2 Per for m 2-D adapt ive noise-r emoval filt er ing
Linear Filtering
conv2 Per for m 2-D convolut ion (MATLAB)
convmtx2 Comput e 2-D convolut ion mat r ix
convn Per for m N-D convolut ion (MATLAB)
filter2 Per for m 2-D filt er ing (MATLAB)
fspecial Cr eat e pr edefined filt er s
11-5
Linear 2-D Filter Design
freqspace Det er mine 2-D fr equency r esponse spacing (MATLAB)
freqz2 Comput e 2-D fr equency r esponse
fsamp2 Design 2-D FIR filt er using fr equency sampling
ftrans2 Design 2-D FIR filt er using fr equency t r ansfor mat ion
fwind1 Design 2-D FIR filt er using 1-D window met hod
fwind2 Design 2-D FIR filt er using 2-D window met hod
Image Transforms
dct2 Comput e 2-D discr et e cosine t r ansfor m
dctmtx Comput e discr et e cosine t r ansfor m mat r ix
fft2 Comput e 2-D fast Four ier t r ansfor m (MATLAB)
fftn Comput e N-D fast Four ier t r ansfor m (MATLAB)
fftshift Rever se quadr ant s of out put of FFT (MATLAB)
idct2 Comput e 2-D inver se discr et e cosine t r ansfor m
ifft2 Comput e 2-D inver se fast Four ier t r ansfor m (MATLAB)
ifftn Comput e N-D inver se fast Four ier t r ansfor m (MATLAB)
iradon Comput e inver se Radon t r ansfor m
phantom Gener at e a head phant om image
radon Comput e Radon t r ansfor m
11 Reference
11-6
Neighborhood and Block Processing
bestblk Choose block size for block pr ocessing
blkproc Implement dist inct block pr ocessing for image
col2im Rear r ange mat r ix columns int o blocks
colfilt Per for m neighbor hood oper at ions using columnwise
funct ions
im2col Rear r ange image blocks int o columns
nlfilter Per for m gener al sliding-neighbor hood oper at ions
Binary Image Operations
applylut Per for m neighbor hood oper at ions using lookup t ables
bwarea Comput e ar ea of object s in binar y image
bweuler Comput e Euler number of binar y image
bwfill Fill backgr ound r egions in binar y image
bwlabel Label connect ed component s in binar y image
bwmorph Per for m mor phological oper at ions on binar y image
bwperim Det er mine per imet er of object s in binar y image
bwselect Select object s in binar y image
dilate Per for m dilat ion on binar y image
erode Per for m er osion on binar y image
makelut Const r uct lookup t able for use wit h applylut
11-7
Region-Based Processing
roicolor Select r egion of int er est , based on color
roifill Smoot hly int er polat e wit hin ar bit r ar y r egion
roifilt2 Filt er a r egion of int er est
roipoly Select polygonal r egion of int er est
Colormap Manipulation
brighten Br ight en or dar ken color map (MATLAB)
cmpermute Rear r ange color s in color map
cmunique Find unique color map color s and cor r esponding image
colormap Set or get color lookup t able (MATLAB)
imapprox Appr oximat e indexed image by one wit h fewer color s
rgbplot Plot RGB color map component s (MATLAB)
Color Space Conversions
hsv2rgb Conver t HSV values t o RGB color space (MATLAB)
ntsc2rgb Conver t NTSC values t o RGB color space
rgb2hsv Conver t RGB values t o HSV color space (MATLAB)
rgb2ntsc Conver t RGB values t o NTSC color space
rgb2ycbcr Conver t RGB values t o YCbCr color space
ycbcr2rgb Conver t YCbCr values t o RGB color space
11 Reference
11-8
Image Types and Type Conversions
dither Conver t image using dit her ing
gray2ind Conver t int ensit y image t o indexed image
grayslice Cr eat e indexed image fr om int ensit y image by t hr esholding
im2bw Conver t image t o binar y image by t hr esholding
im2double Conver t image ar r ay t o double pr ecision
im2uint8 Conver t image ar r ay t o 8-bit unsigned int eger s
im2uint16 Conver t image ar r ay t o 16-bit unsigned int eger s
ind2gray Conver t indexed image t o int ensit y image
ind2rgb Conver t indexed image t o RGB image
isbw Ret ur n t r ue for binar y image
isgray Ret ur n t r ue for int ensit y image
isind Ret ur n t r ue for indexed image
isrgb Ret ur n t r ue for RGB image
mat2gray Conver t mat r ix t o int ensit y image
rgb2gray Conver t RGB image or color map t o gr ayscale
rgb2ind Conver t RGB image t o indexed image
Toolbox Preferences
iptgetpref Get value of Image Pr ocessing Toolbox pr efer ence
iptsetpref Set value of Image Pr ocessing Toolbox pr efer ence
11-9
Demos
dctdemo 2-D DCT image compr ession demo
edgedemo Edge det ect ion demo
firdemo 2-D FIR filt er ing and filt er design demo
imadjdemo Int ensit y adjust ment and hist ogr am equalizat ion demo
nrfiltdemo Noise r educt ion filt er ing demo
qtdemo Quadt r ee decomposit ion demo
roidemo Region-of-int er est pr ocessing demo
Slide Shows
ipss001 Region labeling of st eel gr ains
ipss002 Feat ur e-based logic
ipss003 Cor r ect ion of nonunifor m illuminat ion
applylut
11-10
11
11applylut
Purpose Per for m neighbor hood oper at ions on binar y images, using lookup t ables
Syntax A = applylut(BW,lut)
Description A = applylut(BW,lut) per for ms a 2-by-2 or 3-by-3 neighbor hood oper at ion on
binar y image BW by using a lookup t able (lut). lut is eit her a 16-element or
512-element vect or r et ur ned by makelut. The vect or consist s of t he out put
values for all possible 2-by-2 or 3-by-3 neighbor hoods.
The values r et ur ned in A depend on t he values in lut. For example, if lut
consist s of all 1s and 0s, A will be a binar y image.
Class Support BW and lut can be of class uint8 or double. If t he element s of lut ar e all
int eger s bet ween 0 and 255 (r egar dless of t he class of lut), t hen t he class of A
is uint8; ot her wise, t he class of A is double.
Algorithm applylut per for ms a neighbor hood oper at ion on a binar y image by pr oducing
a mat r ix of indices int o lut, and t hen r eplacing t he indices wit h t he act ual
values in lut. The specific algor it hm used depends on whet her you use 2-by-2
or 3-by-3 neighbor hoods.
2-by-2 Nei ghborhoods
For 2-by-2 neighbor hoods, length(lut) is 16. Ther e ar e 4 pixels in each
neighbor hood, and 2 possible st at es for each pixel, so t he t ot al number of
per mut at ions is 2
4
= 16.
To pr oduce t he mat r ix of indices, applylut convolves t he binar y image BW wit h
t his mat r ix:
8 2
4 1
The r esult ing convolut ion cont ains int eger values in t he r ange [0,15]. applylut
uses t he cent r al par t of t he convolut ion, of t he same size as BW, and adds 1 t o
each value t o shift t he r ange t o [1,16]. It t hen const r uct s A by r eplacing t he
values in t he cells of t he index mat r ix wit h t he values in lut t hat t he indices
point t o.
applylut
11-11
3-by-3 Nei ghborhoods
For 3-by-3 neighbor hoods, length(lut) is 512. Ther e ar e 9 pixels in each
neighbor hood, and 2 possible st at es for each pixel, so t he t ot al number of
per mut at ions is 2
9
= 512.
To pr oduce t he mat r ix of indices, applylut convolves t he binar y image BW wit h
t his mat r ix:
256 32 4
128 16 2
64 8 1
The r esult ing convolut ion cont ains int eger values in t he r ange [0,511].
applylut uses t he cent r al par t of t he convolut ion, of t he same size as BW, and
adds 1 t o each value t o shift t he r ange t o [1,512]. It t hen const r uct s A by
r eplacing t he values in t he cells of t he index mat r ix wit h t he values in lut t hat
t he indices point t o.
Example In t his example, you per for m er osion using a 2-by-2 neighbor hood. An out put
pixel is on only if all four of t he input pixels neighbor hood pixels ar e on.
lut = makelut('sum(x(:)) == 4',2);
BW1 = imread('text.tif');
BW2 = applylut(BW1,lut);
imshow(BW1)
figure, imshow(BW2)
See Also makelut
bestblk
11-12
11best blk
Purpose Det er mine block size for block pr ocessing
Syntax siz = bestblk([m n],k)
[mb,nb] = bestblk([m n],k)
Description siz = bestblk([m n],k) r et ur ns, for an m-by-n image, t he opt imal block size
for block pr ocessing. k is a scalar specifying t he maximum r ow and column
dimensions for t he block; if t he ar gument is omit t ed, it default s t o 100. siz is a
1-by-2 vect or cont aining t he r ow and column dimensions for t he block.
[mb,nb] = bestblk([m n],k) r et ur ns t he r ow and column dimensions for t he
block in mb and nb, r espect ively.
Algorithm bestblk r et ur ns t he opt imal block size given m, n, and k. The algor it hm for
det er mining siz is:
If m is less t han or equal t o k, r et ur n m.
If m is gr eat er t han k, consider all values bet ween min(m/10,k/2) and k.
Ret ur n t he value t hat minimizes t he padding r equir ed.
The same algor it hm is t hen r epeat ed for n.
Example siz = bestblk([640 800],72)
siz =
64 50
See Also blkproc
blkproc
11-13
11blkpr oc
Purpose Implement dist inct block pr ocessing for an image
Syntax B = blkproc(A,[m n],fun)
B = blkproc(A,[m n],fun,P1,P2,...)
B = blkproc(A,[m n],[mborder nborder],fun,...)
B = blkproc(A,'indexed',...)
Description B = blkproc(A,[m n],fun) pr ocesses t he image A by applying t he funct ion fun
t o each dist inct m-by-n block of A, padding A wit h zer os if necessar y. fun can be
an inline funct ion, a t ext st r ing cont aining t he name of a funct ion, or a st r ing
cont aining an expr ession. fun should oper at e on an m-by-n block, x, and r et ur n
a mat r ix, vect or , or scalar y.
y = fun(x)
blkproc does not r equir e t hat y be t he same size as x. However , B is t he same
size as A only if y is t he same size as x.
B = blkproc(A,[m n],fun,P1,P2,...) passes t he addit ional par amet er s
P1,P2,..., t o fun.
B = blkproc(A,[m n],[mborder nborder],fun,...) defines an over lapping
bor der ar ound t he blocks. blkproc ext ends t he or iginal m-by-n blocks by
mborder on t he t op and bot t om, and nborder on t he left and r ight , r esult ing in
blocks of size (m+2*mborder)-by-(n+2*nborder). blkproc pads t he bor der wit h
zer os, if necessar y, on t he edges of A. fun should oper at e on t he ext ended block.
The line below pr ocesses an image mat r ix as 4-by-6 blocks, each having a r ow
bor der of 2 and a column bor der of 3. Because each 4-by-6 block has t his 2-by-3
bor der , fun act ually oper at es on blocks of size 8-by-12.
B = blkproc(A,[4 6],[2 3],fun,...)
B = blkproc(A,'indexed',...) pr ocesses A as an indexed image, padding
wit h zer os if t he class of A is uint8 or uint16, or ones if t he class of A is double.
Class Support The input image A can be of any class suppor t ed by fun. The class of B depends
on t he class of t he out put fr om fun.
blkproc
11-14
Example This example uses blkproc t o set t he pixels in each 8-by-8 block t o t he st andar d
deviat ion of t he element s in t hat block.
I = imread('alumgrns.tif');
I2 = blkproc(I,[8 8],'std2(x)*ones(size(x))');
imshow(I)
figure, imshow(I2,[]);
See Also colfilt, nlfilter,inline
brighten
11-15
11bright en
Purpose Br ight en or dar ken a color map
Syntax brighten(beta)
newmap = brighten(beta)
newmap = brighten(map,beta)
brighten(fig,beta)
Description brighten(beta) r eplaces t he cur r ent color map wit h a br ight er or dar ker map
t hat has essent ially t he same color s. The map is br ight er if 0 < beta 1 and
dar ker if 1 beta < 0.
brighten(beta) followed by brighten(beta) r est or es t he or iginal map.
newmap = brighten(beta) r et ur ns a br ight er or dar ker ver sion of t he cur r ent
color map wit hout changing t he display.
newmap = brighten(map,beta) r et ur ns a br ight er or dar ker ver sion of t he
specified color map wit hout changing t he display.
brighten(fig,beta) br ight ens all of t he object s in t he figur e fig.
Remarks brighten is a funct ion in MATLAB.
See Also imadjust, rgbplot
colormap in t he online MATLAB Funct ion Refer ence
bwarea
11-16
11bwar ea
Purpose Comput e t he ar ea of t he object s in a binar y image
Syntax total = bwarea(BW)
Description total = bwarea(BW) est imat es t he ar ea of t he object s in binar y image BW.
total is a scalar whose value cor r esponds r oughly t o t he t ot al number of on
pixels in t he image, but may not be exact ly t he same because differ ent pat t er ns
of pixels ar e weight ed differ ent ly.
Class Support BW can be of class uint8 or double. total is of class double.
Algorithm bwarea est imat es t he ar ea of all of t he on pixels in an image by summing t he
ar eas of each pixel in t he image. The ar ea of an individual pixel is det er mined
by looking at it s 2-by-2 neighbor hood. Ther e ar e six differ ent pat t er ns
dist inguished, each r epr esent ing a differ ent ar ea:
Pat t er ns wit h zer o on pixels (ar ea = 0)
Pat t er ns wit h one on pixel (ar ea = 1/4)
Pat t er ns wit h t wo adjacent on pixels (ar ea = 1/2)
Pat t er ns wit h t wo diagonal on pixels (ar ea = 3/4)
Pat t er ns wit h t hr ee on pixels (ar ea = 7/8)
Pat t er ns wit h all four on pixels (ar ea = 1)
Keep in mind t hat each pixel is par t of four differ ent 2-by-2 neighbor hoods.
This means, for example, t hat a single on pixel sur r ounded by off pixels has a
t ot al ar ea of 1.
bwarea
11-17
Example This example comput es t he ar ea in t he object s of a 256-by-256 binar y image.
BW = imread('circles.tif');
imshow(BW);
bwarea(BW)
ans =
15799
See Also bweuler, bwperim
References Pr at t , William K. Digital Image Processing. New Yor k: J ohn Wiley & Sons,
Inc., 1991. p. 634.
bweuler
11-18
11bweuler
Purpose Comput e t he Euler number of a binar y image
Syntax eul = bweuler(BW,n)
Description eul = bweuler(BW,n) r et ur ns t he Euler number for t he binar y image BW. eul
is a scalar whose value is t he t ot al number of object s in t he image minus t he
t ot al number of holes in t hose object s. n can have a value of eit her 4 or 8, wher e
4 specifies 4-connect ed object s and 8 specifies 8-connect ed object s; if t he
ar gument is omit t ed, it default s t o 8.
Class Support BW can be of class uint8 or double. eul is of class double.
Example BW = imread('circles.tif');
imshow(BW);
bweuler(BW)
ans =
2
Algorithm bweuler comput es t he Euler number by consider ing pat t er ns of convexit y and
concavit y in local 2-by-2 neighbor hoods. See Pr at t , p. 633, for a discussion of
t he algor it hm used.
See Also bwmorph, bwperim
bweuler
11-19
References Pr at t , William K. Digital Image Processing. New Yor k: J ohn Wiley & Sons,
Inc., 1991. p. 633.
Hor n, Ber t hold P. K., Robot Vision. New Yor k: McGr aw-Hill, 1986. pp. 73-77.
bwfill
11-20
11bwfill
Purpose Fill backgr ound r egions in a binar y image
Syntax 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) per for ms a flood-fill oper at ion on t he input binar y
image BW1, st ar t ing fr om t he pixel (r,c). If r and c ar e equal-lengt h vect or s, t he
fill is per for med in par allel fr om t he st ar t ing pixels (r(k),c(k)). n can have a
value of eit her 4 or 8 (t he default ), wher e 4 specifies 4-connect ed for egr ound
and 8 specifies 8-connect ed for egr ound. The for egr ound of BW1 compr ises t he on
pixels (i.e., having value of 1).
BW2 = bwfill(BW1,n) displays t he image BW1 on t he scr een and let s you select
t he st ar t ing point s using t he mouse. If you omit BW1, bwfill oper at es on t he
image in t he cur r ent axes. Use nor mal but t on clicks t o add point s. Pr ess
Backspace or De le t e t o r emove t he pr eviously select ed point . A shift -click,
r ight -click, or double-click select s a final point and t hen st ar t s t he fill; pr essing
Return finishes t he select ion wit hout adding a point .
[BW2,idx] = bwfill(...) r et ur ns t he linear indices of all pixels filled by
bwfill.
BW2 = bwfill(x,y,BW1,xi,yi,n) uses t he vect or s x and y t o est ablish a
nondefault spat ial coor dinat e syst em for BW1. xi and yi ar e scalar s or
equal-lengt h vect or s t hat specify locat ions in t his coor dinat e syst em.
[x,y,BW2,idx,xi,yi] = bwfill(...) r et ur ns t he XData and YData in x and y;
t he out put image in BW2; linear indices of all filled pixels in idx; and t he fill
st ar t ing point s in xi and yi.
BW2 = bwfill(BW1,'holes',n) fills t he holes in t he binar y image BW1. bwfill
aut omat ically det er mines which pixels ar e in object holes, and t hen changes
t he value of t hose pixels fr om 0 t o 1. n default s t o 8 if you omit t he ar gument .
bwfill
11-21
[BW2,idx] = bwfill(BW1,'holes',n) r et ur ns t he linear indices of all pixels
filled in by bwfill.
If bwfill is used wit h no out put ar gument s, t he r esult ing image is displayed
in a new figur e.
Remarks bwfill differ s fr om many ot her binar y image oper at ions in t hat it oper at es on
backgr ound pixels, r at her t han for egr ound pixels. If t he for egr ound is
8-connect ed, t he backgr ound is 4-connect ed, and vice ver sa. Not e, however ,
t hat you specify t he connect edness of t he foreground when you call bwfill.
Class Support The input image BW1 can be of class double or uint8. The out put image BW2 is
of class uint8.
bwfill
11-22
Examples BW1 = [1 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0
1 0 0 0 1 0 1 0
1 0 0 0 1 1 1 0
1 1 1 1 0 1 1 1
1 0 0 1 1 0 1 0
1 0 0 0 1 0 1 0
1 0 0 0 1 1 1 0]

BW2 = bwfill(BW1,3,3,8)

BW2 =

1 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0
1 1 1 1 1 0 1 0
1 1 1 1 1 1 1 0
1 1 1 1 0 1 1 1
1 0 0 1 1 0 1 0
1 0 0 0 1 0 1 0
1 0 0 0 1 1 1 0
I = imread('blood1.tif');
BW3 = ~im2bw(I);
BW4 = bwfill(BW3,'holes');
imshow(BW3)
figure, imshow(BW4)
See Also bwselect, roifill
bwlabel
11-23
11bwlabel
Purpose Label connect ed component s in a binar y image
Syntax L = bwlabel(BW,n)
[L,num] = bwlabel(BW,n)
Description L = bwlabel(BW,n) r et ur ns a mat r ix L, of t he same size as BW, cont aining labels
for t he connect ed object s in BW. n can have a value of eit her 4 or 8, wher e 4
specifies 4-connect ed object s and 8 specifies 8-connect ed object s; if t he
ar gument is omit t ed, it default s t o 8.
The element s of L ar e int eger values gr eat er t han or equal t o 0. The pixels
labeled 0 ar e t he backgr ound. The pixels labeled 1 make up one object , t he
pixels labeled 2 make up a second object , and so on.
[L,num] = bwlabel(BW,n) r et ur ns in num t he number of connect ed object s
found in BW.
Class Support The input image BW can be of class double or uint8. The out put mat r ix L is of
class double.
Remarks You can use t he MATLAB find funct ion in conjunct ion wit h bwlabel t o r et ur n
vect or s of indices for t he pixels t hat make up a specific object . For example, t o
r et ur n t he coor dinat es for t he pixels in object 2:
[r,c] = find(bwlabel(BW)==2)
You can display t he out put mat r ix as a pseudocolor indexed image. Each object
appear s in a differ ent color , so t he object s ar e easier t o dist inguish t han in t he
or iginal image. To do t his, you must fir st add 1 t o each element in t he out put
mat r ix, so t hat t he dat a is in t he pr oper r ange. Also, it is good idea t o use a
color map in which t he fir st few color s ar e ver y dist inct .
bwlabel
11-24
Example This example illust r at es using 4-connect ed object s. Not ice object s 2 and 3; wit h
8-connect ed labeling, bwlabel would consider t hese a single object r at her t han
t wo separ at e object s.
BW = [1 1 1 0 0 0 0 0
1 1 1 0 1 1 0 0
1 1 1 0 1 1 0 0
1 1 1 0 0 0 1 0
1 1 1 0 0 0 1 0
1 1 1 0 0 0 1 0
1 1 1 0 0 1 1 0
1 1 1 0 0 0 0 0]
L = bwlabel(BW,4)
L =
1 1 1 0 0 0 0 0
1 1 1 0 2 2 0 0
1 1 1 0 2 2 0 0
1 1 1 0 0 0 3 0
1 1 1 0 0 0 3 0
1 1 1 0 0 0 3 0
1 1 1 0 0 3 3 0
1 1 1 0 0 0 0 0
[r,c] = find(L==2);
rc = [r c]
rc =

2 5
3 5
2 6
3 6
See Also bweuler, bwselect
Reference Har alick, Rober t M., and Linda G. Shapir o. Computer and Robot Vision,
Volume I. Addison-Wesley, 1992. pp. 28-48.
bwmorph
11-25
11bwmor ph
Purpose Per for m mor phological oper at ions on binar y images
Syntax BW2 = bwmorph(BW1,operation)
BW2 = bwmorph(BW1,operation,n)
Description BW2 = bwmorph(BW1,operation) applies a specific mor phological oper at ion t o
t he binar y image BW1.
BW2 = bwmorph(BW1,operation,n) applies t he oper at ion n t imes. n can be Inf,
in which case t he oper at ion is r epeat ed unt il t he image no longer changes.
operation is a st r ing t hat can have one of t he values list ed below.
'bothat' (bot t om hat ) per for ms binar y closur e (dilat ion followed by er osion)
and subt r act s t he or iginal image.
'bridge' br idges pr eviously unconnect ed pixels. For example,
1 0 0 1 0 0
1 0 1 becomes 1 1 1
0 0 1 0 0 1
'clean' r emoves isolat ed pixels (individual 1s t hat ar e sur r ounded by 0s),
such as t he cent er pixel in t his pat t er n:
0 0 0
0 1 0
0 0 0
'close' per for ms binar y closur e (dilat ion followed by er osion).
'bothat' 'erode' 'shrink'
'bridge' 'fill' 'skel'
'clean' 'hbreak' 'spur'
'close' 'majority' 'thicken'
'diag' 'open' 'thin'
'dilate' 'remove' 'tophat'
bwmorph
11-26
'diag' uses diagonal fill t o eliminat e 8-connect ivit y of t he backgr ound. For
example,
0 1 0 0 1 0
1 0 0 becomes 1 1 0
0 0 0 0 0 0
'dilate' per for ms dilat ion using t he st r uct ur ing element ones(3).
'erode' per for ms er osion using t he st r uct ur ing element ones(3).
'fill' fills isolat ed int er ior pixels (individual 0s t hat ar e sur r ounded by 1s),
such as t he cent er pixel in t his pat t er n:
1 1 1
1 0 1
1 1 1
'hbreak' r emoves H-connect ed pixels. For example,
1 1 1 1 1 1
0 1 0 becomes 0 0 0
1 1 1 1 1 1
'majority' set s a pixel t o 1 if five or mor e pixels in it s 3-by-3 neighbor hood ar e
1s; ot her wise, it set s t he pixel t o 0.
'open' implement s binar y opening (er osion followed by dilat ion).
'remove' r emoves int er ior pixels. This opt ion set s a pixel t o 0 if all of it s
4-connect ed neighbor s ar e 1, t hus leaving only t he boundar y pixels on.
'shrink', wit h n = Inf, shr inks object s t o point s. It r emoves pixels so t hat
object s wit hout holes shr ink t o a point , and object s wit h holes shr ink t o a
connect ed r ing halfway bet ween each hole and t he out er boundar y. This opt ion
pr eser ves t he Euler number .
'skel', wit h n = Inf, r emoves pixels on t he boundar ies of object s but does not
allow object s t o br eak apar t . The pixels r emaining make up t he image skelet on.
This opt ion pr eser ves t he Euler number .
bwmorph
11-27
'spur' r emoves spur pixels. For example,
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 1 0 becomes 0 0 0 0
0 1 0 0 0 1 0 0
1 1 0 0 1 1 0 0
'thicken', wit h n = Inf, t hickens object s by adding pixels t o t he ext er ior of
object s unt il doing so would r esult in pr eviously unconnect ed object s being
8-connect ed. This opt ion pr eser ves t he Euler number .
'thin', wit h n = Inf, t hins object s t o lines. It r emoves pixels so t hat an object
wit hout holes shr inks t o a minimally connect ed st r oke, and an object wit h holes
shr inks t o a connect ed r ing halfway bet ween each hole and t he out er boundar y.
This opt ion pr eser ves t he Euler number .
'tophat' (t op hat ) r et ur ns t he image minus t he binar y opening of t he image.
Class Support The input image BW1 can be of class double or uint8. The out put image BW2 is
of class uint8.
bwmorph
11-28
Examples 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 Har alick, Rober t M., and Linda G. Shapir o. Computer and Robot Vision,
Volume I. Addison-Wesley, 1992.
Pr at t , William K. Digital Image Processing. J ohn Wiley & Sons, Inc., 1991.
bwperim
11-29
11bwper im
Purpose Det er mine t he per imet er of t he object s in a binar y image
Syntax BW2 = bwperim(BW1,n)
Description BW2 = bwperim(BW1,n) r et ur ns a binar y image cont aining only t he per imet er
pixels of object s in t he input image BW1. A pixel is par t of t he per imet er if it s
value is 1 and t her e is at least one zer o-valued pixel in it s neighbor hood. n can
have a value of eit her 4 or 8, wher e 4 specifies 4-connect ed neighbor hoods and
8 specifies 8-connect ed neighbor hoods; if t he ar gument is omit t ed, it default s
t o 4.
Class Support The input image BW1 can be of class double or uint8. The out put image BW2 is
of class uint8.
Example BW1 = imread('circbw.tif');
BW2 = bwperim(BW1,8);
imshow(BW1)
figure, imshow(BW2)
See Also bwarea, bweuler, bwfill
bwselect
11-30
11bwselect
Purpose Select object s in a binar y image
Syntax 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) r et ur ns a binar y image cont aining t he object s
t hat over lap t he pixel (r,c). r and c can be scalar s or equal-lengt h vect or s. If r
and c ar e vect or s, BW2 cont ains t he set s of object s over lapping wit h any of t he
pixels (r(k),c(k)). n can have a value of eit her 4 or 8 (t he default ), wher e 4
specifies 4-connect ed object s and 8 specifies 8-connect ed object s. Object s ar e
connect ed set s of on pixels (i.e., pixels having a value of 1).
BW2 = bwselect(BW1,n) displays t he image BW1 on t he scr een and let s you
select t he (r,c) coor dinat es using t he mouse. If you omit BW1, bwselect
oper at es on t he image in t he cur r ent axes. Use nor mal but t on clicks t o add
point s. Pr essing Backs pace or De le te r emoves t he pr eviously select ed point .
A shift -click, r ight -click, or double-click select s t he final point ; pr essing
Return finishes t he select ion wit hout adding a point .
[BW2,idx] = bwselect(...) r et ur ns t he linear indices of t he pixels belonging
t o t he select ed object s.
BW2 = bwselect(x,y,BW1,xi,yi,n) uses t he vect or s x and y t o est ablish a
nondefault spat ial coor dinat e syst em for BW1. xi and yi ar e scalar s or
equal-lengt h vect or s t hat specify locat ions in t his coor dinat e syst em.
[x,y,BW2,idx,xi,yi] = bwselect(...) r et ur ns t he XData and YData in x and
y; t he out put image in BW2; linear indices of all t he pixels belonging t o t he
select ed object s in idx; and t he specified spat ial coor dinat es in xi and yi.
If bwselect is called wit h no out put ar gument s, t he r esult ing image is
displayed in a new figur e.
bwselect
11-31
Example BW1 = imread('text.tif');
c = [16 90 144];
r = [85 197 247];
BW2 = bwselect(BW1,c,r,4);
imshow(BW1)
figure, imshow(BW2)
Class Support The input image BW1 can be of class double or uint8. The out put image BW2 is
of class uint8.
See Also bwfill, bwlabel, impixel, roipoly, roifill
cmpermute
11-32
11cmper mut e
Purpose Rear r ange t he color s in a color map
Syntax [Y,newmap] = cmpermute(X,map)
[Y,newmap] = cmpermute(X,map,index)
Description [Y,newmap] = cmpermute(X,map) r andomly r eor der s t he color s in map t o
pr oduce a new color map newmap. cmpermute also modifies t he values in X t o
maint ain cor r espondence bet ween t he indices and t he color map, and r et ur ns
t he r esult in Y. The image Y and associat ed color map newmap pr oduce t he same
image as X and map.
[Y,newmap] = cmpermute(X,map,index) uses an or der ing mat r ix (such as t he
second out put of sort) t o define t he or der of color s in t he new color map.
Class Support The input image X can be of class uint8 or double. Y is r et ur ned as an ar r ay of
t he same class as X.
Example To or der a color map by luminance, use:
ntsc = rgb2ntsc(map);
[dum,index] = sort(ntsc(:,1));
[Y,newmap] = cmpermute(X,map,index);
See Also randperm, sort in t he online MATLAB Funct ion Refer ence
cmunique
11-33
11cmunique
Purpose Find unique color map color s and t he cor r esponding image
Syntax [Y,newmap] = cmunique(X,map)
[Y,newmap] = cmunique(RGB)
[Y,newmap] = cmunique(I)
Description [Y,newmap] = cmunique(X,map) r et ur ns t he indexed image Y and associat ed
color map newmap t hat pr oduce t he same image as (X,map) but wit h t he
smallest possible color map. cmunique r emoves duplicat e r ows fr om t he
color map and adjust s t he indices in t he image mat r ix accor dingly.
[Y,newmap] = cmunique(RGB) conver t s t he t r uecolor image RGB t o t he indexed
image Y and it s associat ed color map newmap. newmap is t he smallest possible
color map for t he image, cont aining one ent r y for each unique color in RGB. (Not e
t hat newmap may be ver y lar ge, because t he number of ent r ies can be as many
as t he number of pixels in RGB.)
[Y,newmap] = cmunique(I) conver t s t he int ensit y image I t o an indexed image
Y and it s associat ed color map newmap. newmap is t he smallest possible color map
for t he image, cont aining one ent r y for each unique int ensit y level in I.
Class Support The input image can be of class uint8, uint16, or double. The class of t he
out put image Y is uint8 if t he lengt h of newmap is less t han or equal t o 256. If
t he lengt h of newmap is gr eat er t han 256, Y is of class double.
See Also gray2ind, rgb2ind
col2im
11-34
11col2im
Purpose Rear r ange mat r ix columns int o blocks
Syntax A = col2im(B,[m n],[mm nn],block_type)
A = col2im(B,[m n],[mm nn])
Description col2im r ear r anges mat r ix columns int o blocks. block_type is a st r ing wit h one
of t hese values:
'distinct' for m-by-n dist inct blocks
'sliding' for m-by-n sliding blocks (default )
A = col2im(B,[m n],[mm nn],'distinct') r ear r anges each column of B
int o a dist inct m-by-n block t o cr eat e t he mat r ix A of size mm-by-nn. If
B = [A11(:) A12(:) A21(:) A22(:)], wher e each column has lengt h m*n,
t hen A = [A11 A12;A21 A22] wher e each A
ij
is m-by-n.
A = col2im(B,[m n],[mm nn],'sliding') r ear r anges t he r ow vect or B
int o a mat r ix of size (mmm+1)-by-(nnn+1). B must be a vect or of size
1-by-(mmm+1)*(nnn+1). B is usually t he r esult of pr ocessing t he out put of
im2col(...,'sliding') using a column compr ession funct ion (such as sum).
A = col2im(B,[m n],[mm nn]) uses t he default block_type of 'sliding'.
Class Support B can be of class double or of any int eger class. A is of t he same class as B.
See Also blkproc, colfilt, im2col, nlfilter
colfilt
11-35
11colfilt
Purpose Per for m neighbor hood oper at ions using columnwise funct ions
Syntax B = colfilt(A,[m n],block_type,fun)
B = colfilt(A,[m n],block_type,fun,P1,P2,...)
B = colfilt(A,[m n],[mblock nblock],block_type,fun,...)
B = colfilt(A,'indexed',...)
Description colfilt pr ocesses dist inct or sliding blocks as columns. colfilt can per for m
similar oper at ions t o blkproc and nlfilter, but oft en execut es much fast er .
B = colfilt(A,[m n],block_type,fun) pr ocesses t he image A by r ear r anging
each m-by-n block of A int o a column of a t empor ar y mat r ix, and t hen applying
t he funct ion fun t o t his mat r ix. fun can be an inline funct ion, a t ext st r ing
cont aining t he name of a funct ion, or a st r ing cont aining an expr ession.
colfilt zer o pads A, if necessar y.
Befor e calling fun, colfilt calls im2col t o cr eat e t he t empor ar y mat r ix. Aft er
calling fun, colfilt r ear r anges t he columns of t he mat r ix back int o m-by-n
blocks using col2im.
block_type is a st r ing wit h one of t hese values:
'distinct' for m-by-n dist inct blocks
'sliding' for m-by-n sliding neighbor hoods
B = colfilt(A,[m n],'distinct',fun) r ear r anges each m-by-n dist inct block
of A int o a column in a t empor ar y mat r ix, and t hen applies t he funct ion fun t o
t his mat r ix. fun must r et ur n a mat r ix of t he same size as t he t empor ar y
mat r ix. colfilt t hen r ear r anges t he columns of t he mat r ix r et ur ned by fun
int o m-by-n dist inct blocks.
B = colfilt(A,[m n],'sliding',fun) r ear r anges each m-by-n sliding
neighbor hood of A int o a column in a t empor ar y mat r ix, and t hen applies t he
funct ion fun t o t his mat r ix. fun must r et ur n a r ow vect or cont aining a single
value for each column in t he t empor ar y mat r ix. (Column compr ession funct ions
such as sum r et ur n t he appr opr iat e t ype of out put .) colfilt t hen r ear r anges
t he vect or r et ur ned by fun int o a mat r ix of t he same size as A.
colfilt
11-36
B = colfilt(A,[m n],block_type,fun,P1,P2,...) passes t he addit ional
par amet er s P1,P2,..., t o fun. colfilt calls fun using,
y = fun(x,P1,P2,...)
wher e x is t he t empor ar y mat r ix befor e pr ocessing, and y is t he t empor ar y
mat r ix aft er pr ocessing.
B = colfilt(A,[m n],[mblock nblock],block_type,fun,...) pr ocesses t he
mat r ix A as above, but in blocks of size mblock-by-nblock t o save memor y. Not e
t hat using t he [mblock nblock] ar gument does not change t he r esult of t he
oper at ion.
B = colfilt(A,'indexed',...) pr ocesses A as an indexed image, padding
wit h zer os if t he class of A is uint8 or uint16, or ones if t he class of A is double.
Class Support The input image A can be of any class suppor t ed by fun. The class of B depends
on t he class of t he out put fr om fun.
Example This example set s each out put pixel t o t he mean value of t he input pixels
5-by-5 neighbor hood.
I2 = colfilt(I,[5 5],'sliding','mean');
See Also blkproc, col2im, im2col, nlfilter
colorbar
11-37
11colorbar
Purpose Display a color bar
Syntax colorbar('vert')
colorbar('horiz')
colorbar(h)
colorbar
h = colorbar(...)
Description colorbar('vert') appends a ver t ical color bar t o t he cur r ent axes, r esizing t he
axes t o make r oom for t he color bar . colorbar wor ks wit h bot h t wo-dimensional
and t hr ee-dimensional plot s.
colorbar('horiz') appends a hor izont al color bar t o t he cur r ent axes.
colorbar(h) places t he color bar in t he axes h. The color bar is hor izont al if t he
widt h of t he axes is gr eat er t han it s height .
colorbar wit h no ar gument s adds a new ver t ical color bar or updat es an
exist ing one.
h = colorbar(...) r et ur ns a handle t o t he color bar axes.
Remarks colorbar is a funct ion in MATLAB.
colorbar
11-38
Examples Display a color bar t o view values for a filt er ed image.
I = imread('blood1.tif');
h = fspecial('log');
I2 = filter2(h,I);
imshow(I2,[]), colormap(jet(64)), colorbar
conv2
11-39
11conv2
Purpose Per for m t wo-dimensional convolut ion
Syntax C = conv2(A,B)
C = conv2(hcol,hrow,A)
C = conv2(...,shape)
Description C = conv2(A,B) per for ms t he t wo-dimensional convolut ion of mat r ices A and
B, r et ur ning t he r esult in t he out put mat r ix C. The size in each dimension of C
is equal t o t he sum of t he cor r esponding dimensions of t he input mat r ices
minus one. That is, if t he size of A is [ma,mb] and t he size of B is [mb,nb], t hen
t he size of C is [ma+mb1,na+nb1].
C = conv2(hcol,hrow,A) convolves A separ ably wit h hcol in t he column
dir ect ion and hrow in t he r ow dir ect ion. hcol and hrow ar e bot h vect or s.
C = conv2(...,shape) r et ur ns a subsect ion of t he t wo-dimensional
convolut ion, as specified by t he shape par amet er . shape is a st r ing wit h one of
t hese values:
'full' (t he default ) r et ur ns t he full t wo-dimensional convolut ion.
'same' r et ur ns t he cent r al par t of t he convolut ion of t he same size as A.
'valid' r et ur ns only t hose par t s of t he convolut ion t hat ar e comput ed
wit hout t he zer o-padded edges. Using t his opt ion, size(C) = [mamb+1,
nanb+1] when size(A) > size(B).
For image filt er ing, A should be t he image mat r ix and B should be t he filt er
(convolut ion ker nel) if t he shape par amet er is 'same' or 'valid'. If t he shape
par amet er is 'full', t he or der does not mat t er , because full convolut ion is
commut at ive.
Class Support All vect or and mat r ix input s t o conv2 can be of class double or of any int eger
class. The out put mat r ix C is of class double.
Remarks conv2 is a funct ion in MATLAB.
conv2
11-40
Example A = magic(5)
A =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
B = [1 2 1;0 2 0;3 1 3]
B =
1 2 1
0 2 0
3 1 3
C = conv2(A,B)
C =
17 58 66 34 32 38 15
23 85 88 35 67 76 16
55 149 117 163 159 135 67
79 78 160 161 187 129 51
23 82 153 199 205 108 75
30 68 135 168 91 84 9
33 65 126 85 104 15 27
See Also filter2
xcorr, xcorr2 in t he S ignal Processing Toolbox Users Guide
conv, deconv in t he online MATLAB Funct ion Refer ence
convmtx2
11-41
11convmt x2
Purpose Comput e t wo-dimensional convolut ion mat r ix
Syntax T = convmtx2(H,m,n)
T = convmtx2(H,[m n])
Description T = convmtx2(H,m,n) or T = convmtx2(H,[m n]) r et ur ns t he
convolut ion mat r ix T for t he mat r ix H. If X is an m-by-n mat r ix, t hen
reshape(T*X(:),size(H)+[m n]1) is t he same as conv2(X,H).
Class Support The input s ar e all of class double. The out put mat r ix T is of class sparse. The
number of nonzer o element s in T is no lar ger t han prod(size(H))*m*n.
See Also conv2
convmtx in t he S ignal Processing Toolbox Users Guide
convn
11-42
11convn
Purpose Per for m N-dimensional convolut ion
Syntax C = convn(A,B)
C = convn(A,B,shape)
Description C = convn(A,B) comput es t he N-dimensional convolut ion of mat r ices A and B.
C = convn(A,B,shape) r et ur ns a subsect ion of t he N-dimensional convolut ion,
as specified by t he shape par amet er . shape is a st r ing wit h one of t hese values:
'full' (t he default ) r et ur ns t he full convolut ion.
'same' r et ur ns t he cent r al par t of t he convolut ion of t he same size as A.
'valid' r et ur ns only t hose par t s of t he convolut ion t hat ar e comput ed
wit hout zer o-padded edges.
Class Support The input mat r ices A and B can be of class double or of any int eger class. The
out put mat r ix C is of class double.
Remarks convn is a funct ion in MATLAB.
See Also conv2
corr2
11-43
11corr 2
Purpose Comput e t he t wo-dimensional cor r elat ion coefficient bet ween t wo mat r ices
Syntax r = corr2(A,B)
Description r = corr2(A,B) comput es t he cor r elat ion coefficient bet ween A and B, wher e A
and B ar e mat r ices or vect or s of t he same size.
Class Support A and B can be of class double or of any int eger class. r is a scalar of class
double.
Algorithm corr2 comput es t he cor r elat ion coefficient using
wher e = mean2(A), and = mean2(B).
See Also std2
corrcoef in t he online MATLAB Funct ion Refer ence
r
A
m n
A ( ) B
m n
B ( )
n

A
m n
A ( )
2
n

,

_
B
m n
B ( )
2
n

,

_
----------------------------------------------------------------------------------------------------- =
A B
dct2
11-44
11dct 2
Purpose Comput e t wo-dimensional discr et e cosine t r ansfor m
Syntax B = dct2(A)
B = dct2(A,m,n)
B = dct2(A,[m n])
Description B = dct2(A) r et ur ns t he t wo-dimensional discr et e cosine t r ansfor m of A. The
mat r ix B is t he same size as A and cont ains t he discr et e cosine t r ansfor m
coefficient s B(k
1
,k
2
).
B = dct2(A,m,n) or B = dct2(A,[m n]) pads t he mat r ix A wit h zer os t o size
m-by-n befor e t r ansfor ming. If m or n is smaller t han t he cor r esponding
dimension of A, dct2 t r uncat es A.
Class Support A can be of class double or of any int eger class. The r et ur ned mat r ix B is of class
double.
Algorithm The discr et e cosine t r ansfor m (DCT) is closely r elat ed t o t he discr et e Four ier
t r ansfor m. It is a separ able, linear t r ansfor mat ion; t hat is, t he
t wo-dimensional t r ansfor m is equivalent t o a one-dimensional DCT per for med
along a single dimension followed by a one-dimensional DCT in t he ot her
dimension. The definit ion of t he t wo-dimensional DCT for an input image A and
out put image B is
wher e M and N ar e t he r ow and column size of A, r espect ively. If you apply t he
DCT t o r eal dat a, t he r esult is also r eal. The DCT t ends t o concent r at e
infor mat ion, making it useful for image compr ession applicat ions.
This t r ansfor m can be inver t ed using idct2.
B
p q

p

q
A
m n
2m 1 + ( )p
2M
-------------------------------
2n 1 + ( )q
2N
-----------------------------,
0 p M 1
0 q N 1
cos cos
n 0 =
N 1

m 0 =
M 1

p
1 M, p 0 =
2 M , 1 p M 1
'

=
q
1 N , q 0 =
2 N , 1 q N 1
'

=
dct2
11-45
Example The commands below comput e t he discr et e cosine t r ansfor m for t he autumn
image. Not ice t hat most of t he ener gy is in t he upper -left cor ner .
RGB = imread('autumn.tif');
I = rgb2gray(RGB);
J = dct2(I);
imshow(log(abs(J)),[]), colormap(jet(64)), colorbar
Now set values less t han magnit ude 10 in t he DCT mat r ix t o zer o, and t hen
r econst r uct t he image using t he inver se DCT funct ion idct2.
J(abs(J) < 10) = 0;
K = idct2(J)/255;
imshow(K)
See Also fft2, idct2, ifft2
References J ain, Anil K. Fundamentals of Digital Image Processing. Englewood Cliffs, NJ :
Pr ent ice Hall, 1989. pp. 150-153.
dct2
11-46
Pennebaker , William B., and J oan L. Mit chell. J PEG: S till Image Data
Compression S tandard. Van Nost r and Reinhold, 1993.
dctmtx
11-47
11dct mt x
Purpose Comput e discr et e cosine t r ansfor m mat r ix
Syntax D = dctmtx(n)
Description D = dctmtx(n) r et ur ns t he n-by-n DCT t r ansfor m mat r ix. D*A is t he DCT of t he
columns of A and D'*A is t he inver se DCT of t he columns of A (when A is n-by-n).
Class Support n is a scalar of class double. D is r et ur ned as a mat r ix of class double.
Remarks If A is squar e, t he t wo-dimensional DCT of A can be comput ed as D*A*D'. This
comput at ion is somet imes fast er t han using dct2, especially if you ar e
comput ing a lar ge number of small DCTs, because D needs t o be det er mined
only once.
For example, in J PEG compr ession, t he DCT of each 8-by-8 block is comput ed.
To per for m t his comput at ion, use dctmtx t o det er mine D, and t hen calculat e
each DCT using D*A*D' (wher e A is each 8-by-8 block). This is fast er t han
calling dct2 for each individual block.
See Also dct2
dilate
11-48
11dilat e
Purpose Per for m dilat ion on a binar y image
Syntax BW2 = dilate(BW1,SE)
BW2 = dilate(BW1,SE,alg)
BW2 = dilate(BW1,SE,...,n)
Description BW2 = dilate(BW1,SE) per for ms dilat ion on t he binar y image BW1, using t he
binar y st r uct ur ing element SE. SE is a mat r ix cont aining only 1s and 0s.
BW2 = dilate(BW1,SE,alg) per for ms dilat ion using t he specified algor it hm.
alg is a st r ing t hat can have one of t hese values:
'spatial' (default ) pr ocesses t he image in t he spat ial domain.
'frequency' pr ocesses t he image in t he fr equency domain.
Bot h algor it hms pr oduce t he same r esult , but t hey make differ ent t r adeoffs
bet ween speed and memor y use. The fr equency algor it hm is fast er for lar ge
images and st r uct ur ing element s t han t he spat ial algor it hm, but uses much
mor e memor y.
BW2 = dilate(BW1,SE,...,n) per for ms t he dilat ion oper at ion n t imes.
Class Support The input image BW1 can be of class double or uint8. The out put image BW2 is
of class uint8.
Remarks You should use t he fr equency algor it hm only if you have a lar ge amount of
memor y on your syst em. If you use t his algor it hm wit h insufficient memor y, it
may act ually be slower t han t he spat ial algor it hm, due t o vir t ual memor y
paging. If t he fr equency algor it hm slows down your syst em excessively, or if
you r eceive out of memor y messages, use t he spat ial algor it hm inst ead.
dilate
11-49
Example BW1 = imread('text.tif');
SE = ones(6,2);
BW2 = dilate(BW1,SE);
imshow(BW1)
figure, imshow(BW2)
See Also bwmorph, erode
References Har alick, Rober t M., and Linda G. Shapir o. Computer and Robot Vision,
Volume I. Addison-Wesley, 1992. p. 158.
Gonzalez, Rafael C., and Richar d E. Woods. Digital Image Processing.
Addison-Wesley, 1992. p. 518.
dither
11-50
11dit her
Purpose Conver t an image, incr easing appar ent color r esolut ion by dit her ing
Syntax X = dither(RGB,map)
BW = dither(I)
Description X = dither(RGB,map) cr eat es an indexed image appr oximat ion of t he RGB
image in t he ar r ay RGB by dit her ing t he color s in color map map.
X = dither(RGB,map,Qm,Qe) cr eat es an indexed image fr om RGB, specifying t he
par amet er s Qm and Qe. Qm specifies t he number of quant izat ion bit s t o use along
each color axis for t he inver se color map, and Qe specifies t he number of
quant izat ion bit s t o use for t he color space er r or calculat ions. If Qe < Qm,
dit her ing cannot be per for med and an undit her ed indexed image is r et ur ned in
X. If you omit t hese par amet er s, dither uses t he default values Qm = 5, Qe = 8.
BW = dither(I) conver t s t he int ensit y image in t he mat r ix I t o t he binar y
(black and whit e) image BW by dit her ing.
Class Support The input image (RGB or I) can be of class uint8, uint16, or double. All ot her
input ar gument s must be of class double. The out put image (X or BW) is of class
uint8 if it is a binar y image or if it is an indexed image wit h 256 or fewer color s;
ot her wise it s class is double.
Algorithm dither incr eases t he appar ent color r esolut ion of an image by applying
Floyd-St einber gs er r or diffusion dit her algor it hm.
Reference Floyd, R. W. and L. St einber g. An Adapt ive Algor it hm for Spat ial Gr ay Scale.
International S ymposium Digest of Technical Papers. Societ y for Infor mat ion
Displays, 1975. p. 36.
Lim, J ae S. Two-Dimensional S ignal and Image Processing. Englewood Cliffs,
NJ : Pr ent ice Hall, 1990. pp. 469-476.
See Also rgb2ind
double
11-51
11double
Purpose Conver t dat a t o double pr ecision
Syntax B = double(A)
Description B = double(A) cr eat es a double-pr ecision ar r ay B fr om t he ar r ay A. If A is a
double ar r ay, B is ident ical t o A.
double is useful if you have a uint8 image ar r ay t hat you want t o per for m
ar it hmet ic oper at ions on, because MATLAB does not suppor t t hese oper at ions
on uint8 dat a.
Remarks double is a MATLAB built -in funct ion.
Example A = imread('saturn.tif');
B = sqrt(double(A));
See Also im2double, im2uint, uint8
edge
11-52
11
11edge
Purpose Find edges in an int ensit y image
Syntax 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 t akes an int ensit y image I as it s input , and r et ur ns a binar y image BW of
t he same size as I, wit h 1s wher e t he funct ion finds edges in I and 0s
elsewher e.
edge
11-53
edge suppor t s six differ ent edge-finding met hods:
The Sobel met hod finds edges using t he Sobel appr oximat ion t o t he
der ivat ive. It r et ur ns edges at t hose point s wher e t he gr adient of I is
maximum.
The Pr ewit t met hod finds edges using t he Pr ewit t appr oximat ion t o t he
der ivat ive. It r et ur ns edges at t hose point s wher e t he gr adient of I is
maximum.
The Rober t s met hod finds edges using t he Rober t s appr oximat ion t o t he
der ivat ive. It r et ur ns edges at t hose point s wher e t he gr adient of I is
maximum.
The Laplacian of Gaussian met hod finds edges by looking for zer o cr ossings
aft er filt er ing I wit h a Laplacian of Gaussian filt er .
The zer o-cr oss met hod finds edges by looking for zer o cr ossings aft er filt er ing
I wit h a filt er you specify.
The Canny met hod finds edges by looking for local maxima of t he gr adient of
I. The gr adient is calculat ed using t he der ivat ive of a Gaussian filt er . The
met hod uses t wo t hr esholds, t o det ect st r ong and weak edges, and includes
t he weak edges in t he out put only if t hey ar e connect ed t o st r ong edges. This
met hod is t her efor e less likely t han t he ot her s t o be fooled by noise, and
mor e likely t o det ect t r ue weak edges.
The par amet er s you can supply differ depending on t he met hod you specify. If
you do not specify a met hod, edge uses t he Sobel met hod.
Sobe l Me thod
BW = edge(I,'sobel') specifies t he Sobel met hod.
BW = edge(I,'sobel',thresh) specifies t he sensit ivit y t hr eshold for t he Sobel
met hod. edge ignor es all edges t hat ar e not st r onger t han thresh. If you do not
specify thresh, or if thresh is empt y ([]), edge chooses t he value
aut omat ically.
BW = edge(I,'sobel',thresh,direction) specifies dir ect ion of det ect ion for
t he Sobel met hod. direction is a st r ing specifying whet her t o look for
'horizontal' or 'vertical' edges, or 'both' (t he default ).
[BW,thresh] = edge(I,'sobel',...) r et ur ns t he t hr eshold value.
edge
11-54
Prewi tt Method
BW = edge(I,'prewitt') specifies t he Pr ewit t met hod.
BW = edge(I,'prewitt',thresh) specifies t he sensit ivit y t hr eshold for t he
Pr ewit t met hod. edge ignor es all edges t hat ar e not st r onger t han thresh. If
you do not specify thresh, or if thresh is empt y ([]), edge chooses t he value
aut omat ically.
BW = edge(I,'prewitt',thresh,direction) specifies dir ect ion of det ect ion
for t he Pr ewit t met hod. direction is a st r ing specifying whet her t o look for
'horizontal' or 'vertical' edges, or 'both' (t he default ).
[BW,thresh] = edge(I,'prewitt',...) r et ur ns t he t hr eshold value.
Roberts Met hod
BW = edge(I,method) specifies t he Rober t s met hod.
BW = edge(I,method,thresh) specifies t he sensit ivit y t hr eshold for t he
Rober t s met hod. edge ignor es all edges t hat ar e not st r onger t han thresh. If
you do not specify thresh, or if thresh is empt y ([]), edge chooses t he value
aut omat ically.
[BW,thresh] = edge(I,method,...) r et ur ns t he t hr eshold value.
Laplaci an of Gaus s i an Me thod
BW = edge(I,'log') specifies t he Laplacian of Gaussian met hod.
BW = edge(I,'log',thresh) specifies t he sensit ivit y t hr eshold for t he
Laplacian of Gaussian met hod. edge ignor es all edges t hat ar e not st r onger
t han thresh. If you do not specify thresh, or if thresh is empt y ([]), edge
chooses t he value aut omat ically.
BW = edge(I,'log',thresh,sigma) specifies t he Laplacian of Gaussian
met hod, using sigma as t he st andar d deviat ion of t he LoG filt er . The default
sigma is 2; t he size of t he filt er is n-by-n, wher e n = ceil(sigma*3)*2+1.
[BW,thresh] = edge(I,'log',...) r et ur ns t he t hr eshold value.
edge
11-55
Zero-cross Met hod
BW = edge(I,'zerocross',thresh,h) specifies t he zer o-cr oss met hod, using
t he filt er h. thresh is t he sensit ivit y t hr eshold; if t he ar gument is empt y ([]),
edge chooses t he sensit ivit y t hr eshold aut omat ically.
[BW,thresh] = edge(I,'zerocross',...) r et ur ns t he t hr eshold value.
Canny Met hod
BW = edge(I,'canny') specifies t he Canny met hod.
BW = edge(I,'canny',thresh) specifies sensit ivit y t hr esholds for t he Canny
met hod. thresh is a t wo-element vect or in which t he fir st element is t he low
t hr eshold, and t he second element is t he high t hr eshold. If you specify a scalar
for thresh, t his value is used for t he high t hr eshold and 0.4*thresh is used for
t he low t hr eshold. If you do not specify thresh, or if thresh is empt y ([]), edge
chooses low and high values aut omat ically.
BW = edge(I,'canny',thresh,sigma) specifies t he Canny met hod, using
sigma as t he st andar d deviat ion of t he Gaussian filt er . The default sigma is 1;
t he size of t he filt er is chosen aut omat ically, based on sigma.
[BW,thresh] = edge(I,'canny',...) r et ur ns t he t hr eshold values as a
t wo-element vect or .
Class Support I can be of class uint8, uint16, or double. BW is of class uint8.
Remarks For t he 'log' and 'zerocross' met hods, if you specify a t hr eshold of 0, t he
out put image has closed cont our s, because it includes all of t he zer o cr ossings
in t he input image.
edge
11-56
Example Find t he edges of t he rice.tif image using t he Pr ewit t and Canny met hods.
I = imread('rice.tif');
BW1 = edge(I,'prewitt');
BW2 = edge(I,'canny');
imshow(BW1);
figure, imshow(BW2)
References Lim, J ae S. Two-Dimensional S ignal and Image Processing. Englewood Cliffs,
NJ : Pr ent ice Hall, 1990. pp. 478-488.
Par ker , J ames R. Algorithms for Image Processing and Computer Vision. New
Yor k: J ohn Wiley & Sons, Inc., 1997. pp. 23-29.
Canny, J ohn. A Comput at ional Appr oach t o Edge Det ect ion, IEEE
Transactions on Pattern Analysis and Machine Intelligence, 1986. Vol. PAMI-8,
No. 6, pp. 679-698.
erode
11-57
11er ode
Purpose Per for m er osion on a binar y image
Syntax BW2 = erode(BW1,SE)
BW2 = erode(BW1,SE,alg)
BW2 = erode(BW1,SE,...,n)
Description BW2 = erode(BW1,SE) per for ms er osion on t he binar y image BW1, using t he
binar y st r uct ur ing element SE. SE is a mat r ix cont aining only 1s and 0s.
BW2 = erode(BW1,SE,alg) per for ms er osion using t he specified algor it hm. alg
is a st r ing t hat can have one of t hese values:
'spatial' (default ) pr ocesses t he image in t he spat ial domain.
'frequency' pr ocesses t he image in t he fr equency domain.
Bot h algor it hms pr oduce t he same r esult , but t hey make differ ent t r adeoffs
bet ween speed and memor y use. The fr equency algor it hm is fast er for lar ge
images and st r uct ur ing element s t han t he spat ial algor it hm, but uses much
mor e memor y.
BW2 = erode(BW1,SE,...,n) per for ms t he er osion oper at ion n t imes.
Class Support The input image BW1 can be of class double or uint8. The out put image BW2 is
of class uint8.
Remarks You should use t he fr equency algor it hm only if you have a lar ge amount of
memor y on your syst em. If you use t his algor it hm wit h insufficient memor y, it
may act ually be slower t han t he spat ial algor it hm, due t o vir t ual memor y
paging. If t he fr equency algor it hm slows down your syst em excessively, or if
you r eceive out of memor y messages, use t he spat ial algor it hm inst ead.
erode
11-58
Example BW1 = imread('text.tif');
SE = ones(3,1);
BW2 = erode(BW1,SE);
imshow(BW1)
figure, imshow(BW2)
See Also bwmorph, dilate
References Har alick, Rober t M., and Linda G. Shapir o. Computer and Robot Vision,
Volume I. Addison-Wesley, 1992. p. 158.
Gonzalez, Rafael C., and Richar d E. Woods. Digital Image Processing.
Addison-Wesley, 1992. p. 518.
fft2
11-59
11fft 2
Purpose Comput e t wo-dimensional fast Four ier t r ansfor m (FFT)
Syntax B = fft2(A)
B = fft2(A,m,n)
Description B = fft2(A) per for ms a t wo-dimensional fast Four ier t r ansfor m, r et ur ning t he
r esult in B. B is t he same size as A; if A is a vect or , B has t he same or ient at ion
as A.
B = fft2(A,m,n) t r uncat es or zer o pads A, if necessar y, t o cr eat e an m-by-n
mat r ix befor e per for ming t he FFT. The r esult B is also m-by-n.
Class Support The input mat r ix A can be of class double or of any int eger class. The out put
mat r ix B is of class double.
Remarks fft2 is a funct ion in MATLAB.
fft2
11-60
Example 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 comput es t he one-dimensional fft of each column A, t hen of each r ow of
t he r esult . The t ime r equir ed t o comput e fft2(A) depends on t he number of
pr ime fact or s of m and n. fft2 is fast est when m and n ar e power s of 2.
See Also dct2, fftshift, idct2, ifft2
fft, ifft in t he online MATLAB Funct ion Refer ence
fftn
11-61
11fft n
Purpose Comput e N-dimensional fast Four ier t r ansfor m
Syntax B = fftn(A)
B = fftn(A,siz)
Description B = fftn(A) per for ms t he N-dimensional fast Four ier t r ansfor m. The r esult B
is t he same size as A.
B = fftn(A,siz) pads A wit h zer os (or t r uncat es A) t o cr eat e an N-dimensional
ar r ay of size siz befor e doing t he t r ansfor m. The size of t he r esult is siz.
Class Support The input mat r ix A can be of class double or of any int eger class. The out put
mat r ix B is of class double.
Remarks fftn is a funct ion in MATLAB.
Algorithm fftn(A) is equivalent t o:
B = A;
for p = 1:length(size(A))
B = fft(B,[],p);
end
This code comput es t he one-dimensional fast Four ier t r ansfor m along each
dimension of A. The t ime r equir ed t o comput e fftn(A) depends st r ongly on t he
number of pr ime fact or s of t he dimensions of A. It is fast est when all of t he
dimensions ar e power s of 2.
See Also fft2, ifftn
fft in t he online MATLAB Funct ion Refer ence
fftshift
11-62
11fft shift
Purpose Shift DC component of fast Four ier t r ansfor m t o cent er of spect r um
Syntax B = fftshift(A)
Description B = fftshift(A) r ear r anges t he out put s of fft, fft2, and fftn by moving t he
zer o fr equency component t o t he cent er of t he ar r ay.
For vect or s, fftshift(A) swaps t he left and r ight halves of A. For mat r ices,
fftshift(A) swaps quadr ant s one and t hr ee of A wit h quadr ant s t wo and four .
For higher -dimensional ar r ays, fftshift(A) swaps half-spaces of A along
each dimension.
Class Support The input mat r ix A can be of class double or of any int eger class. The out put
mat r ix B is of t he same class as A.
Remarks fftshift is a funct ion in MATLAB.
Example B = fftn(A);
C = fftshift(B);
See Also fft2, fftn, ifftshift
fft in t he online MATLAB Funct ion Refer ence
filter2
11-63
11filt er 2
Purpose Per for m t wo-dimensional linear filt er ing
Syntax B = filter2(h,A)
B = filter2(h,A,shape)
Description B = filter2(h,A) filt er s t he dat a in A wit h t he t wo-dimensional FIR filt er in
t he mat r ix h. It comput es t he r esult , B, using t wo-dimensional cor r elat ion, and
r et ur ns t he cent r al par t of t he cor r elat ion t hat is t he same size as A.
B = filter2(h,A,shape) r et ur ns t he par t of B specified by t he shape
par amet er . shape is a st r ing wit h one of t hese values:
'full' r et ur ns t he full t wo-dimensional cor r elat ion. In t his case, B is lar ger
t han A.
'same' (t he default ) r et ur ns t he cent r al par t of t he cor r elat ion. In t his case,
B is t he same size as A.
'valid' r et ur ns only t hose par t s of t he cor r elat ion t hat ar e comput ed
wit hout zer o-padded edges. In t his case, B is smaller t han A.
Class Support The mat r ix input s t o filter2 can be of class double or of any int eger class. The
out put mat r ix B is of class double.
Remarks Two-dimensional cor r elat ion is equivalent t o t wo-dimensional convolut ion
wit h t he filt er mat r ix r ot at ed 180 degr ees. See t he Algor it hm sect ion for mor e
infor mat ion about how filter2 per for ms linear filt er ing.
filter2 is a funct ion in MATLAB.
filter2
11-64
Example A = magic(6)
A =
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
h = fspecial('sobel')
h =
1 2 1
0 0 0
1 2 1
B = filter2(h,A,'valid')
B =
8 4 4 8
23 44 5 40
23 50 1 40
8 4 4 8
Algorithm Given an image A and a t wo-dimensional FIR filt er h, filter2 r ot at es your
filt er mat r ix (t he comput at ional molecule) 180 degr ees t o cr eat e a convolut ion
ker nel. It t hen calls conv2, t he t wo-dimensional convolut ion funct ion, t o
implement t he filt er ing oper at ion.
filter2 uses conv2 t o comput e t he full t wo-dimensional convolut ion of t he FIR
filt er wit h t he input mat r ix. By default , filter2 t hen ext r act s t he cent r al par t
of t he convolut ion t hat is t he same size as t he input mat r ix, and r et ur ns t his as
t he r esult . If t he shape par amet er specifies an alt er nat e par t of t he convolut ion
for t he r esult , filter2 r et ur ns t he appr opr iat e par t .
See Also conv2, roifilt2
freqspace
11-65
11fr eqspace
Purpose Det er mine fr equency spacing for t wo-dimensional fr equency r esponse
Syntax [f1,f2] = freqspace(n)
[f1,f2] = freqspace([m n])
[x1,y1] = freqspace(...,'meshgrid')
f = freqspace(N)
f = freqspace(N,'whole')
Description freqspace r et ur ns t he implied fr equency r ange for equally spaced fr equency
r esponses. freqspace is useful when cr eat ing desir ed fr equency r esponses for
fsamp2, fwind1, and fwind2, as well as for var ious one-dimensional
applicat ions.
[f1,f2] = freqspace(n) r et ur ns t he t wo-dimensional fr equency vect or s f1
and f2 for an n-by-n mat r ix.
For n odd, bot h f1 and f2 ar e [n+1:2:n1]/n.
For n even, bot h f1 and f2 ar e [n:2:n2]/n.
[f1,f2] = freqspace([m n]) r et ur ns t he t wo-dimensional fr equency vect or s
f1 and f2 for an m-by-n mat r ix.
[x1,y1] = freqspace(...,'meshgrid') is equivalent t o
[f1,f2] = freqspace(...);
[x1,y1] = meshgrid(f1,f2);
f = freqspace(N) r et ur ns t he one-dimensional fr equency vect or f assuming N
evenly spaced point s ar ound t he unit cir cle. For N even or odd, f is (0:2/N:1).
For N even, freqspace t her efor e r et ur ns (N+2)/2 point s. For N odd, it r et ur ns
(N+1)/2 point s.
f = freqspace(N,'whole') r et ur ns N evenly spaced point s ar ound t he whole
unit cir cle. In t his case, f is 0:2/N:2*(N1)/N.
Remarks freqspace is a funct ion in MATLAB.
See Also fsamp2, fwind1, fwind2
meshgrid in t he online MATLAB Funct ion Refer ence
freqz2
11-66
11fr eqz2
Purpose Comput e t wo-dimensional fr equency r esponse
Syntax [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) r et ur ns H, t he n2-by-n1 fr equency r esponse of
h, and t he fr equency vect or s f1 (of lengt h n1) and f2 (of lengt h n2). h is a
t wo-dimensional FIR filt er , in t he for m of a comput at ional molecule. f1 and f2
ar e r et ur ned as nor malized fr equencies in t he r ange 1.0 t o 1.0, wher e 1.0
cor r esponds t o half t he sampling fr equency, or r adians.
[H,f1,f2] = freqz2(h,[n2 n1]) r et ur ns t he same r esult r et ur ned 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) r et ur ns t he fr equency r esponse for t he FIR
filt er h at fr equency values in f1 and f2. These fr equency values must be in t he
r ange 1.0 t o 1.0, wher e 1.0 cor r esponds t o half t he sampling fr equency, or
r adians.
[...] = freqz2(h,...,[dx dy]) uses [dx dy] t o over r ide t he int er sample
spacing in h. dx det er mines t he spacing for t he x-dimension and dy det er mines
t he spacing for t he y-dimension. The default spacing is 0.5, which cor r esponds
t o a sampling fr equency of 2.0.
[...] = freqz2(h,...,dx) uses dx t o det er mine t he int er sample spacing in
bot h dimensions.
Wit h no out put ar gument s, freqz2(...) pr oduces a mesh plot of t he
t wo-dimensional magnit ude fr equency r esponse.
Class Support The input mat r ix h can be of class double or of any int eger class. All ot her
input s t o freqz2 must be of class double. All out put s ar e of class double.
freqz2
11-67
Example Use t he window met hod t o cr eat e a 16-by-16 filt er , t hen view it s fr equency
r esponse 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 freqz in t he Signal Pr ocessing Toolbox
fsamp2
11-68
11fsamp2
Purpose Design t wo-dimensional FIR filt er using fr equency sampling
Syntax h = fsamp2(Hd)
h = fsamp2(f1,f2,Hd,[m n])
Description fsamp2 designs t wo-dimensional FIR filt er s based on a desir ed
t wo-dimensional fr equency r esponse sampled at point s on t he Car t esian plane.
h = fsamp2(Hd) designs a t wo-dimensional FIR filt er wit h fr equency r esponse
Hd, and r et ur ns t he filt er coefficient s in mat r ix h. (fsamp2 r et ur ns h as a
comput at ional molecule, which is t he appr opr iat e for m t o use wit h filter2.)
The filt er h has a fr equency r esponse t hat passes t hr ough point s in Hd. If Hd is
m-by-n, t hen h is also m-by-n.
Hd is a mat r ix cont aining t he desir ed fr equency r esponse sampled at equally
spaced point s bet ween 1.0 and 1.0 along t he x and y fr equency axes, wher e 1.0
cor r esponds t o half t he sampling fr equency, or r adians.
For accur at e r esult s, use fr equency point s r et ur ned by freqspace t o cr eat e Hd.
(See t he ent r y for freqspace for mor e infor mat ion.)
h = fsamp2(f1,f2,Hd,[m n]) pr oduces an m-by-n FIR filt er by mat ching t he
filt er r esponse at t he point s in t he vect or s f1 and f2. The fr equency vect or s f1
and f2 ar e in nor malized fr equency, wher e 1.0 cor r esponds t o half t he sampling
fr equency, or r adians. The r esult ing filt er fit s t he desir ed r esponse as closely
as possible in t he least squar es sense. For best r esult s, t her e must be at least
m*n desir ed fr equency point s. fsamp2 issues a war ning if you specify fewer t han
m*n point s.
Class Support The input mat r ix Hd can be of class double or of any int eger class. All ot her
input s t o fsamp2 must be of class double. All out put s ar e of class double.
Example Use fsamp2 t o design an appr oximat ely symmet r ic t wo-dimensional bandpass
filt er wit h passband bet ween 0.1 and 0.5 (nor malized fr equency, wher e 1.0
cor r esponds t o half t he sampling fr equency, or r adians).
H
d
f
1
f
2
, ( ) H
d

1

2
, ( ) =

1
f
1
=
2
, f
2
=
fsamp2
11-69
1 Cr eat e a mat r ix Hd t hat cont ains t he desir ed bandpass r esponse. Use
freqspace t o cr eat e t he fr equency r ange vect or s 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 t he filt er t hat passes t hr ough t his r esponse.
h = fsamp2(Hd);
fsamp2
11-70
freqz2(h)
Algorithm fsamp2 comput es t he filt er h by t aking t he inver se discr et e Four ier t r ansfor m
of t he desir ed fr equency r esponse. If t he desir ed fr equency r esponse is r eal and
symmet r ic (zer o phase), t he r esult ing filt er is also zer o phase.
See Also conv2, filter2, freqspace, ftrans2, fwind1, fwind2
Reference Lim, J ae S. Two-Dimensional S ignal and Image Processing. Englewood Cliffs,
NJ : Pr ent ice Hall, 1990. pp. 213-217.
fspecial
11-71
11fspecial
Purpose Cr eat e pr edefined filt er s
Syntax h = fspecial(type)
h = fspecial(type,parameters)
Description h = fspecial(type) cr eat es a t wo-dimensional filt er h of t he specified t ype.
(fspecial r et ur ns h as a comput at ional molecule, which is t he appr opr iat e
for m t o use wit h filter2.) type is a st r ing having one of t hese values:
'gaussian' for a Gaussian lowpass filt er
'sobel' for a Sobel hor izont al edge-emphasizing filt er
'prewitt' for a Pr ewit t hor izont al edge-emphasizing filt er
'laplacian' for a filt er appr oximat ing t he t wo-dimensional Laplacian
oper at or
'log' for a Laplacian of Gaussian filt er
'average' for an aver aging filt er
'unsharp' for an unshar p cont r ast enhancement filt er
Depending on type, fspecial may t ake addit ional par amet er s which you can
supply. These par amet er s all have default values.
h = fspecial('gaussian',n,sigma) r et ur ns a r ot at ionally symmet r ic
Gaussian lowpass filt er wit h st andar d deviat ion sigma (in pixels). n is a 1-by-2
vect or specifying t he number of r ows and columns in h. (n can also be a scalar ,
in which case h is n-by-n.) If you do not specify t he par amet er s, fspecial uses
t he default values of [3 3] for n and 0.5 for sigma.
h = fspecial('sobel') r et ur ns t his 3-by-3 hor izont al edge-finding and
y-der ivat ive appr oximat ion filt er :
[ 1 2 1
0 0 0
1 2 1 ]
To find ver t ical edges, or for x-der ivat ives, use h'.
fspecial
11-72
h = fspecial('prewitt') r et ur ns t his 3-by-3 hor izont al edge-finding and
y-der ivat ive appr oximat ion filt er :
[ 1 1 1
0 0 0
1 1 1 ]
To find ver t ical edges, or for x-der ivat ives, use h'.
h = fspecial('laplacian',alpha) r et ur ns a 3-by-3 filt er appr oximat ing t he
t wo-dimensional Laplacian oper at or . The par amet er alpha cont r ols t he shape
of t he Laplacian and must be in t he r ange 0 t o 1.0. fspecial uses t he default
value of 0.2 if you do not specify alpha.
h = fspecial('log',n,sigma) r et ur ns a r ot at ionally symmet r ic Laplacian of
Gaussian filt er wit h st andar d deviat ion sigma (in pixels). n is a 1-by-2 vect or
specifying t he number of r ows and columns in h. (n can also be a scalar , in
which case h is n-by-n.) If you do not specify t he par amet er s, fspecial uses t he
default values of [5 5] for n and 0.5 for sigma.
h = fspecial('average',n) r et ur ns an aver aging filt er . n is a 1-by-2 vect or
specifying t he number of r ows 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 t he default value
of [3 3].
h = fspecial('unsharp',alpha) r et ur ns a 3-by-3 unshar p cont r ast
enhancement filt er . fspecial cr eat es t he unshar p filt er fr om t he negat ive of
t he Laplacian filt er wit h par amet er alpha. alpha cont r ols t he shape of t he
Laplacian and must be in t he r ange 0 t o 1.0. fspecial uses t he default value
of 0.2 if you do not specify alpha.
fspecial
11-73
Example I = imread('saturn.tif');
h = fspecial('unsharp',0.5);
I2 = filter2(h,I)/255;
imshow(I)
figure, imshow(I2)
Algorithms fspecial cr eat es Gaussian filt er s using:
fspecial cr eat es Laplacian filt er s using:
h
g
n
1
n
2
, ( ) e
n
1
2
n
2
2
+ ( ) 2
2
( )
=
h n
1
n
2
, ( )
h
g
n
1
n
2
, ( )
h
g
n
2

n
1

--------------------------- =

2
2
x
2
---------

2
y
2
--------- + =

2 4
1 + ( )
------------------

4
---
1
4
-------------

4
---
1
4
------------- 1
1
4
-------------

4
---
1
4
-------------

4
---

fspecial
11-74
fspecial cr eat es Laplacian of Gaussian (LoG) filt er s using:
fspecial cr eat es aver aging filt er s using:
ones(n(1),n(2))/(n(1)*n(2))
fspecial cr eat es unshar p filt er s using:
See Also conv2, edge, filter2, fsamp2, fwind1, fwind2
del2 in t he online MATLAB Funct ion Refer ence
h
g
n
1
n
2
, ( ) e
n
1
2
n
2
2
+ ( ) 2
2
( )
=
h n
1
n
2
, ( )
n
1
2
n
2
2
+ 2
2
( )h
g
n
1
n
2
, ( )
2
6
h
g
n
2

n
1

------------------------------------------------------------------------ =
1
1 + ( )
------------------
1
1 5 + 1
1
ftrans2
11-75
11ft r ans2
Purpose Design t wo-dimensional FIR filt er using fr equency t r ansfor mat ion
Syntax h = ftrans2(b,t)
h = ftrans2(b)
Description h = ftrans2(b,t) pr oduces t he t wo-dimensional FIR filt er h t hat cor r esponds
t o t he one-dimensional FIR filt er b using t he t r ansfor m t. (ftrans2 r et ur ns h
as a comput at ional molecule, which is t he appr opr iat e for m t o use wit h
filter2.) b must be a one-dimensional, odd-lengt h (Type I) FIR filt er such
as can be r et ur ned by fir1, fir2, or remez in t he Signal Pr ocessing Toolbox.
The t r ansfor m mat r ix t cont ains coefficient s t hat define t he fr equency
t r ansfor mat ion t o use. If t is m-by-n and b has lengt h Q, t hen h is size
((m1)*(Q1)/2+1)-by-((n1)*(Q1)/2+1).
h = ftrans2(b) uses t he McClellan t r ansfor m mat r ix t:
t = [1 2 1; 2 4 2; 1 2 1]/8;
Remarks The t r ansfor mat ion below defines t he fr equency r esponse of t he
t wo-dimensional filt er r et ur ned by ftrans2,
wher e B() is t he Four ier t r ansfor m of t he one-dimensional filt er b,
and T(
1
,
2
) is t he Four ier t r ansfor m of t he t r ansfor mat ion mat r ix t.
The r et ur ned filt er h is t he inver se Four ier t r ansfor m of H(
1
,
2
).
H
1

2
, ( ) B ( )
cos T
1

2
, ( ) =
=
B ( ) b n ( )e
j n
n N =
N

=
T
1

2
, ( ) t n
1
n
2
, ( )e
j
1
n
1

e
j
2
n
2

n
1

n
2

=
h n
1
n
2
, ( )
1
2 ( )
2
-------------- H
1

2
, ( )e
j
1
n
1
e
j
2
n
2

1
d
2
d

=
ftrans2
11-76
Example Use ftrans2 t o design an appr oximat ely cir cular ly symmet r ic t wo-dimensional
bandpass filt er wit h passband bet ween 0.1 and 0.6 (nor malized fr equency,
wher e 1.0 cor r esponds t o half t he sampling fr equency, or r adians).
1 Since ftrans2 t r ansfor ms a one-dimensional FIR filt er t o cr eat e a
t wo-dimensional filt er , fir st design a one-dimensional FIR bandpass filt er
using t he Signal Pr ocessing Toolbox funct ion 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/pi1,fftshift(abs(H)))
2 Use ftrans2 wit h t he default McClellan t r ansfor mat ion t o cr eat e t he
desir ed appr oximat ely cir cular ly symmet r ic filt er .
h = ftrans2(b);
ftrans2
11-77
freqz2(h)
See Also conv2, filter2, fsamp2, fwind1, fwind2
Reference Lim, J ae S. Two-Dimensional S ignal and Image Processing. Englewood Cliffs,
NJ : Pr ent ice Hall, 1990. pp. 218-237.
fwind1
11-78
11fwind1
Purpose Design t wo-dimensional FIR filt er using one-dimensional window met hod
Syntax h = fwind1(Hd,win)
h = fwind1(Hd,win1,win2)
h = fwind1(f1,f2,Hd,...)
Description fwind1 designs t wo-dimensional FIR filt er s using t he window met hod. fwind1
uses a one-dimensional window specificat ion t o design a t wo-dimensional FIR
filt er based on t he desir ed fr equency r esponse Hd. fwind1 wor ks wit h
one-dimensional windows only; use fwind2 t o wor k wit h t wo-dimensional
windows.
h = fwind1(Hd,win) designs a t wo-dimensional FIR filt er h wit h fr equency
r esponse Hd. (fwind1 r et ur ns h as a comput at ional molecule, which is t he
appr opr iat e for m t o use wit h filter2.) fwind1 uses t he one-dimensional
window win t o for m an appr oximat ely cir cular ly symmet r ic t wo-dimensional
window using Huangs met hod. You can specify win using windows fr om t he
Signal Pr ocessing Toolbox, such as boxcar, hamming, hanning, bartlett,
blackman, kaiser, or chebwin. If length(win) is n, t hen h is n-by-n.
Hd is a mat r ix cont aining t he desir ed fr equency r esponse sampled at equally
spaced point s bet ween 1.0 and 1.0 (in nor malized fr equency, wher e 1.0
cor r esponds t o half t he sampling fr equency, or r adians) along t he x and y
fr equency axes. For accur at e r esult s, use fr equency point s r et ur ned by
freqspace t o cr eat e Hd. (See t he ent r y for freqspace for mor e infor mat ion.)
h = fwind1(Hd,win1,win2) uses t he t wo one-dimensional windows win1 and
win2 t o cr eat e a separ able t wo-dimensional window. If length(win1) is n and
length(win2) is m, t hen h is m-by-n.
h = fwind1(f1,f2,Hd,...) let s you specify t he desir ed fr equency r esponse Hd
at ar bit r ar y fr equencies (f1 and f2) along t he x and y axes. The fr equency
vect or s f1 and f2 should be in t he r ange 1.0 t o 1.0, wher e 1.0 cor r esponds t o
half t he sampling fr equency, or r adians. The lengt h of t he window(s) cont r ols
t he size of t he r esult ing filt er , as above.
Class Support The input mat r ix Hd can be of class double or of any int eger class. All ot her
input s t o fwind1 must be of class double. All out put s ar e of class double.
fwind1
11-79
Example Use fwind1 t o design an appr oximat ely cir cular ly symmet r ic t wo-dimensional
bandpass filt er wit h passband bet ween 0.1 and 0.5 (nor malized fr equency,
wher e 1.0 cor r esponds t o half t he sampling fr equency, or r adians).
1 Cr eat e a mat r ix Hd t hat cont ains t he desir ed bandpass r esponse. Use
freqspace t o cr eat e t he fr equency r ange vect or s 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)
fwind1
11-80
2 Design t he filt er using a one-dimensional Hamming window.
h = fwind1(Hd,hamming(21));
freqz2(h)
Algorithm fwind1 t akes a one-dimensional window specificat ion and for ms an
appr oximat ely cir cular ly symmet r ic t wo-dimensional window using Huangs
met hod,
wher e w(t) is t he one-dimensional window and w(n
1
,n
2
) is t he r esult ing
t wo-dimensional window.
Given t wo windows, fwind1 for ms a separ able t wo-dimensional window,
w n
1
n
2
, ( ) w t ( )
t n
1
2
n
2
2
+ =
=
w n
1
n
2
, ( ) w
1
n
1
( )w
2
n
2
( ) =
fwind1
11-81
fwind1 calls fwind2 wit h Hd and t he t wo-dimensional window. fwind2
comput es h using an inver se Four ier t r ansfor m and mult iplicat ion by t he
t wo-dimensional window.
See Also conv2, filter2, fsamp2, freqspace, ftrans2, fwind2
Reference Lim, J ae S. Two-Dimensional S ignal and Image Processing. Englewood Cliffs,
NJ : Pr ent ice Hall, 1990.
h
d
n
1
n
2
, ( )
1
2 ( )
2
-------------- H
d

1

2
, ( )e
j
1
n
1
e
j
2
n
2

1
d
2
d

=
h n
1
n
2
, ( ) h
d
n
1
n
2
, ( )w n
1
n
2
, ( ) =
fwind2
11-82
11fwind2
Purpose Design t wo-dimensional FIR filt er using t wo-dimensional window met hod
Syntax h = fwind2(Hd,win)
h = fwind2(f1,f2,Hd,win)
Description Use fwind2 t o design t wo-dimensional FIR filt er s using t he window met hod.
fwind2 uses a t wo-dimensional window specificat ion t o design a
t wo-dimensional FIR filt er based on t he desir ed fr equency r esponse Hd. fwind2
wor ks wit h t wo-dimensional windows; use fwind1 t o wor k wit h
one-dimensional windows.
h = fwind2(Hd,win) pr oduces t he t wo-dimensional FIR filt er h using an
inver se Four ier t r ansfor m of t he desir ed fr equency r esponse Hd and
mult iplicat ion by t he window win. Hd is a mat r ix cont aining t he desir ed
fr equency r esponse at equally spaced point s in t he Car t esian plane. fwind2
r et ur ns h as a comput at ional molecule, which is t he appr opr iat e for m t o use
wit h filter2. h is t he same size as win.
For accur at e r esult s, use fr equency point s r et ur ned by freqspace t o cr eat e Hd.
(See t he ent r y for freqspace for mor e infor mat ion.
h = fwind2(f1,f2,Hd,win) let s you specify t he desir ed fr equency r esponse Hd
at ar bit r ar y fr equencies (f1 and f2) along t he x and y axes. The fr equency
vect or s f1 and f2 should be in t he r ange 1.0 t o 1.0, wher e 1.0 cor r esponds t o
half t he sampling fr equency, or r adians. h is t he same size as win.
Class Support The input mat r ix Hd can be of class double or of any int eger class. All ot her
input s t o fwind2 must be of class double. All out put s ar e of class double.
Example Use fwind2 t o design an appr oximat ely cir cular ly symmet r ic t wo-dimensional
bandpass filt er wit h passband bet ween 0.1 and 0.5 (nor malized fr equency,
wher e 1.0 cor r esponds t o half t he sampling fr equency, or r adians).
fwind2
11-83
1 Cr eat e a mat r ix Hd t hat cont ains t he desir ed bandpass r esponse. Use
freqspace t o cr eat e t he fr equency r ange vect or s 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)
fwind2
11-84
2 Cr eat e a t wo-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 t he filt er using t he window fr om st ep 2.
h = fwind2(Hd,win);
fwind2
11-85
freqz2(h)
Algorithm fwind2 comput es h using an inver se Four ier t r ansfor m and mult iplicat ion by
t he t wo-dimensional window win,
See Also conv2, filter2, fsamp2, freqspace, ftrans2, fwind1
Reference Lim, J ae S. Two-Dimensional S ignal and Image Processing. Englewood Cliffs,
NJ : Pr ent ice Hall, 1990. pp. 202-213.
h
d
n
1
n
2
, ( )
1
2 ( )
2
-------------- H
d

1

2
, ( )e
j
1
n
1
e
j
2
n
2

1
d
2
d

=
h n
1
n
2
, ( ) h
d
n
1
n
2
, ( )w n
1
n
2
, ( ) =
getimage
11-86
11get image
Purpose Get image dat a fr om axes
Syntax A = getimage(h)
[x,y,A] = getimage(h)
[...,A,flag] = getimage(h)
[...] = getimage
Description A = getimage(h) r et ur ns t he fir st image dat a cont ained in t he Handle
Gr aphics object h. h can be a figur e, axes, image, or t ext ur e-mapped sur face. A
is ident ical t o t he image CData; it cont ains t he same values and is of t he same
class (uint8 or double) as t he image CData. If h is not an image or does not
cont ain an image or t ext ur e-mapped sur face, A is empt y.
[x,y,A] = getimage(h) r et ur ns t he image XData in x and t he YData in y. XData
and YData ar e t wo-element vect or s t hat indicat e t he r ange of t he x-axis and
y-axis.
[...,A,flag] = getimage(h) r et ur ns an int eger flag t hat indicat es t he t ype
of image h cont ains. This t able summar izes t he possible values for flag.
[...] = getimage r et ur ns infor mat ion for t he cur r ent axes. It is equivalent t o
[...] = getimage(gca).
Class Support The out put ar r ay A is of t he same class as t he image CData. All ot her input s and
out put s ar e of class double.
Flag Type of image
0 Not an image; A is r et ur ned as an empt y mat r ix
1 Int ensit y image wit h values in st andar d r ange ([0,1] for
double ar r ays, [0,255] for uint8 ar r ays, [0,65535] for uint16
ar r ays)
2 Indexed image
3 Int ensit y dat a, but not in st andar d r ange
4 RGB image
getimage
11-87
Example This example illust r at es obt aining t he image dat a fr om an image displayed
dir ect ly fr om a file.
imshow rice.tif
I = getimage;
gray2ind
11-88
11gr ay2ind
Purpose Conver t an int ensit y image t o an indexed image
Syntax [X,map] = gray2ind(I,n)
Description gray2ind scales, t hen r ounds, an int ensit y image t o pr oduce an equivalent
indexed image.
[X,map] = gray2ind(I,n) conver t s t he int ensit y image I t o an indexed image
X wit h color map gray(n). If n is omit t ed, it default s t o 64.
Class Support The input image I can be of class uint8, uint16, or double. The class of t he
out put image X is uint8 if t he color map lengt h is less t han or equal t o 256. If
t he color map lengt h is gr eat er t han 256, X is of class double.
See Also ind2gray
grayslice
11-89
11gr ayslice
Purpose Cr eat e indexed image fr om int ensit y image, using mult ilevel t hr esholding
Syntax X = grayslice(I,n)
X = grayslice(I,v)
Description X = grayslice(I,n) t hr esholds t he int ensit y image I using cut off values
, r et ur ning an indexed image in X.
X = grayslice(I,v), wher e v is a vect or of values bet ween 0 and 1, t hr esholds
I using t he values of v, r et ur ning an indexed image in X.
You can view t he t hr esholded image using imshow(X,map) wit h a color map of
appr opr iat e lengt h.
Class Support The input image I can be of class uint8, uint16, or double. Not e t hat t he
t hr eshold values ar e always bet ween 0 and 1, even if I is of class uint8 or
uint16. In t his case, each t hr eshold value is mult iplied by 255 or 65535 t o
det er mine t he act ual t hr eshold t o use.
The class of t he out put image X depends on t he number of t hr eshold values, as
specified by n or length(v). If t he number of t hr eshold values is less t han 256,
t hen X is of class uint8, and t he values in X r ange fr om 0 t o n or length(v). If
t he number of t hr eshold values is 256 or gr eat er , X is of class double, and t he
values in X r ange fr om 1 t o n+1 or length(v)+1.
Example I = imread('ngc4024m.tif');
X = grayslice(I,16);
imshow(I)
figure, imshow(X,jet(16))
1
n
---
2
n
---
n 1
n
------------ - , , ,
grayslice
11-90
See Also gray2ind
histeq
11-91
11hist eq
Purpose Enhance cont r ast using hist ogr am equalizat ion
Syntax 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 t he cont r ast of images by t r ansfor ming t he values in an
int ensit y image, or t he values in t he color map of an indexed image, so t hat t he
hist ogr am of t he out put image appr oximat ely mat ches a specified hist ogr am.
J = histeq(I,hgram) t r ansfor ms t he int ensit y image I so t hat t he hist ogr am
of t he out put int ensit y image J wit h length(hgram) bins appr oximat ely
mat ches hgram. The vect or hgram should cont ain int eger count s for equally
spaced bins wit h int ensit y values fr om 0 t o 1.0. histeq aut omat ically scales
hgram so t hat sum(hgram) = prod(size(I)). The hist ogr am of J will bet t er
mat ch hgram when length(hgram) is much smaller t han t he number of discr et e
levels in I.
J = histeq(I,n) t r ansfor ms t he int ensit y image I, r et ur ning in J an int ensit y
image wit h n discr et e gr ay levels. A r oughly equal number of pixels is mapped
t o each of t he n levels in J, so t hat t he hist ogr am of J is appr oximat ely flat . (The
hist ogr am of J is flat t er when n is much smaller t han t he number of discr et e
levels in I.) The default value for n is 64.
[J,T] = histeq(I,...) r et ur ns t he gr ay scale t r ansfor mat ion t hat maps gr ay
levels in t he int ensit y image I t o gr ay levels in J.
newmap = histeq(X,map,hgram) t r ansfor ms t he color map associat ed wit h t he
indexed image X so t hat t he hist ogr am of t he gr ay component of t he indexed
image (X,newmap) appr oximat ely mat ches hgram. histeq r et ur ns t he
t r ansfor med color map in newmap. length(hgram) must be t he same as
size(map,1).
newmap = histeq(X,map) t r ansfor ms t he values in t he color map so t hat t he
hist ogr am of t he gr ay component of t he indexed image X is appr oximat ely flat .
It r et ur ns t he t r ansfor med color map in newmap.
histeq
11-92
[newmap,T] = histeq(X,...) r et ur ns t he gr ayscale t r ansfor mat ion T t hat
maps t he gr ay component of map t o t he gr ay component of newmap.
Class Support For synt axes t hat include an int ensit y image I as input , I can be of class uint8,
uint16, or double, and t he out put image J has t he same class as I. For
synt axes t hat include an indexed image X as input , X can be of class uint8 or
double; t he out put color map is always of class double. Also, t he opt ional out put
T (t he gr ay level t r ansfor m) is always of class double.
Examples Enhance t he cont r ast of an int ensit y image using hist ogr am equalizat ion.
I = imread('tire.tif');
J = histeq(I);
imshow(I)
figure, imshow(J)
histeq
11-93
Display t he r esult ing hist ogr ams.
imhist(I,64)
figure; imhist(J,64)
Algorithm When you supply a desir ed hist ogr am hgram, histeq chooses t he gr ayscale
t r ansfor mat ion T t o minimize
wher e c
0
is t he cumulat ive hist ogr am of A, c
1
is t he cumulat ive sum of hgram for
all int ensit ies k. This minimizat ion is subject t o t he const r aint s t hat T must be
monot onic and c
1
(T(a)) cannot over shoot c
0
(a) by mor e t han half t he dist ance
bet ween t he hist ogr am count s at a. histeq uses t his t r ansfor mat ion t o map t he
gr ay levels in X (or t he color map) t o t heir new values
If you do not specify hgram, histeq cr eat es a flat hgram,
hgram = ones(1,n)*prod(size(A))/n;
and t hen applies t he pr evious algor it hm.
See Also brighten, imadjust, imhist
c
1
T k ( ) ( ) c
0
k ( )
b T a ( ) =
hsv2rgb
11-94
11hsv2r gb
Purpose Conver t hue-sat ur at ion-value (HSV) values t o RGB color space
Syntax rgbmap = hsv2rgb(hsvmap)
RGB = hsv2rgb(HSV)
Description rgbmap = hsv2rgb(hsvmap) conver t s t he HSV values in hsvmap t o RGB color
space. hsvmap is an m-by-3 mat r ix t hat cont ains hue, sat ur at ion, and value
component s as it s t hr ee columns, and rgbmap is r et ur ned as an m-by-3 mat r ix
t hat r epr esent s t he same set of color s as r ed, gr een, and blue values. Bot h
rgbmap and hsvmap cont ain values in t he r ange 0 t o 1.0.
RGB = hsv2rgb(HSV) conver t s t he HSV image t o t he equivalent RGB image.
HSV is an m-by-n-by-3 image ar r ay whose t hr ee planes cont ain t he hue,
sat ur at ion, and value component s for t he image. RGB is r et ur ned as an
m-by-n-by-3 image ar r ay whose t hr ee planes cont ain t he r ed, gr een, and blue
component s for t he image.
Class Support The input ar r ay t o hsv2rgb must be of class double. The out put ar r ay is of class
double.
Remarks hsv2rgb is a funct ion in MATLAB.
See Also rgb2hsv, rgbplot
colormap in t he online MATLAB Funct ion Refer ence
idct2
11-95
11
11idct 2
Purpose Comput e t wo-dimensional inver se discr et e cosine t r ansfor m
Syntax B = idct2(A)
B = idct2(A,m,n)
B = idct2(A,[m n])
Description B = idct2(A) r et ur ns t he t wo-dimensional inver se discr et e cosine t r ansfor m
of A.
B = idct2(A,m,n) or B = idct2(A,[m n]) pads A wit h zer os t o size m-by-n
befor e t r ansfor ming. If [m n] < size(A), idct2 cr ops A befor e t r ansfor ming.
For any A, idct2(dct2(A)) equals A t o wit hin r oundoff er r or .
Class Support The input mat r ix A can be of class double or of any int eger class. The out put
mat r ix B is of class double.
Algorithm idct2 comput es t he t wo-dimensional inver se DCT using
See Also dct2, dctmtx, fft2, ifft2
References J ain, Anil K. Fundamentals of Digital Image Processing. Englewood Cliffs, NJ :
Pr ent ice Hall, 1989. pp. 150-153.
Pennebaker , William B., and J oan L. Mit chell. J PEG: S till Image Data
Compression S tandard. New Yor k: Van Nost r and Reinhold, 1993.
A
m n

p

q
B
p q
2m 1 + ( )p
2M
-------------------------------
2n 1 + ( )q
2N
-----------------------------,
0 m M 1
0 n N 1
cos cos
q 0 =
N 1

p 0 =
M 1

p
1 M, p 0 =
2 M , 1 p M 1
'

=
q
1 N , q 0 =
2 N , 1 q N 1
'

=
ifft2
11-96
11ifft 2
Purpose Comput e t wo-dimensional inver se fast Four ier t r ansfor m
Syntax B = ifft2(A)
B = ifft2(A,m,n)
Description B = ifft2(A) r et ur ns t he t wo-dimensional inver se fast Four ier t r ansfor m of
mat r ix A. If A is a vect or , B has t he same or ient at ion as A.
B = ifft(A,m,n) pads mat r ix A wit h zer os t o size m-by-n. If [m n] < size(A),
ifft2 cr ops A befor e t r ansfor ming.
For any A, ifft2(fft2(A)) equals A t o wit hin r oundoff er r or . If A is r eal,
ifft2(fft2(A)) may have small imaginar y par t s.
Class Support The input mat r ix A can be of class double or of any int eger class. The out put
mat r ix B is of class double.
Remarks ifft2 is a funct ion in MATLAB.
Algorithm The algor it hm for ifft2(A) is t he same as t he algor it hm for fft2(A), except
for a sign change and scale fact or s of [m,n] = size(A). Like fft2, t he execut ion
t ime is fast est when m and n ar e power s of 2 and slowest when t hey ar e lar ge
pr ime number s.
See Also fft2, fftshift, idct2
dftmtx, filter, freqz, specplot, spectrum in t he S ignal Processing Toolbox
Users Guide
fft, ifft in t he online MATLAB Funct ion Refer ence
ifftn
11-97
11ifft n
Purpose Comput e N-dimensional inver se fast Four ier t r ansfor m
Syntax B = ifftn(A)
B = ifftn(A,siz)
Description B = ifftn(A) per for ms t he N-dimensional inver se fast Four ier t r ansfor m. The
r esult B is t he same size as A.
B = ifftn(A,siz) pads A wit h zer os (or t r uncat es A) t o cr eat e an
N-dimensional ar r ay of size siz befor e doing t he inver se t r ansfor m.
For any A, ifftn(fftn(A)) equals A wit hin r oundoff er r or . If A is r eal,
ifftn(fftn(A)) may have small imaginar y par t s.
Class Support The input mat r ix A can be of class double or of any int eger class. The out put
mat r ix B is of class double.
Remarks ifftn is a funct ion in MATLAB.
Algorithm ifftn(A) is equivalent t o
B = A;
for p = 1:length(size(A))
B = ifft(B,[],p);
end
This code comput es t he one-dimensional inver se fast Four ier t r ansfor m along
each dimension of A. The t ime r equir ed t o comput e ifftn(A) depends most on
t he number of pr ime fact or s of t he dimensions of A. It is fast est when all of t he
dimensions ar e power s of 2.
See Also fft2, fftn, ifft2
im2bw
11-98
11im2bw
Purpose Conver t an image t o a binar y image, based on t hr eshold
Syntax BW = im2bw(I,level)
BW = im2bw(X,map,level)
BW = im2bw(RGB,level)
Description im2bw pr oduces binar y images fr om indexed, int ensit y, or RGB images. To do
t his, it conver t s t he input image t o gr ayscale for mat (if it is not alr eady an
int ensit y image), and t hen conver t s t his gr ayscale image t o binar y by
t hr esholding. The out put binar y image BW has values of 0 (black) for all pixels
in t he input image wit h luminance less t han level and 1 (whit e) for all ot her
pixels. (Not e t hat you specify level in t he r ange [0,1], r egar dless of t he class of
t he input image.)
BW = im2bw(I,level) conver t s t he int ensit y image I t o black and whit e.
BW = im2bw(X,map,level) conver t s t he indexed image X wit h color map map t o
black and whit e.
BW = im2bw(RGB,level) conver t s t he RGB image RGB t o black and whit e.
Class Support The input image can be of class uint8, uint16, or double. The out put image BW
is of class uint8.
Example load trees
BW = im2bw(X,map,0.4);
imshow(X,map)
figure, imshow(BW)
See Also ind2gray, rgb2gray
im2col
11-99
11im2col
Purpose Rear r ange image blocks int o columns
Syntax B = im2col(A,[m n],block_type)
B = im2col(A,[m n])
B = im2col(A,'indexed',...)
Description im2col r ear r anges image blocks int o columns. block_type is a st r ing t hat can
have one of t hese values:
'distinct' for m-by-n dist inct blocks
'sliding' for m-by-n sliding blocks (default )
B = im2col(A,[m n],'distinct') r ear r anges each dist inct m-by-n block in t he
image A int o a column of B. im2col pads A wit h zer os, if necessar y, so it s size is
an int eger mult iple of m-by-n. If A = [A11 A12;A21 A22], wher e each A
ij
is
m-by-n, t hen B = [A11(:) A12(:) A21(:) A22(:)].
B = im2col(A,[m n],'sliding') conver t s each sliding m-by-n block of A int o a
column of B, wit h no zer o padding. B has m*n r ows and will cont ain as many
columns as t her e ar e m-by-n neighbor hoods of A. If t he size of A is [mm nn], t hen
t he size of B is (m*n)-by-((mmm+1)*(nnn+1)).
B = im2col(A,[m n]) uses t he default block_type of 'sliding'.
For t he sliding block case, each column of B cont ains t he neighbor hoods of A
r eshaped as nhood(:) wher e nhood is a mat r ix cont aining an m-by-n
neighbor hood of A. im2col or der s t he columns of B so t hat t hey can be r eshaped
t o for m a mat r ix in t he nor mal way. For example, suppose you use a funct ion,
such as sum(B), t hat r et ur ns a scalar for each column of B. You can dir ect ly
st or e t he r esult in a mat r ix of size (mmm+1)-by-(nnn+1), using t hese calls:
B = im2col(A,[m n],'sliding');
C = reshape(sum(B),mmm+1,nnn+1);
B = im2col(A,'indexed',...) pr ocesses A as an indexed image, padding wit h
zer os if t he class of A is uint8, or ones if t he class of A is double.
Class Support The input image A can be of class double or of any int eger class. The out put
mat r ix B is of t he same class as t he input image.
See Also blkproc, col2im, colfilt, nlfilter
im2double
11-100
11im2double
Purpose Conver t image ar r ay t o double pr ecision
Syntax I2 = im2double(I1)
RGB2 = im2double(RGB1)
BW2 = im2double(BW1)
X2 = im2double(X1,'indexed')
Description im2double t akes an image as input , and r et ur ns an image of class double. If
t he input image is of class double, t he out put image is ident ical t o it . If t he
input image is of class uint8 or uint16, im2double r et ur ns t he equivalent
image of class double, r escaling or offset t ing t he dat a as necessar y.
I2 = im2double(I1) conver t s t he int ensit y image I1 t o double pr ecision,
r escaling t he dat a if necessar y.
RGB2 = im2double(RGB1) conver t s t he t r uecolor image RGB1 t o double
pr ecision, r escaling t he dat a if necessar y.
BW2 = im2double(BW1) conver t s t he binar y image BW1 t o double pr ecision.
X2 = im2double(X1,'indexed') conver t s t he indexed image X1 t o double
pr ecision, offset t ing t he dat a if necessar y.
See Also double, im2uint8, uint8
im2uint8
11-101
11im2uint 8
Purpose Conver t image ar r ay t o eight -bit unsigned int eger s
Syntax I2 = im2uint8(I1)
RGB2 = im2uint8(RGB1)
BW2 = im2uint8(BW1)
X2 = im2uint8(X1,'indexed')
Description im2uint8 t akes an image as input , and r et ur ns an image of class uint8. If t he
input image is of class uint8, t he out put image is ident ical t o it . If t he input
image is of class uint16 or double, im2uint8 r et ur ns t he equivalent image of
class uint8, r escaling or offset t ing t he dat a as necessar y.
I2 = im2uint8(I1) conver t s t he int ensit y image I1 t o uint8, r escaling t he
dat a if necessar y.
RGB2 = im2uint8(RGB1) conver t s t he t r uecolor image RGB1 t o uint8, r escaling
t he dat a if necessar y.
BW2 = im2uint8(BW1) conver t s t he binar y image BW1 t o uint8.
X2 = im2uint8(X1,'indexed') conver t s t he indexed image X1 t o uint8,
offset t ing t he dat a if necessar y. Not e t hat it is not always possible t o conver t
an indexed image t o uint8. If X1 is of class double, max(X1(:)) must be 256 or
less; if X1 is of class uint16, max(X1(:)) must be 255 or less. To conver t a
uint16 indexed image t o uint8 by r educing t he number of color s, use imapprox.
See Also im2uint16, double, im2double, uint8, imapprox, uint16
im2uint16
11-102
11im2uint 16
Purpose Conver t image ar r ay t o sixt een-bit unsigned int eger s
Syntax I2 = im2uint16(I1)
RGB2 = im2uint16(RGB1)
X2 = im2uint16(X1,'indexed')
Description im2uint16 t akes an image as input , and r et ur ns an image of class uint16. If
t he input image is of class uint16, t he out put image is ident ical t o it . If t he
input image is of class double or uint8, im2uint16 r et ur ns t he equivalent
image of class uint16, r escaling or offset t ing t he dat a as necessar y.
I2 = im2uint16(I1) conver t s t he int ensit y image I1 t o uint16, r escaling t he
dat a if necessar y.
RGB2 = im2uint16(RGB1) conver t s t he t r uecolor image RGB1 t o uint16,
r escaling t he dat a if necessar y.
X2 = im2uint16(X1,'indexed') conver t s t he indexed image X1 t o uint16,
offset t ing t he dat a if necessar y. Not e t hat it is not always possible t o conver t
an indexed image t o uint16. If X1 is of class double, max(X1(:)) must be 65536
or less.
Note: im2uint16 does not suppor t binar y images.
See Also im2uint8, double, im2double, uint8, uint16, imapprox
imadjust
11-103
11imadjust
Purpose Adjust image int ensit y values or color map
Syntax J = imadjust(I,[low high],[bottom top],gamma)
newmap = imadjust(map,[low high],[bottom top],gamma)
RGB2 = imadjust(RGB1,...)
Description J = imadjust(I,[low high],[bottom top],gamma) t r ansfor ms t he values in
t he int ensit y image I t o values in J by mapping values bet ween low and high
t o values bet ween bottom and top. Values below low and above high ar e
clipped; t hat is, values below low map t o bottom, and t hose above high map t o
top. You can use an empt y mat r ix ([]) for [low high] or for [bottom top] t o
specify t he default of [0 1]. gamma specifies t he shape of t he cur ve descr ibing t he
r elat ionship bet ween t he values in I and J. If gamma is less t han 1, t he mapping
is weight ed t owar d higher (br ight er ) out put values. If gamma is gr eat er t han 1,
t he mapping is weight ed t owar d lower (dar ker ) out put values. If you omit t he
ar gument , gamma default s t o 1 (linear mapping).
newmap = imadjust(map,[low high],[bottom top],gamma) t r ansfor ms t he
color map associat ed wit h an indexed image. If [low high] and [bottom top]
ar e bot h 2-by-3, and gamma is a 1-by-3 vect or , imadjust r escales t he r ed, gr een,
and blue component s separ at ely. The r escaled color map, newmap, is t he same
size as map.
RGB2 = imadjust(RGB1,...) per for ms t he adjust ment on each image plane
(r ed, gr een, and blue) of t he RGB image RGB1. As wit h t he color map
adjust ment , you can use differ ent par amet er values for each plane by
specifying [low high] and [bottom top] as 2-by-3 mat r ices, and gamma as a
1-by-3 vect or .
Class Support For synt ax t hat include an input image (r at her t han a color map), t he image can
be of class uint8, uint16, or double. The out put image is of t he same class as
t he input image. For synt ax t hat include a color map, t he input and out put
color maps ar e of class double.
Remarks If top < bottom, t he out put image is r ever sed (i.e., as in a negat ive).
imadjust
11-104
Example I = imread('pout.tif');
J = imadjust(I,[0.3 0.7],[]);
imshow(I)
figure, imshow(J)
See Also brighten, histeq
imapprox
11-105
11imappr ox
Purpose Appr oximat e indexed image by one wit h fewer color s
Syntax [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) appr oximat es t he color s in t he indexed
image X and associat ed color map map by using minimum var iance
quant izat ion. imapprox r et ur ns indexed image Y wit h color map newmap, which
has at most n color s.
[Y,newmap] = imapprox(X,map,tol) appr oximat es t he color s in X and map
t hr ough unifor m quant izat ion. newmap cont ains at most (floor(1/tol)+1)^3
color s. tol must be bet ween 0 and 1.0.
Y = imapprox(X,map,newmap) appr oximat es t he color s in map by using
color map mapping t o find t he color s in newmap t hat best mat ch t he color s in map.
Y = imapprox(...,dither_option) enables or disables dit her ing.
dither_option is a st r ing t hat can have one of t hese values:
'dither' dit her s, if necessar y, t o achieve bet t er color r esolut ion at t he
expense of spat ial r esolut ion (default ).
'nodither' maps each color in t he or iginal image t o t he closest color in t he
new map. No dit her ing is per for med.
Class Support The input image X can be of class uint8, uint16, or double. The out put image
Y is of class uint8 if t he lengt h of newmap is less t han or equal t o 256. If t he
lengt h of newmap is gr eat er t han 256, X is of class double.
Algorithm imapprox uses rgb2ind t o cr eat e a new color map t hat uses fewer color s.
See Also cmunique, dither, rgb2ind
imcontour
11-106
11imcont our
Purpose Cr eat e a cont our plot of image dat a
Syntax imcontour(I,n)
imcontour(I,v)
imcontour(x,y,...)
imcontour(...,LineSpec)
[C,h] = imcontour(...)
Description imcontour(I,n) dr aws a cont our plot of t he int ensit y image I, aut omat ically
set t ing up t he axes so t heir or ient at ion and aspect r at io mat ch t he image. n is
t he number of equally spaced cont our levels in t he plot ; if you omit t he
ar gument , t he number of levels and t he values of t he levels ar e chosen
aut omat ically.
imcontour(I,v) dr aws a cont our plot of I wit h cont our lines at t he dat a values
specified in vect or v. The number of cont our levels is equal t o length(v).
imcontour(x,y,...) uses t he vect or s x and y t o specify t he x- and y-axis limit s.
imcontour(...,LineSpec) dr aws t he cont our s using t he line t ype and color
specified by LineSpec. Mar ker symbols ar e ignor ed.
[C,h] = imcontour(...) r et ur ns t he cont our mat r ix C and a vect or of handles
t o t he object s in t he plot . (The object s ar e act ually pat ches, and t he lines ar e
t he edges of t he pat ches.) You can use t he clabel funct ion wit h t he cont our
mat r ix C t o add cont our labels t o t he plot .
Class Support The input image can be of class uint8, uint16, or double.
imcontour
11-107
Example I = imread('ic.tif');
imcontour(I,3)
See Also clabel, contour, LineSpec in t he online MATLAB Funct ion Refer ence
imcrop
11-108
11imcr op
Purpose Cr op an image
Syntax 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 cr ops an image t o a specified r ect angle. In t he synt axes below, imcrop
displays t he input image and wait s for you t o specify t he cr op r ect angle wit h
t he mouse.
I2 = imcrop(I)
X2 = imcrop(X,map)
RGB2 = imcrop(RGB)
If you omit t he input ar gument s, imcrop oper at es on t he image in t he cur r ent
axes.
To specify t he r ect angle:
For a single-but t on mouse, pr ess t he mouse but t on and dr ag t o define t he
cr op r ect angle. Finish by r eleasing t he mouse but t on.
For a 2- or 3-but t on mouse, pr ess t he left mouse but t on and dr ag t o define
t he cr op r ect angle. Finish by r eleasing t he mouse but t on.
If you hold down t he Shi ft key while dr agging, or if you pr ess t he r ight mouse
but t on on a 2- or 3-but t on mouse, imcrop const r ains t he bounding r ect angle t o
be a squar e.
When you r elease t he mouse but t on, imcrop r et ur ns t he cr opped image in t he
supplied out put ar gument . If you do not supply an out put ar gument , imcrop
displays t he out put image in a new figur e.
imcrop
11-109
You can also specify t he cr opping r ect angle nonint er act ively, using t hese
synt axes:
I2 = imcrop(I,rect)
X2 = imcrop(X,map,rect)
RGB2 = imcrop(RGB,rect)
rect is a 4-element vect or wit h t he for m [xmin ymin width height]; t hese
values ar e specified in spat ial coor dinat es.
To specify a nondefault spat ial coor dinat e syst em for t he input image, pr ecede
t he ot her input ar gument s wit h t wo 2-element vect or s specifying t he XData and
YData. For example,
[...] = imcrop(x,y,...)
If you supply addit ional out put ar gument s, imcrop r et ur ns infor mat ion about
t he select ed r ect angle and t he coor dinat e syst em of t he input image. For
example,
[A,rect] = imcrop(...)
[x,y,A,rect] = imcrop(...)
A is t he out put image. x and y ar e t he XData and YData of t he input image.
Class Support The input image A can be of class uint8, uint16, or double. The out put image
B is of t he same class as A. rect is always of class double.
Remarks Because rect is specified in t er ms of spat ial coor dinat es, t he width and height
element s of rect do not always cor r espond exact ly wit h t he size of t he out put
image. For example, suppose rect is [20 20 40 30], using t he default spat ial
coor dinat e syst em. The upper -left cor ner of t he specified r ect angle is t he cent er
of t he pixel (20,20) and t he lower -r ight cor ner is t he cent er of t he pixel (50,60).
The r esult ing out put image is 31-by-41, not 30-by-40, because t he out put image
includes all pixels in t he input image t hat ar e complet ely or partially enclosed
by t he r ect angle.
imcrop
11-110
Example I = imread('ic.tif');
I2 = imcrop(I,[60 40 100 90]);
imshow(I)
figure, imshow(I2)
See Also zoom
imfeature
11-111
11imfeat ur e
Purpose Comput e feat ur e measur ement s for image r egions
Syntax stats = imfeature(L,measurements)
stats = imfeature(L,measurements,n)
Description stats = imfeature(L,measurements) comput es a set of measur ement s for
each labeled r egion in t he label mat r ix L. Posit ive int eger element s of L
cor r espond t o differ ent r egions. For example, t he set of element s of L equal t o
1 cor r esponds t o r egion 1; t he set of element s of L equal t o 2 cor r esponds t o
r egion 2; and so on. stats is a st r uct ur e ar r ay of lengt h max(L(:)). The fields
of t he st r uct ur e ar r ay denot e differ ent measur ement s for each r egion, as
specified by measurements.
measurements can be a comma-separ at ed list of st r ings, a cell ar r ay cont aining
st r ings, t he single st r ing 'all', or t he single st r ing 'basic'. The set of valid
measur ement st r ings includes:
Measur ement st r ings ar e case insensit ive and can be abbr eviat ed.
If measurements is t he st r ing 'all', t hen all of t he above measur ement s ar e
comput ed. If measurements is not specified or if it is t he st r ing 'basic', t hen
t hese measur ement s ar e comput ed: 'Area', 'Centroid', and 'BoundingBox'.
stats = imfeature(L,measurements,n) specifies t he t ype of connect ivit y used
in comput ing t he 'FilledImage', 'FilledArea', and 'EulerNumber'
measur ement s. n can have a value of eit her 4 or 8, wher e 4 specifies
4-connect ed object s and 8 specifies 8-connect ed object s; if t he ar gument is
omit t ed, it default s t o 8.
'Area' 'Image' 'EulerNumber'
'Centroid' 'FilledImage' 'Extrema'
'BoundingBox' 'FilledArea' 'EquivDiameter'
'MajorAxisLength' 'ConvexHull' 'Solidity'
'MinorAxisLength' 'ConvexImage' 'Extent'
'Eccentricity' 'ConvexArea' 'PixelList'
'Orientation'
imfeature
11-112
Definitions 'Area' Scalar ; t he act ual number of pixels in t he r egion. (This value may
differ slight ly fr om t he value r et ur ned by bwarea, which weight s differ ent
pat t er ns of pixels differ ent ly.)
'Centroid' 1-by-2 vect or ; t he x- and y-coor dinat es of t he cent er of mass of t he
r egion.
'BoundingBox' 1-by-4 vect or ; t he smallest r ect angle t hat can cont ain t he
r egion. The for mat of t he vect or is [x y width height], wher e x and y ar e t he
x- and y-coor dinat es of t he upper -left cor ner of t he r ect angle, and width and
height ar e t he widt h and height of t he r ect angle. Not e t hat x and y ar e always
nonint eger values, because t hey ar e t he spat ial coor dinat es for t he upper -left
cor ner of a pixel in t he image; for example, if t his pixel is t he t hir d pixel in t he
fift h r ow of t he image, t hen x = 2.5 and y = 4.5.
This figur e illust r at es t he cent r oid and bounding box. The r egion consist s of t he
whit e pixels; t he gr een box is t he bounding box, and t he r ed dot is t he cent r oid.
'MajorAxisLength' Scalar ; t he lengt h (in pixels) of t he major axis of t he
ellipse t hat has t he same second-moment s as t he r egion.
'MinorAxisLength' Scalar ; t he lengt h (in pixels) of t he minor axis of t he
ellipse t hat has t he same second-moment s as t he r egion.
'Eccentricity' Scalar ; t he eccent r icit y of t he ellipse t hat has t he same
second-moment s as t he r egion. The eccent r icit y is t he r at io of t he dist ance
bet ween t he foci of t he ellipse and it s major axis lengt h. The value is bet ween
0 and 1. (0 and 1 ar e degener at e cases; an ellipse whose eccent r icit y is 0 is
act ually a cir cle, while an ellipse whose eccent r icit y is 1 is a line segment .)
'Orientation' Scalar ; t he angle (in degr ees) bet ween t he x-axis and t he
major axis of t he ellipse t hat has t he same second-moment s as t he r egion.
This figur e illust r at es t he axes and or ient at ion of t he ellipse. The left side of
t he figur e shows an image r egion and it s cor r esponding ellipse. The r ight side
imfeature
11-113
shows t he same ellipse, wit h feat ur es indicat ed gr aphically; t he solid blue lines
ar e t he axes, t he r ed dot s ar e t he foci, and t he or ient at ion is t he angle bet ween
t he hor izont al dot t ed line and t he major axis.
'Image' Binar y image (uint8) of t he same size as t he bounding box of t he
r egion; t he on pixels cor r espond t o t he r egion, and all ot her pixels ar e off.
'FilledImage' Binar y image (uint8) of t he same size as t he bounding box of
t he r egion; t he on pixels cor r espond t o t he r egion, wit h all holes filled in.
'FilledArea' Scalar ; t he number of on pixels in FilledImage.
This figur e illust r at es Image' and FilledImage'.
'ConvexHull' p-by-2 mat r ix; t he smallest convex polygon t hat can cont ain
t he r egion. Each r ow of t he mat r ix cont ains t he x- and y-coor dinat es of one
ver t ex of t he polygon.
'ConvexImage' Binar y image (uint8); t he convex hull, wit h all pixels wit hin
t he hull filled in (i.e., set t o on). (For pixels t hat t he boundar y of t he hull passes
Original image, containing a single region 'Image' 'FilledImage'
imfeature
11-114
t hr ough, imfeature uses t he same logic as roipoly t o det er mine whet her t he
pixel is inside or out side t he hull.) The image is t he size of t he bounding box of
t he r egion.
'ConvexArea' Scalar ; t he number of pixels in 'ConvexImage'.
'EulerNumber' Scalar ; equal t o t he number of object s in t he r egion minus t he
number of holes in t hose object s.
'Extrema' 8-by-2 mat r ix; t he ext r emal point s in t he r egion. Each r ow of t he
mat r ix cont ains t he x- and y-coor dinat es of one of t he point s; t he for mat of t he
vect or is [top-left top-right right-top right-bottom bottom-right
bottom-left left-bottom left-top].
This figur e illust r at es t he ext r ema of t wo differ ent r egions. In t he r egion on t he
left , each ext r emal point is dist inct ; in t he r egion on t he r ight , cer t ain ext r emal
point s (e.g., top-left and left-top) ar e ident ical.
'EquivDiameter' Scalar ; t he diamet er of a cir cle wit h t he same ar ea as t he
r egion. Comput ed as sqrt(4*Area/pi).
'Solidity' Scalar ; t he pr opor t ion of t he pixels in t he convex hull t hat ar e
also in t he r egion. Comput ed as Area/ConvexArea.
'Extent' Scalar ; t he pr opor t ion of t he pixels in t he bounding box t hat ar e
also in t he r egion. Comput ed as t he Area divided by ar ea of t he bounding box.
'PixelList' p-by-2 mat r ix; t he act ual pixels in t he r egion. Each r ow of t he
mat r ix cont ains t he x- and y-coor dinat es of one pixel in t he r egion.
Class Support The input label mat r ix L can be of class double or of any int eger class.
top-left
left-top
left-bottom
bottom-left
top-right
right-bottom
right-top
bottom-right
top-left
left-top
left-bottom
bottom-left
top-right
right-bottom
right-top
bottom-right
imfeature
11-115
Remarks The comma-separ at ed list synt ax for st r uct ur e ar r ays is ver y useful when
wor king wit h t he out put of imfeature. For example, for a field t hat cont ains a
scalar , you can use a t his synt ax t o cr eat e a vect or cont aining t he value of t his
field for each r egion in t he image.
For inst ance, if stats is a st r uct ur e ar r ay wit h field Area, t hen t hese t wo
expr essions ar e equivalent :
stats(1).Area, stats(2).Area, ..., stats(end).Area
and:
stats.Area
Ther efor e, you can use t hese calls t o cr eat e a vect or cont aining t he ar ea of each
r egion in t he image:
stats = imfeature(L,'Area');
allArea = [stats.Area];
allArea is a vect or of t he same lengt h as t he st r uct ur e ar r ay stats.
The funct ion ismember is useful in conjunct ion wit h imfeature for select ing
r egions based on cer t ain cr it er ia. For example, t hese commands cr eat e a binar y
image cont aining only t he r egions in text.tif whose ar ea is gr eat er t han 80:
idx = find([stats.Area] > 80);
BW2 = ismember(L,idx);
Most of t he measur ement s t ake ver y lit t le t ime t o comput e. The except ions ar e
t hese, which may t ake significant ly longer , depending on t he number of r egions
in L:
'ConvexHull'
'ConvexImage'
'ConvexArea'
'FilledImage'
Not e t hat comput ing cer t ain gr oups of measur ement s t akes about t he same
amount of t ime as comput ing just one of t hem, because imfeature t akes
advant age of int er mediat e comput at ions used in bot h comput at ions. Ther efor e,
it is fast est t o comput e all of t he desir ed measur ement s in a single call t o
imfeature.
imfeature
11-116
Example BW = imread('text.tif');
L = bwlabel(BW);
stats = imfeature(L,'all');
stats(23)
ans =
Area: 89
Centroid: [95.6742 192.9775]
BoundingBox: [87.5000 184.5000 16 15]
MajorAxisLength: 19.9127
MinorAxisLength: 14.2953
Eccentricity: 0.6961
Orientation: 9.0845
ConvexHull: [28x2 double]
ConvexImage: [15x16 uint8 ]
ConvexArea: 205
Image: [15x16 uint8 ]
FilledImage: [15x16 uint8 ]
FilledArea: 122
EulerNumber: 0
Extrema: [ 8x2 double]
EquivDiameter: 10.6451
Solidity: 0.4341
Extent: 0.3708
PixelList: [89x2 double]
See Also bwlabel
ismember in t he online MATLAB Funct ion Refer ence
imfinfo
11-117
11imfinfo
Purpose Ret ur n infor mat ion about a gr aphics file
Syntax info = imfinfo(filename,fmt)
info = imfinfo(filename)
Description info = imfinfo(filename,fmt) r et ur ns a st r uct ur e whose fields cont ain
infor mat ion about an image in a gr aphics file. filename is a st r ing t hat
specifies t he name of t he gr aphics file, and fmt is a st r ing t hat specifies t he
for mat of t he file. The file must be in t he cur r ent dir ect or y or in a dir ect or y on
t he MATLAB pat h. If imfinfo cannot find a file named filename, it looks for a
file named filename.fmt.
This t able list s t he possible values for fmt.
If filename is a TIFF or HDF file cont aining mor e t han one image, info is a
st r uct ur e ar r ay wit h one element (i.e., an individual st r uct ur e) for each image
in t he file. For example, info(3) would cont ain infor mat ion about t he t hir d
image in t he file.
Format File Type
'bmp' Windows Bit map (BMP)
'hdf' Hier ar chical Dat a For mat (HDF)
'jpg' or 'jpeg' J oint Phot ogr aphic Exper t s Gr oup (J PEG)
'pcx' Windows Paint br ush (PCX)
png Por t able Net wor k Gr aphics (PNG)
'tif' or 'tiff' Tagged Image File For mat (TIFF)
'xwd' X Windows Dump (XWD)
imfinfo
11-118
The set of fields in info depends on t he individual file and it s for mat . However ,
t he fir st nine fields ar e always t he same. This t able list s t hese fields and
descr ibes t heir values.
info = imfinfo(filename) at t empt s t o infer t he for mat of t he file fr om it s
cont ent s.
Remarks imfinfo is a funct ion in MATLAB.
Field Value
Filename A st r ing cont aining t he name of t he file; if t he file is
not in t he cur r ent dir ect or y, t he st r ing cont ains t he
full pat hname of t he file
FileModDate A st r ing cont aining t he dat e when t he file was last
modified
FileSize An int eger indicat ing t he size of t he file in byt es
Format A st r ing cont aining t he file for mat , as specified by fmt;
for J PEG and TIFF files, t he t hr ee-let t er var iant is
r et ur ned
FormatVersion A st r ing or number descr ibing t he ver sion of t he
for mat
Width An int eger indicat ing t he widt h of t he image in pixels
Height An int eger indicat ing t he height of t he image in pixels
BitDepth An int eger indicat ing t he number of bit s per pixel
ColorType A st r ing indicat ing t he t ype of image; eit her
'truecolor' for a t r uecolor RGB image, 'grayscale'
for a gr ayscale int ensit y image, or 'indexed' for an
indexed image
imfinfo
11-119
Example info = imfinfo('canoe.tif')
info =
Filename:'canoe.tif'
FileModDate: '25-Oct-1996 22:10:39'
FileSize: 69708
Format: 'tif'
FormatVersion: []
Width: 346
Height: 207
BitDepth: 8
ColorType: 'indexed'
FormatSignature: [73 73 42 0]
ByteOrder: 'little-endian'
NewSubfileType: 0
BitsPerSample: 8
Compression: 'PackBits'
PhotometricInterpretation: 'RGB Palette'
StripOffsets: [ 9x1 double]
SamplesPerPixel: 1
RowsPerStrip: 23
StripByteCounts: [ 9x1 double]
XResolution: 72
YResolution: 72
ResolutionUnit: 'Inch'
Colormap: [256x3 double]
PlanarConfiguration: 'Chunky'
TileWidth: []
TileLength: []
TileOffsets: []
TileByteCounts: []
Orientation: 1
FillOrder: 1
GrayResponseUnit: 0.0100
MaxSampleValue: 255
MinSampleValue: 0
Thresholding: 1
See Also imread, imwrite
imhist
11-120
11imhist
Purpose Display a hist ogr am of image dat a
Syntax imhist(I,n)
imhist(X,map)
[counts,x] = imhist(...)
Description imhist(I,n) displays a hist ogr am wit h n bins for t he int ensit y image I above
a gr ayscale color bar of lengt h n. If you omit t he ar gument , imhist uses a
default value of n = 256 if I is a gr ayscale image, or n = 2 if I is a binar y image.
imhist(X,map) displays a hist ogr am for t he indexed image X. This hist ogr am
shows t he dist r ibut ion of pixel values above a color bar of t he color map map. The
color map must be at least as long as t he lar gest index in X. The hist ogr am has
one bin for each ent r y in t he color map.
[counts,x] = imhist(...) r et ur ns t he hist ogr am count s in counts and t he
bin locat ions in x so t hat stem(x,counts) shows t he hist ogr am. For indexed
images, it r et ur ns t he hist ogr am count s for each color map ent r y; t he lengt h of
counts is t he same as t he lengt h of t he color map.
Class Support The input image can be of class uint8, uint16, or double.
Example I = imread('pout.tif');
imhist(I)
See Also histeq
hist in t he online MATLAB Funct ion Refer ence
immovie
11-121
11immovie
Purpose Make a movie of a mult ifr ame indexed image
Syntax mov = immovie(X,map)
Description mov = immovie(X,map) r et ur ns t he movie mat r ix mov fr om t he images in t he
mult ifr ame indexed image X. As it cr eat es t he movie mat r ix, it displays t he
movie fr ames on t he scr een. You can play t he movie using t he MATLAB movie
funct ion.
X compr ises mult iple indexed images, all having t he same size and all using t he
color map map. X is an m-by-n-by-1-by-k ar r ay, wher e k is t he number of images.
Class Support X can be of class uint8, uint16, or double. mov is of class double.
Example load mri
mov = immovie(D,map);
See Also montage
getframe, movie in t he online MATLAB Funct ion Refer ence
imnoise
11-122
11imnoise
Purpose Add noise t o an image
Syntax J = imnoise(I,type)
J = imnoise(I,type,parameters)
Description J = imnoise(I,type) adds noise of t ype t o t he int ensit y image I. type is a
st r ing t hat can have one of t hese values:
'gaussian' for Gaussian whit e noise
'salt & pepper' for on and off pixels
'speckle' for mult iplicat ive noise
J = imnoise(I,type,parameters) accept s an algor it hm t ype plus addit ional
modifying par amet er s par t icular t o t he t ype of algor it hm chosen. If you omit
t hese ar gument s, imnoise uses default values for t he par amet er s. Her e ar e
examples of t he differ ent noise t ypes and t heir par amet er s:
J = imnoise(I,'gaussian',m,v) adds Gaussian whit e noise of mean m and
var iance v t o t he image I. The default is zer o mean noise wit h 0.01 var iance.
J = imnoise(I,'salt & pepper',d) adds salt and pepper noise t o t he image
I, wher e d is t he noise densit y. This affect s appr oximat ely d*prod(size(I))
pixels. The default is 0.05 noise densit y.
J = imnoise(I,'speckle',v) adds mult iplicat ive noise t o t he image I, using
t he equat ion J = I + n*I, wher e n is unifor mly dist r ibut ed r andom noise wit h
mean 0 and var iance v. The default for v is 0.04.
Class Support The input image I can be of class uint8, uint16, or double. The out put image
J is of t he same class as I.
imnoise
11-123
Example I = imread('eight.tif');
J = imnoise(I,'salt & pepper',0.02);
imshow(I)
figure, imshow(J)
See Also rand, randn in t he online MATLAB Funct ion Refer ence
impixel
11-124
11impixel
Purpose Det er mine pixel color values
Syntax 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 r et ur ns t he r ed, gr een, and blue color values of specified image pixels.
In t he synt axes below, impixel displays t he input image and wait s for you t o
specify t he pixels wit h t he mouse.
P = impixel(I)
P = impixel(X,map)
P = impixel(RGB)
If you omit t he input ar gument s, impixel oper at es on t he image in t he cur r ent
axes.
Use nor mal but t on clicks t o select pixels. Pr ess Backs pace or De le te t o
r emove t he pr eviously select ed pixel. A shift -click, r ight -click, or double-click
adds a final pixel and ends t he select ion; pr essing Return finishes t he
select ion wit hout adding a pixel.
When you finish select ing pixels, impixel r et ur ns an m-by-3 mat r ix of RGB
values in t he supplied out put ar gument . If you do not supply an out put
ar gument , impixel r et ur ns t he mat r ix in ans.
You can also specify t he pixels nonint er act ively, using t hese synt axes:
P = impixel(I,c,r)
P = impixel(X,map,c,r)
P = impixel(RGB,c,r)
impixel
11-125
r and c ar e equal-lengt h vect or s specifying t he coor dinat es of t he pixels whose
RGB values ar e r et ur ned in P. The k
t h
r ow of P cont ains t he RGB values for t he
pixel (r(k),c(k)).
If you supply t hr ee out put ar gument s, impixel r et ur ns t he coor dinat es of t he
select ed pixels. For example,
[c,r,P] = impixel(...)
To specify a nondefault spat ial coor dinat e syst em for t he input image, use
t hese synt axes:
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 ar e 2-element vect or s specifying t he image XData and YData. xi and yi
ar e equal-lengt h vect or s specifying t he spat ial coor dinat es of t he pixels whose
RGB values ar e r et ur ned in P. If you supply t hr ee out put ar gument s, impixel
r et ur ns t he coor dinat es of t he select ed pixels.
[xi,yi,P] = impixel(x,y,...)
Class Support The input image can be of class uint8, uint16, or double. All ot her input s and
out put s ar e of class double.
Remarks impixel wor ks wit h indexed, int ensit y, and RGB images. impixel always
r et ur ns pixel values as RGB t r iplet s, r egar dless of t he image t ype.
For an RGB image, impixel r et ur ns t he act ual dat a for t he pixel. The values
ar e eit her uint8 int eger s or double float ing-point number s, depending on
t he class of t he image ar r ay.
For an indexed image, impixel r et ur ns t he RGB t r iplet st or ed in t he r ow of
t he color map t hat t he pixel value point s t o. The values ar e double
float ing-point number s.
For an int ensit y image, impixel r et ur ns t he int ensit y value as an RGB
t r iplet , wher e R=G=B. The values ar e eit her uint8 int eger s or double
float ing-point number s, depending on t he class of t he image ar r ay.
impixel
11-126
Example RGB = imread('flowers.tif');
c = [12 146 410];
r = [104 156 129];
pixels = impixel(RGB,c,r)
pixels =
61 59 101
253 240 0
237 37 44
See Also improfile, pixval
improfile
11-127
11impr ofile
Purpose Comput e pixel-value cr oss-sect ions along line segment s
Syntax 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 comput es t he int ensit y values along a line or a mult iline pat h in an
image. improfile select s equally spaced point s along t he pat h you specify, and
t hen uses int er polat ion t o find t he int ensit y value for each point . improfile
wor ks wit h gr ayscale int ensit y images and RGB images.
If you call improfile wit h one of t hese synt axes, it oper at es int er act ively on
t he image in t he cur r ent axes:
c = improfile
c = improfile(n)
n specifies t he number of point s t o comput e t he int ensit y value for . If you do not
pr ovide t his ar gument , improfile chooses a value for n, r oughly equal t o t he
number of pixels t he pat h t r aver ses.
You specify t he line or pat h using t he mouse, by clicking on point s in t he image.
Pr ess Backspace or Delet e t o r emove t he pr eviously select ed point . A
shift -click, r ight -click, or double-click adds a final point and ends t he select ion;
pr essing Re t urn finishes t he select ion wit hout adding a point . When you
finish select ing point s, improfile r et ur ns t he int er polat ed dat a values in c. c
is an n-by-1 vect or if t he input is a gr ayscale int ensit y image, or an n-by-1-by-3
ar r ay if t he input is an RGB image.
improfile
11-128
If you omit t he out put ar gument , improfile displays a plot of t he comput ed
int ensit y values. If t he specified pat h consist s of a single line segment ,
improfile cr eat es a t wo-dimensional plot of int ensit y values ver sus t he
dist ance along t he line segment ; if t he pat h consist s of t wo or mor e line
segment s, improfile cr eat es a t hr ee-dimensional plot of t he int ensit y values
ver sus t heir x- and y-coor dinat es.
You can also specify t he pat h nonint er act ively, using t hese synt axes:
c = improfile(I,xi,yi)
c = improfile(I,xi,yi,n)
xi and yi ar e equal-lengt h vect or s specifying t he spat ial coor dinat es of t he
endpoint s of t he line segment s.
You can use t hese synt axes t o r et ur n addit ional infor mat ion:
[cx,cy,c] = improfile(...)
[cx,cy,c,xi,yi] = improfile(...)
cx and cy ar e vect or s of lengt h n, cont aining t he spat ial coor dinat es of t he
point s at which t he int ensit y values ar e comput ed.
To specify a nondefault spat ial coor dinat e syst em for t he input image, use
t hese synt axes:
[...] = improfile(x,y,I,xi,yi)
[...] = improfile(x,y,I,xi,yi,n)
x and y ar e 2-element vect or s specifying t he image XData and YData.
[...] = improfile(...,method) uses t he specified int er polat ion met hod.
method is a st r ing t hat can have one of t hese values:
'nearest' (default ) uses near est neighbor int er polat ion.
'bilinear' uses bilinear int er polat ion.
'bicubic' uses bicubic int er polat ion.
If you omit t he method ar gument , improfile uses t he default met hod of
'nearest'.
Class Support The input image can be of class uint8, uint16, or double. All ot her input s and
out put s ar e of class double.
improfile
11-129
Example I = imread('alumgrns.tif');
x = [35 338 346 103];
y = [253 250 17 148];
improfile(I,x,y), grid on
See Also impixel, pixval
interp2 in t he online MATLAB Funct ion Refer ence
imread
11-130
11imr ead
Purpose Read images fr om gr aphics files
Syntax A = imread(filename,fmt)
[X,map] = imread(filename,fmt)
[...] = imread(filename)
[...] = imread(...,idx) (TIFF only)
[...] = imread(...,ref) (HDF only)
[...] = imread(...,BackgroundColor,BG) (PNG only)
[A,map,alpha] = imread(...) (PNG only)
Description A = imread(filename,fmt) r eads a gr ayscale or t r uecolor image named
filename int o A. If t he file cont ains a gr ayscale int ensit y image, A is a
t wo-dimensional ar r ay. If t he file cont ains a t r uecolor (RGB) image, A is a
t hr ee-dimensional (m-by-n-by-3) ar r ay.
[X,map] = imread(filename,fmt) r eads t he indexed image in filename int o
X and it s associat ed color map int o map. The color map values ar e r escaled t o t he
r ange [0,1]. A and map ar e t wo-dimensional ar r ays.
[...] = imread(filename) at t empt s t o infer t he for mat of t he file fr om it s
cont ent .
filename is a st r ing t hat specifies t he name of t he gr aphics file, and fmt is a
st r ing t hat specifies t he for mat of t he file. If t he file is not in t he cur r ent
dir ect or y or in a dir ect or y in t he MATLAB pat h, specify t he full pat hname for
a locat ion on your syst em. If imread cannot find a file named filename, it looks
for a file named filename.fmt. If you do not specify a st r ing for fmt, t he t oolbox
will t r y t o discer n t he for mat of t he file by checking t he file header .
imread
11-131
This t able list s t he possible values for fmt.
Special Case
Syntax:
TIFF-Specific Synt ax
[...] = imread(...,idx) r eads in one image fr om a mult i-image TIFF file.
idx is an int eger value t hat specifies t he or der in which t he image appear s in
t he file. For example, if idx is 3, imread r eads t he t hir d image in t he file. If you
omit t his ar gument , imread r eads t he fir st image in t he file. To r ead all ages of
a TIFF file, omit t he idx ar gument .
PNG-Specific Synt ax
The discussion in t his sect ion is only r elevant t o PNG files t hat cont ain
t r anspar ent pixels. A PNG file does not necessar ily cont ain t r anspar ency dat a.
Tr anspar ent pixels, when t hey exist , will be ident ified by one of t wo
component s: a transparency chunk or an alpha channel. (A PNG file can only
have one of t hese component s, not bot h.)
The t r anspar ency chunk ident ifies which pixel values will be t r eat ed as
t r anspar ent , e.g., if t he value in t he t r anspar ency chunk of an 8-bit image is
0.5020, all pixels in t he image wit h t he color 0.5020 can be displayed as
t r anspar ent . An alpha channel is an ar r ay wit h t he same number of pixels as
ar e in t he image, which indicat es t he t r anspar ency st at us of each
cor r esponding pixel in t he image (t r anspar ent or nont r anspar ent ).
Format File type
'bmp' Windows Bit map (BMP)
'hdf' Hier ar chical Dat a For mat (HDF)
'jpg' or 'jpeg' J oint Phot ogr aphic Exper t s Gr oup (J PEG)
'pcx' Windows Paint br ush (PCX)
png Por t able Net wor k Gr aphics (PNG)
'tif' or 'tiff' Tagged Image File For mat (TIFF)
'xwd' X Windows Dump (XWD)
imread
11-132
Anot her pot ent ial PNG component r elat ed t o t r anspar ency is t he background
color chunk, which (if pr esent ) defines a color value t hat can be used behind all
t r anspar ent pixels. This sect ion ident ifies t he default behavior of t he t oolbox
for r eading PNG images t hat cont ain eit her a t r anspar ency chunk or an alpha
channel, and descr ibes how you can over r ide it .
Case 1. You do not ask t o out put t he alpha channel and do not specify a
backgr ound color t o use. For example,
[a,map] = imread(filename);
a = imread(filename);
If t he PNG file cont ains a backgr ound color chunk, t he t r anspar ent pixels will
be composit ed against t he specified backgr ound color .
If t he PNG file does not cont ain a backgr ound color chunk, t he t r anspar ent
pixels will be composit ed against 0 for gr ayscale (black), 1 for indexed (fir st
color in map), or [0 0 0] for RGB (black).
Case 2. You do not ask t o out put t he alpha channel but you specify t he
backgr ound color par amet er in your call. For example,
[...] = imread(...,'BackgroundColor',bg);
The t r anspar ent pixels will be composit ed against t he specified color . The for m
of bg depends on whet her t he file cont ains an indexed, int ensit y (gr ayscale), or
RGB image. If t he input image is indexed, bg should be an int eger in t he r ange
[1,P] wher e P is t he color map lengt h. If t he input image is int ensit y, bg should
be an int eger in t he r ange [0,1]. If t he input image is RGB, bg should be a
3-element vect or whose values ar e in t he r ange [0,1].
Ther e is one except ion t o t he t oolboxs behavior of using your backgr ound color .
If you set backgr ound t o 'none' no composit ing will be per for med. For
example,
[...] = imread(...,'Back','none');
Note: If you specify a backgr ound color, you cannot out put t he alpha channel.
imread
11-133
Case 3. You ask t o get t he alpha channel as an out put var iable. For example,
[a,map,alpha] = imread(filename);
[a,map,alpha] = imread(filename,fmt);
No composit ing is per for med; t he alpha channel will be st or ed separ at ely fr om
t he image (not mer ged int o t he image as in cases 1 and 2). This for m of imread
r et ur ns t he alpha channel if one is pr esent , and also r et ur ns t he image and any
associat ed color map. If t her e is no alpha channel, alpha r et ur ns []. If t her e is
no color map, or t he image is gr ayscale or t r uecolor , map may be empt y.
HDF-Specific Synt ax
[...] = imread(...,ref) r eads in one image fr om a mult i-image HDF file.
ref is an int eger value t hat specifies t he r efer ence number used t o ident ify t he
image. For example, if ref is 12, imread r eads t he image whose r efer ence
number is 12. (Not e t hat in an HDF file t he r efer ence number s do not
necessar ily cor r espond t o t he or der of t he images in t he file. You can use
imfinfo t o mat ch up image or der wit h r efer ence number .) If you omit t his
ar gument , imread r eads t he fir st image in t he file.
imread
11-134
This t able summar izes t he t ypes of images t hat imread can r ead.
Class Support In most of t he image file for mat s suppor t ed by imread, pixels ar e st or ed using
eight or fewer bit s per color plane. When r eading such a file, t he class of t he
out put (A or X) is uint8. imread also suppor t s r eading 16-bit -per -pixel dat a
fr om TIFF and PNG files; for such image files, t he class of t he out put (A or X) is
uint16. Not e t hat for indexed images, imread always r eads t he color map int o
an ar r ay of class double, even t hough t he image ar r ay it self may be of class
uint8 or uint16.
Remarks imread is a funct ion in MATLAB.
Examples This example r eads t he sixt h image in a TIFF file:
[X,map] = imread('flowers.tif',6);
Format Variants
BMP 1-bit , 4-bit , 8-bit , and 24-bit uncompr essed images; 4-bit
and 8-bit r un-lengt h encoded (RLE) images
HDF 8-bit r ast er image dat aset s, wit h or wit hout associat ed
color map; 24-bit r ast er image dat aset s
J PEG Any baseline J PEG image (8 or 24-bit ); J PEG images wit h
some commonly used ext ensions
PCX 1-bit , 8-bit , and 24-bit images
PNG Any PNG image, including 1-bit , 2-bit , 4-bit , 8-bit , and
16-bit gr ayscale images; 8-bit and 16-bit indexed images;
24-bit and 48-bit RGB images
TIFF Any baseline TIFF image, including 1-bit , 8-bit , and 24-bit
uncompr essed images; 1-bit , 8-bit , 16-bit , and 24-bit images
wit h packbit s compr ession; 1-bit images wit h CCITT
compr ession; also 16-bit gr ayscale, 16-bit indexed, and
48-bit RGB images.
XWD 1-bit and 8-bit ZPixmaps; XYBit maps; 1-bit XYPixmaps
imread
11-135
This example r eads t he four t h image in an HDF file.
info = imfinfo('skull.hdf');
[X,map] = imread('skull.hdf',info(4).Reference);
This example r eads a 24-bit PNG image and set s any of it s fully t r anspar ent
(alpha channel) pixels t o r ed.
bg = [255 0 0];
A = imread('image.png','BackgroundColor',bg);
This example r et ur ns t he alpha channel (if any) of a PNG image.
[A,map,alpha] = imread('image.png');
See Also imfinfo, imwrite,fread,double,uint8,uint16
See fread in t he online MATLAB Funct ion Refer ence
imresize
11-136
11imr esize
Purpose Resize an image
Syntax B = imresize(A,m,method)
B = imresize(A,[mrows ncols],method)
B = imresize(...,method,n)
B = imresize(...,method,h)
Description imresize r esizes an image of any t ype using t he specified int er polat ion
met hod. method is a st r ing t hat can have one of t hese values:
'nearest' (default ) uses near est neighbor int er polat ion.
'bilinear' uses bilinear int er polat ion.
'bicubic' uses bicubic int er polat ion.
If you omit t he method ar gument , imresize uses t he default met hod of
'nearest'.
B = imresize(A,m,method) r et ur ns an image t hat is m t imes t he size of A. If m
is bet ween 0 and 1.0, B is smaller t han A. If m is gr eat er t han 1.0, B is lar ger t han
A.
B = imresize(A,[mrows ncols],method) r et ur ns an image of size
[mrows ncols]. If t he specified size does not pr oduce t he same aspect r at io
as t he input image has, t he out put image is dist or t ed.
When t he specified out put size is smaller t han t he size of t he input image, and
method is 'bilinear' or 'bicubic', imresize applies a lowpass filt er befor e
int er polat ion t o r educe aliasing. The default filt er size is 11-by-11.
You can specify a differ ent or der for t he default filt er using:
[...] = imresize(...,method,n)
n is an int eger scalar specifying t he size of t he filt er , which is n-by-n. If n is 0
(zer o), imresize omit s t he filt er ing st ep.
You can also specify your own filt er h using:
[...] = imresize(...,method,h)
h is any t wo-dimensional FIR filt er (such as t hose r et ur ned by ftrans2, fwind1,
fwind2, or fsamp2).
imresize
11-137
Class Support The input image can be of class uint8, uint16, or double. The out put image is
of t he same class as t he input image.
See Also interp2 in t he online MATLAB Funct ion Refer ence
imrotate
11-138
11imr ot at e
Purpose Rot at e an image
Syntax B = imrotate(A,angle,method)
B = imrotate(A,angle,method,'crop')
Description B = imrotate(A,angle,method) r ot at es t he image A by angle degr ees in a
count er -clockwise dir ect ion, using t he specified int er polat ion met hod. method
is a st r ing t hat can have one of t hese values:
'nearest' (default ) uses near est neighbor int er polat ion.
'bilinear' uses bilinear int er polat ion.
'bicubic' uses bicubic int er polat ion.
If you omit t he method ar gument , imrotate uses t he default met hod of
'nearest'.
The r et ur ned image mat r ix B is, in gener al, lar ger t han A t o include t he whole
r ot at ed image. imrotate set s invalid values on t he per ipher y of B t o 0.
B = imrotate(A,angle,method,'crop') r ot at es t he image A t hr ough angle
degr ees and r et ur ns t he cent r al por t ion which is t he same size as A.
Class Support The input image can be of class uint8, uint16, or double. The out put image is
of t he same class as t he input image.
Remarks To r ot at e t he image clockwise, specify a negat ive angle.
imrotate
11-139
Example I = imread('ic.tif');
J = imrotate(I,4,'bilinear','crop');
imshow(I)
figure, imshow(J)
See Also imcrop, imresize
imshow
11-140
11imshow
Purpose Display an image
Syntax 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 t he int ensit y image I wit h n discr et e levels of gr ay. If you
omit n, imshow uses 256 gr ay levels on 24-bit displays, or 64 gr ay levels on ot her
syst ems.
imshow(I,[low high]) displays I as a gr ayscale int ensit y image, specifying
t he dat a r ange for I. The value low (and any value less t han low) displays as
black, t he value high (and any value gr eat er t han high) displays as whit e, and
values in bet ween display as int er mediat e shades of gr ay. imshow uses t he
default number of gr ay levels. If you use an empt y mat r ix ([]) for [low high],
imshow uses [min(I(:)) max(I(:))]; t he minimum value in I displays as
black, and t he maximum value displays as whit e.
imshow(BW) displays t he binar y image BW. Values of 0 display as black, and
values of 1 display as whit e.
imshow(X,map) displays t he indexed image X wit h t he color map map.
imshow(RGB) displays t he t r uecolor image RGB.
imshow(...,display_option) displays t he image, calling truesize if
display_option is 'truesize', or suppr essing t he call t o truesize if
display_option is 'notruesize'. Eit her opt ion st r ing can be abbr eviat ed. If
you do not supply t his ar gument , imshow det er mines whet her t o call truesize
based on t he set t ing of t he 'ImshowTruesize' pr efer ence.
imshow(x,y,A,...) uses t he 2-element vect or s x and y t o est ablish a
nondefault spat ial coor dinat e syst em, by specifying t he image XData and
YData.
imshow
11-141
imshow filename displays t he image st or ed in t he gr aphics file filename.
imshow calls imread t o r ead t he image fr om t he file, but t he image dat a is not
st or ed in t he MATLAB wor kspace. The file must be in t he cur r ent dir ect or y or
on t he MATLAB pat h.
h = imshow(...) r et ur ns t he handle t o t he image object cr eat ed by imshow.
Class Support The input image can be of class uint8, uint16, or double.
Remarks You can use t he iptsetpref funct ion t o set sever al t oolbox pr efer ences t hat
modify t he behavior of imshow. For example,
'ImshowBorder' cont r ols whet her imshow displays t he image wit h a bor der
ar ound it .
'ImshowAxesVisible' cont r ols whet her imshow displays t he image wit h t he
axes box and t ick labels.
'ImshowTruesize' cont r ols whet her imshow calls t he truesize funct ion.
Not e t hat t he display_option ar gument t o imshow enables you t o over r ide t he
'ImshowTruesize' pr efer ence.
For mor e infor mat ion about t hese pr efer ences, see t he r efer ence ent r y for
iptsetpref.
See Also getimage, imread, iptgetpref, iptsetpref, subimage, truesize, warp
image, imagesc in t he online MATLAB Funct ion Refer ence
imwrite
11-142
11imwr it e
Purpose Wr it e an image t o a gr aphics file
Syntax imwrite(A,filename,fmt)
imwrite(X,map,filename,fmt)
imwrite(...,filename)
imwrite(...,Param1,Val1,Param2,Val2...)
Description imwrite(A,filename,fmt) wr it es t he image in A t o filename. A can be eit her
a gr ayscale image (M-by-N) or a t r uecolor image (M-by-N-by-3). If A is of class
uint8 or uint16, imwrite wr it es t he act ual values in t he ar r ay t o t he file. If A
is of class double, imwrite r escales t he values in t he ar r ay befor e wr it ing,
using uint8(round(255*A)). This oper at ion conver t s t he float ing-point
number s in t he r ange [0,1] t o 8-bit int eger s in t he r ange [0,255].
imwrite(X,map,filename,fmt) wr it es t he indexed image in X and it s
associat ed color map map t o filename. If X is of class uint8 or uint16, imwrite
wr it es t he act ual values in t he ar r ay t o t he file. If X is of class double, imwrite
offset s t he values in t he ar r ay befor e wr it ing using uint8(X1). (See not e below
for an except ion.) map must be a valid MATLAB color map of class double;
imwrite r escales t he values in map using uint8(round(255*map)). Not e t hat
most image file for mat s do not suppor t color maps wit h mor e t han 256 ent r ies.
Note: If t he image is double, and you specify PNG as t he out put for mat and a
bit dept h of 16 bpp, t he values in t he ar r ay will be offset using uint16(X-1).
imwrite(...,filename) wr it es t he image t o filename, infer r ing t he for mat t o
use fr om t he filenames ext ension. The ext ension must be one of t he legal
values for fmt.
imwrite(...,Param1,Val1,Param2,Val2...) specifies par amet er s t hat
cont r ol var ious char act er ist ics of t he out put file. Par amet er set t ings can
cur r ent ly be made for HDF, J PEG, and TIFF files. For example, if you ar e
wr it ing a J PEG file, you can set t he qualit y of t he J PEG compr ession. For t he
full list of par amet er s available per for mat , see t he t ables of par amet er s.
filename is a st r ing t hat specifies t he name of t he out put file, and fmt is a
st r ing t hat specifies t he for mat of t he file.
imwrite
11-143
This t able list s t he possible values for fmt.
This t able descr ibes t he available par amet er s for HDF files.
Format File Type
'bmp' Windows Bit map (BMP)
'hdf' Hier ar chical Dat a For mat (HDF)
'jpg' or 'jpeg' J oint Phot ogr aphic Exper t s Gr oup (J PEG)
'pcx' Windows Paint br ush (PCX)
'png' Por t able Net wor k Gr aphics (PNG)
'tif' or 'tiff' Tagged Image File For mat (TIFF)
'xwd' X Windows Dump (XWD)
Parameter Values Default
'Compression' One of t hese st r ings: 'none' (t he default ), 'rle',
'jpeg'. 'rle' is valid only for gr ayscale and
indexed images. 'jpeg' is valid only for gr ayscale
and RGB images.
'rle'
'Quality' A number bet ween 0 and 100; t his par amet er
applies only if 'Compression' is 'jpeg'.
A number bet ween 0 and 100; higher number s
mean higher quality (less image degr adat ion due t o
compr ession), but t he r esult ing file size is lar ger.
75
'WriteMode' One of t hese st r ings: 'overwrite' (t he default ), or
'append'.
'overwrite'
imwrite
11-144
This t able descr ibes t he available par amet er s for J PEG files.
This t able descr ibes t he available par amet er s for TIFF files.
This t able descr ibes t he available par amet er s for PNG files.
Parameter Values Default
'Quality' A number bet ween 0 and 100; higher number s
mean higher quality (less image degr adat ion due t o
compr ession), but t he r esult ing file size is lar ger.
75
Parameter Values Default
'Compression' One of t hese st r ings: 'none', 'packbits', 'ccitt'.
'ccitt' is valid for binar y images only. 'packbits'
is t he default for nonbinar y images; 'ccitt' is t he
default for binar y images.
'ccitt' for
binar y images;
'packbits'for all
ot her images
'Description' Any st r ing; fills in t he ImageDescription field
r et ur ned by imfinfo.
empt y
'Resolution' A scalar value t hat is used t o set t he r esolut ion of
t he out put file in bot h t he x and y dir ect ions.
72
Parameter Values Default
'Author' A st r ing Empt y
'Description' A st r ing Empt y
'Copyright' A st r ing Empt y
'CreationTime' A st r ing Empt y
'Software' A st r ing Empt y
'Disclaimer' A st r ing Empt y
'Warning' A st r ing Empt y
imwrite
11-145
'Source' A st r ing Empt y
'Comment' A st r ing Empt y
'InterlaceType' Eit her 'none' or 'adam7' 'none'
'BitDepth' A scalar value indicat ing desir ed bit dept h. For
gr ayscale images t his can be 1, 2, 4, 8, or 16.
For gr ayscale images wit h an alpha channel t his
can be 8 or 16. For indexed images t his can be 1, 2,
4, or 8. For t r uecolor images wit h or wit hout an
alpha channel t his can be 8 or 16.
8 bit s per pixel if
image is double or
uint 8
16 bit s per pixel if
image is uint 16
1 bit per pixel if
image is logical
'Transparency' This value is used t o indicat e t r anspar ency
infor mat ion only when no alpha channel is used. Set
t o t he value t hat indicat es which pixels should be
consider ed t r anspar ent . (If t he image uses a
color map, t his value will r epr esent an index number
t o t he color map.)
For indexed images: a Q-element vect or in t he r ange
[0,1] wher e Q is no lar ger t han t he color map
lengt h and each value indicat es t he t r anspar ency
associat ed wit h t he cor r esponding color map ent r y.
In most cases, Q=1.
For gr ayscale images: a scalar in t he r ange [0,1].
For t r uecolor images: a 3-element vect or in t he
r ange [0,1].
You cannot specify 'Transparency' and 'Alpha' at
t he same t ime.
Empt y
Parameter Values Default
imwrite
11-146
'Background' The value specifies backgr ound color t o be used
when composit ing t r anspar ent pixels. For indexed
images: an int eger in t he r ange [1,P], wher e P is
t he color map lengt h. For gr ayscale images: a scalar
in t he r ange [0,1]. For t r uecolor images: a
3-element vect or in t he r ange [0,1].
Empt y
'Gamma' A nonnegat ive scalar indicat ing t he file gamma Empt y
'Chromaticities' An 8-element vect or [wx wy rx ry gx gy bx by]
t hat specifies t he r efer ence whit e point and t he
pr imar y chr omat icit ies
Empt y
'XResolution' A scalar indicat ing t he number of pixels/unit in t he
hor izont al dir ect ion
Empt y
'YResolution' A scalar indicat ing t he number of pixels/unit in t he
ver t ical dir ect ion
Empt y
'ResolutionUnit' Eit her 'unknown' or 'meter' Empt y
'Alpha' A mat r ix specifying t he t r anspar ency of each pixel
individually. The r ow and column dimensions must
be t he same as t he dat a ar r ay; t hey can be uint8,
uint16, or double, in which case t he values should
be in t he r ange [0,1].
Empt y
'SignificantBits' A scalar or vect or indicat ing how many bit s in t he
dat a ar r ay should be r egar ded as significant ; values
must be in t he r ange [1,bitdepth].
For indexed images: a 3-element vect or. For
gr ayscale images: a scalar. For gr ayscale images
wit h an alpha channel: a 2-element vect or. For
t r uecolor images: a 3-element vect or. For t r uecolor
images wit h an alpha channel: a 4-element vect or
Empt y
Parameter Values Default
imwrite
11-147
In addit ion t o t hese PNG par amet er s, you can use any par amet er name t hat
sat isfies t he PNG specificat ion for keywor ds, including only pr int able
char act er s, 80 char act er s or fewer , and no leading or t r ailing spaces. The value
cor r esponding t o t hese user -specified par amet er s must be a st r ing t hat
cont ains no cont r ol char act er s ot her t han linefeed.
This t able summar izes t he t ypes of images t hat imwrite can wr it e.
Class Support Most of t he suppor t ed image file for mat s st or e uint8 dat a. PNG and TIFF
addit ionally suppor t uint16 dat a. For gr ayscale and RGB images, if t he dat a
ar r ay is double, t he assumed dynamic r ange is [0,1]. The dat a ar r ay is
aut omat ically scaled by 255 befor e being wr it t en out as uint8. If t he dat a ar r ay
is uint8 or uint16 (PNG and TIFF only), t hen it is wr it t en out wit hout scaling
as uint8 or uint16, r espect ively.
Format Variants
BMP 8-bit uncompr essed images wit h associat ed color map;
24-bit uncompr essed images
HDF 8-bit r ast er image dat aset s, wit h or wit hout associat ed color map,
24-bit r ast er image dat aset s; uncompr essed or wit h RLE or J PEG compr ession.
J PEG Baseline J PEG images (8 or 24-bit ).
Note: Indexed images ar e conver t ed t o RGB befor e wr it ing out J PEG files,
because t he J PEG for mat does not suppor t indexed images.
PCX 8-bit images
PNG 1-bit , 2-bit , 4-bit , 8-bit , and 16-bit gr ayscale images;
8-bit and 16-bit gr ayscale images wit h alpha channels;
1-bit , 2-bit , 4-bit , and 8-bit indexed images;
24-bit and 48-bit t r uecolor images wit h or wit hout alpha channels
TIFF Baseline TIFF images, including 1-bit , 8-bit , and 24-bit uncompr essed images;
1-bit , 8-bit , and 24-bit images wit h packbit s compr ession;
1-bit images wit h CCITT compr ession
XWD 8-bit ZPixmaps
imwrite
11-148
Note: If a logical double or uint8 is wr it t en t o a PNG or TIFF file, it is
assumed t o be a binar y image and will be wr it t en wit h a bit dept h of 1.
For indexed images, if t he index ar r ay is double, t hen t he indices ar e fir st
conver t ed t o zer o-based indices by subt r act ing 1 fr om each element , and t hen
t hey ar e wr it t en out as uint8. If t he index ar r ay is uint8 or uint16 (PNG and
TIFF only), t hen it is wr it t en out wit hout modificat ion as uint8 or uint16,
r espect ively. When wr it ing PNG files, you can over r ide t his behavior wit h t he
'BitDepth' par amet er ; see t he PNG t able in t his imwrite r efer ence for det ails.
Remarks imwrite is a funct ion in MATLAB.
Example This example appends an indexed image X and it s color map map t o an exist ing
uncompr essed mult ipage HDF file named flowers.hdf.
imwrite(X,map,'flowers.hdf','Compression','none',...
'WriteMode','append')
See Also imfinfo, imread
fwrite in t he online MATLAB Funct ion Refer ence
ind2gray
11-149
11ind2gr ay
Purpose Conver t an indexed image t o an int ensit y image
Syntax I = ind2gray(X,map)
Description I = ind2gray(X,map) conver t s t he image X wit h color map map t o an int ensit y
image I. ind2gray r emoves t he hue and sat ur at ion infor mat ion fr om t he input
image while r et aining t he luminance.
Class Support X can be of class uint8, uint16, or double. I is of class double.
Example load trees
I = ind2gray(X,map);
imshow(X,map)
figure,imshow(I)
Algorithm ind2gray conver t s t he color map t o NTSC coor dinat es using rgb2ntsc, and set s
t he hue and sat ur at ion component s (I and Q) t o zer o, cr eat ing a gr ay color map.
ind2gray t hen r eplaces t he indices in t he image X wit h t he cor r esponding
gr ayscale int ensit y values in t he gr ay color map.
See Also gray2ind, imshow, rgb2ntsc
ind2rgb
11-150
11ind2r gb
Purpose Conver t an indexed image t o an RGB image
Syntax RGB = ind2rgb(X,map)
Description RGB = ind2rgb(X,map) conver t s t he mat r ix X and cor r esponding color map map
t o RGB (t r uecolor ) for mat .
Class Support X can be of class uint8, uint16, or double. RGB is an m-by-n-by-3 ar r ay of class
double.
See Also ind2gray, rgb2ind
iptgetpref
11-151
11ipt get pr ef
Purpose Get Image Pr ocessing Toolbox pr efer ences
Syntax value = iptgetpref(prefname)
Description value = iptgetpref(prefname) r et ur ns t he value of t he Image Pr ocessing
Toolbox pr efer ence specified by t he st r ing prefname. Pr efer ence names ar e case
insensit ive and can be abbr eviat ed.
iptgetpref wit hout an input ar gument displays t he cur r ent set t ing of all
Image Pr ocessing Toolbox pr efer ences.
Example value = iptgetpref('ImshowAxesVisible')
value =
off
See Also imshow, iptsetpref
iptsetpref
11-152
11ipt set pr ef
Purpose Set Image Pr ocessing Toolbox pr efer ences
Syntax iptsetpref(prefname,value)
Description iptsetpref(prefname,value) set s t he Image Pr ocessing Toolbox pr efer ence
specified by t he st r ing prefname t o value. The set t ing per sist s unt il t he end of
t he cur r ent MATLAB session, or unt il you change t he set t ing. (To make t he
value per sist bet ween sessions, put t he command in your startup.m file.)
This t able descr ibes t he available pr efer ences. Not e t hat t he pr efer ence names
ar e case insensit ive and can be abbr eviat ed.
Preference Name Values
'ImshowBorder' 'loose' (default ) or 'tight'
If 'ImshowBorder' is 'loose', imshow displays t he image wit h a bor der bet ween t he image and
t he edges of t he figur e window, t hus leaving r oom for axes labels, t it les, et c. If 'ImshowBorder' is
'tight', imshow adjust s t he figur e size so t hat t he image ent ir ely fills t he figur e. (However,
t her e may st ill be a bor der if t he image is ver y small, or if t her e ar e ot her object s besides t he
image and it s axes in t he figur e.)
'ImshowAxesVisible' 'on' or 'off' (default )
If 'ImshowAxesVisible' is 'on', imshow displays t he image wit h t he axes box and t ick labels. If
'ImshowAxesVisible' is 'off', imshow displays t he image wit hout t he axes box and t ick labels.
'ImshowTruesize' 'auto' (default ) or 'manual'
If 'ImshowTruesize' is 'manual', imshow does not call truesize. If 'ImshowTruesize' is
'auto', imshow aut omat ically decides whet her t o call truesize. (imshow calls truesize if t her e
will be no ot her object s in t he r esult ing figur e besides t he image and it s axes.) You can over r ide
t his set t ing for an individual display by specifying t he display_option ar gument t o imshow, or
you can call truesize manually aft er displaying t he image.
'TruesizeWarning' 'on' (default ) or 'off'
If 'TruesizeWarning' is 'on', t he truesize funct ion displays a war ning if t he image is t oo lar ge
t o fit on t he scr een. (The ent ir e image is st ill displayed, but at less t han t r ue size.) If
'TruesizeWarning' is 'off', truesize does not display t he war ning. Not e t hat t his pr efer ence
applies even when you call truesize indir ect ly, such as t hr ough imshow.
iptsetpref
11-153
iptsetpref(prefname) displays t he valid values for prefname.
Example iptsetpref('ImshowBorder','tight')
See Also imshow, iptgetpref, truesize
axis in t he online MATLAB Funct ion Refer ence
iradon
11-154
11iradon
Purpose Comput e inver se Radon t r ansfor m
Syntax I = iradon(P,theta)
I = iradon(P,theta,interp,filter,d,n)
[I,h] = iradon(...)
Description I = iradon(P,theta) r econst r uct s t he image I fr om pr oject ion dat a in t he
t wo-dimensional ar r ay P. The columns of P ar e par allel beam pr oject ion dat a.
iradon assumes t hat t he cent er of r ot at ion is t he cent er point of t he pr oject ions,
which is defined as ceil(size(P,1)/2).
theta descr ibes t he angles (in degr ees) at which t he pr oject ions wer e t aken. It
can be eit her a vect or cont aining t he angles or a scalar specifying D_theta, t he
incr ement al angle bet ween pr oject ions. If theta is a vect or , it must cont ain
angles wit h equal spacing bet ween t hem. If theta is a scalar specifying
D_theta, t he pr oject ions ar e t aken at angles theta = m*D_theta, wher e
m = 0,1,2,...,size(P,2)1. If t he input is t he empt y mat r ix ([]), D_theta
default s t o 180/size(P,2).
I = iradon(P,theta,interp,filter,d,n) specifies par amet er s t o use in t he
inver se Radon t r ansfor m. You can specify any combinat ion of t he last four
ar gument s. iradon uses default values for any of t hese ar gument s t hat you
omit .
interp specifies t he t ype of int er polat ion t o use in t he backpr oject ion. The
available opt ions ar e list ed in or der of incr easing accur acy and comput at ional
complexit y.
'nearest' near est neighbor int er polat ion
'linear' linear int er polat ion (default )
'spline' spline int er polat ion
filter specifies t he filt er t o use for fr equency domain filt er ing. filter is a
st r ing t hat specifies any of t he following st andar d filt er s.
'Ram-Lak' The cr opped Ram-Lak or r amp filt er (default ). The fr equency
r esponse of t his filt er is | f | . Because t his filt er is sensit ive t o noise in t he
pr oject ions, one of t he filt er s list ed below may be pr efer able. These filt er s
iradon
11-155
mult iply t he Ram-Lak filt er by a window t hat de-emphasizes high
fr equencies.
'Shepp-Logan' The Shepp-Logan filt er mult iplies t he Ram-Lak filt er by a
sinc funct ion.
'Cosine' The cosine filt er mult iplies t he Ram-Lak filt er by a cosine
funct ion.
'Hamming' The Hamming filt er mult iplies t he Ram-Lak filt er by a
Hamming window.
'Hann' The Hann filt er mult iplies t he Ram-Lak filt er by a Hann window.
d is a scalar in t he r ange (0,1] t hat modifies t he filt er by r escaling it s fr equency
axis. The default is 1. If d is less t han 1, t he filt er is compr essed t o fit int o t he
fr equency r ange [0,d], in nor malized fr equencies; all fr equencies above d ar e set
t o 0.
n is a scalar t hat specifies t he number of r ows and columns in t he r econst r uct ed
image. If n is not specified, t he size is det er mined fr om t he lengt h of t he
pr oject ions.
n = 2*floor(size(P,1)/(2*sqrt(2)))
If you specify n, iradon r econst r uct s a smaller or lar ger por t ion of t he image,
but does not change t he scaling of t he dat a. If t he pr oject ions wer e calculat ed
wit h t he radon funct ion, t he r econst r uct ed image may not be t he same size as
t he or iginal image.
[I,h] = iradon(...) r et ur ns t he fr equency r esponse of t he filt er in t he vect or
h.
Class Support All input ar gument s must be of class double. The out put ar gument s ar e of class
double.
iradon
11-156
Example P = phantom(128);
R = radon(P,0:179);
I = iradon(R,0:179,'nearest','Hann');
imshow(P)
figure, imshow(I)
Algorithm iradon uses t he filt er ed backpr oject ion algor it hm t o per for m t he inver se Radon
t r ansfor m. The filt er is designed dir ect ly in t he fr equency domain and t hen
mult iplied by t he FFT of t he pr oject ions. The pr oject ions ar e zer o-padded t o a
power of 2 befor e filt er ing t o pr event spat ial domain aliasing and t o speed up
t he FFT.
See Also radon, phantom
References Kak, Avinash C., and Malcolm Slaney, Principles of Computerized
Tomographic Imaging. New Yor k: IEEE Pr ess.
isbw
11-157
11isbw
Purpose Ret ur n t r ue for a binar y image
Syntax flag = isbw(A)
Description flag = isbw(A) r et ur ns 1 if A is a binar y image and 0 ot her wise.
isbw uses t hese cr it er ia t o decide if A is a binar y image:
If A is of class double, all values must be eit her 0 or 1, t he logical flag must
be on, and t he number of dimensions of A must be 2.
If A is of class uint8, t he logical flag must be on, and t he number of
dimensions of A must be 2.
If A is of class uint16, it is not a binar y image. (The t oolbox does not suppor t
uint16 binar y images.)
Note: A four-dimensional ar r ay t hat cont ains mult iple binar y images
r et ur ns 0, not 1.
Class Support A can be of class uint8, uint16, or double.
See Also isind, isgray, isrgb
isgray
11-158
11isgr ay
Purpose Ret ur n t r ue for int ensit y image
Syntax flag = isgray(A)
Description flag = isgray(A) r et ur ns 1 if A is a gr ayscale int ensit y image and 0 ot her wise.
isgray uses t hese cr it er ia t o decide if A is an int ensit y image:
If A is of class double, all values must be in t he r ange [0,1], and t he number
of dimensions of A must be 2.
If A is of class uint16 or uint8, t he number of dimensions of A must be 2.
Not e t hat a four -dimensional ar r ay t hat cont ains mult iple int ensit y images
r et ur ns 0, not 1.
Class Support A can be of class uint8, uint16, or double.
See Also isbw, isind, isrgb
isind
11-159
11isind
Purpose Ret ur n t r ue for an indexed image
Syntax flag = isind(A)
Description flag = isind(A) r et ur ns 1 if A is an indexed image and 0 ot her wise.
isind uses t hese cr it er ia t o det er mine if A is an indexed image:
If A is of class double, all values in A must be int eger s gr eat er t han or equal
t o 1, and t he number of dimensions of A must be 2.
If A is of class uint8, it s logical flag must be off, and t he number of
dimensions of A must be 2.
If A is of class uint16, t he number of dimensions of A must be 2.
Note: A four-dimensional ar r ay t hat cont ains mult iple indexed images
r et ur ns 0, not 1.
Class Support A can be of class uint8, uint16, or double.
See Also isbw, isgray, isrgb
isrgb
11-160
11isr gb
Purpose Ret ur n t r ue for an RGB image
Syntax flag = isrgb(A)
Description flag = isrgb(A) r et ur ns 1 if A is an RGB t r uecolor image and 0 ot her wise.
isrgb uses t hese cr it er ia t o det er mine if A is an RGB image:
If A is of class double, all values must be in t he r ange [0,1], and A must be
m-by-n-by-3.
If A is of class uint16 or uint8, A must be m-by-n-by-3.
Note: A four-dimensional ar r ay t hat cont ains mult iple RGB images r et ur ns
0, not 1.
Class Support A can be of class uint8, uint16, or double.
See Also isbw, isgray, isind
makelut
1-165
1
1makelut
Purpose Const r uct a lookup t able for use wit h applylut
Syntax lut = makelut(fun,n)
lut = makelut(fun,n,P1,P2,...)
Description lut = makelut(fun,n) r et ur ns a lookup t able for use wit h applylut. fun is
eit her a st r ing cont aining t he name of a funct ion or an inline funct ion object .
The funct ion should t ake a 2-by-2 or 3-by-3 mat r ix of 1s and 0s as input and
r et ur n a scalar . n is eit her 2 or 3, indicat ing t he size of t he input t o fun. makelut
cr eat es lut by passing all possible 2-by-2 or 3-by-3 neighbor hoods t o fun, one
at a t ime, and const r uct ing eit her a 16-element vect or (for 2-by-2
neighbor hoods) or a 512-element vect or (for 3-by-3 neighbor hoods). The vect or
consist s of t he out put fr om fun for each possible neighbor hood.
lut = makelut(fun,n,P1,P2,...) passes t he addit ional par amet er s
P1,P2,..., t o fun.
Class Support lut is r et ur ned as a vect or of class double.
makelut
1-166
Example In t his example, t he funct ion r et ur ns 1 (t r ue) if t he number of 1s in t he
neighbor hood is 2 or gr eat er , and r et ur ns 0 (false) ot her wise. makelut t hen uses
t he funct ion t o const r uct a lookup t able for 2-by-2 neighbor hoods.
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 applylut
mat2gray
1-167
1mat 2gr ay
Purpose Conver t a mat r ix t o a gr ayscale int ensit y image
Syntax I = mat2gray(A,[amin amax])
I = mat2gray(A)
Description I = mat2gray(A,[amin amax]) conver t s t he mat r ix A t o t he int ensit y image I.
The r et ur ned mat r ix I cont ains values in t he r ange 0 (black) t o 1.0 (full
int ensit y or whit e). amin and amax ar e t he values in A t hat cor r espond t o 0 and
1.0 in I.
I = mat2gray(A) set s t he values of amin and amax t o t he minimum and
maximum values in A.
Class Support The input ar r ay A and t he out put image I ar e of class double.
Example I = imread('rice.tif');
J = filter2(fspecial('sobel'),I);
K = mat2gray(J);
imshow(I)
figure, imshow(K)
See Also gray2ind
mean2
1-168
1mean2
Purpose Comput e t he mean of t he element s of a mat r ix
Syntax b = mean2(A)
Description b = mean2(A) comput es t he mean of t he values in A.
Class Support A is an ar r ay of class double or of any int eger class. b is a scalar of class double.
Algorithm mean2 comput es t he mean of an ar r ay A using mean(A(:)).
See Also std2
mean, std in t he online MATLAB Funct ion Refer ence
medfilt2
1-169
1medfilt 2
Purpose Per for m t wo-dimensional median filt er ing
Syntax B = medfilt2(A,[m n])
B = medfilt2(A)
B = medfilt2(A,'indexed',...)
Description Median filt er ing is a nonlinear oper at ion oft en used in image pr ocessing t o
r educe salt and pepper noise. Median filt er ing is mor e effect ive t han
convolut ion when t he goal is t o simult aneously r educe noise and pr eser ve
edges.
B = medfilt2(A,[m n]) per for ms median filt er ing of t he mat r ix A in t wo
dimensions. Each out put pixel cont ains t he median value in t he m-by-n
neighbor hood ar ound t he cor r esponding pixel in t he input image. medfilt2
pads t he image wit h zer os on t he edges, so t he median values for t he point s
wit hin [m n]/2 of t he edges may appear dist or t ed.
B = medfilt2(A) per for ms median filt er ing of t he mat r ix A using t he default
3-by-3 neighbor hood.
B = medfilt2(A,'indexed',...) pr ocesses A as an indexed image, padding
wit h zer os if t he class of A is uint8, or ones if t he class of A is double.
Class Support The input image A can be of class uint8, uint16, or double (unless t he
'indexed' synt ax is used, in which case A cannot be of class uint16). The
out put image B is of t he same class as A.
Remarks If t he input image A is of class uint8, all of t he out put values ar e r et ur ned as
uint8 int eger s. If t he number of pixels in t he neighbor hood (i.e., m*n) is even,
some of t he median values may not be int eger s. In t hese cases, t he fr act ional
par t s ar e discar ded.
For example, suppose you call medfilt2 using 2-by-2 neighbor hoods, and t he
input image is a uint8 ar r ay t hat includes t his neighbor hood:
1 5
4 8
medfilt2 r et ur ns an out put value of 4 for t his neighbor hood, alt hough t he t r ue
median is 4.5.
medfilt2
1-170
Example This example adds salt and pepper noise t o an image, t hen r est or es t he 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 t o per for m t he filt er ing.
See Also filter2, ordfilt2, wiener2
Reference Lim, J ae S. Two-Dimensional S ignal and Image Processing. Englewood Cliffs,
NJ : Pr ent ice Hall, 1990. pp. 469-476.
montage
1-171
1mont age
Purpose Display mult iple image fr ames as a r ect angular mont age
Syntax montage(I)
montage(BW)
montage(X,map)
montage(RGB)
h = montage(...)
Description montage displays all of t he fr ames of a mult ifr ame image ar r ay in a single
image object , ar r anging t he fr ames so t hat t hey r oughly for m a squar e.
montage(I) displays t he k fr ames of t he int ensit y image ar r ay I. I is
m-by-n-by-1-by-k.
montage(BW) displays t he k fr ames of t he binar y image ar r ay BW. BW is
m-by-n-by-1-by-k.
montage(X,map) displays t he k fr ames of t he indexed image ar r ay X, using t he
color map map for all fr ames. X is m-by-n-by-1-by-k.
montage(RGB) displays t he k fr ames of t he t r uecolor image ar r ay RGB. RGB is
m-by-n-by-3-by-k.
h = montage(...) r et ur ns t he handle t o t he image object .
Class Support The input image can be of class uint8, uint16, or double.
montage
1-172
Example load mri
montage(D,map)
See Also immovie
nlfilter
1-173
1nlfilt er
Purpose Per for m gener al sliding-neighbor hood oper at ions
Syntax 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 t he funct ion fun t o each m-by-n sliding
block of A. fun can be a st r ing cont aining t he name of a funct ion, a st r ing
cont aining an expr ession, or an inline funct ion object . fun should accept an
m-by-n block as input , and r et ur n a scalar r esult :
c = fun(x)
c is t he out put value for t he cent er pixel in t he m-by-n block x. nlfilter calls
fun for each pixel in A. nlfilter zer o pads t he m-by-n block at t he edges, if
necessar y.
B = nlfilter(A,[m n],fun,P1,P2,...) passes t he addit ional par amet er s
P1,P2,..., t o fun.
B = nlfilter(A,'indexed',...) pr ocesses A as an indexed image, padding
wit h ones if A is of class double and zer os if A is of class uint8.
Class Support The input image A can be of any class suppor t ed by fun. The class of B depends
on t he class of t he out put fr om fun.
Remarks nlfilter can t ake a long t ime t o pr ocess lar ge images. In some cases, t he
colfilt funct ion can per for m t he same oper at ion much fast er .
Example This call pr oduces t he same r esult as calling medfilt2 wit h a 3-by-3
neighbor hood:
B = nlfilter(A,[3 3],'median(x(:))');
See Also blkproc, colfilt
ntsc2rgb
1-174
1nt sc2r gb
Purpose Conver t NTSC values t o RGB color space
Syntax rgbmap = ntsc2rgb(yiqmap)
RGB = ntsc2rgb(YIQ)
Description rgbmap = ntsc2rgb(yiqmap) conver t s t he m-by-3 NTSC (t elevision) color
values in yiqmap t o RGB color space. If yiqmap is m-by-3 and cont ains t he NTSC
luminance (Y) and chr ominance (I and Q) color component s as columns, t hen
rgbmap is an m-by-3 mat r ix t hat cont ains t he r ed, gr een, and blue values
equivalent t o t hose color s. Bot h rgbmap and yiqmap cont ain int ensit ies in t he
r ange 0 t o 1.0. The int ensit y 0 cor r esponds t o t he absence of t he component ,
while t he int ensit y 1.0 cor r esponds t o full sat ur at ion of t he component .
RGB = ntsc2rgb(YIQ) conver t s t he NTSC image YIQ t o t he equivalent t r uecolor
image RGB.
ntsc2rgb comput es t he RGB values fr om t he NTSC component s using:
Class Support The input image or color map must be of class double. The out put is of class
double.
See Also rgb2ntsc, rgb2ind, ind2rgb, ind2gray
R
G
B
1.000 0.956 0.621
1.000 0.272 0.647
1.000 1.106 1.703
Y
I
Q
=
ordfilt2
1-175
1or dfilt 2
Purpose Per for m t wo-dimensional or der -st at ist ic filt er ing
Syntax B = ordfilt2(A,order,domain)
B = ordfilt2(A,order,domain,S)
B = ordfilt2(...,padopt)
Description B = ordfilt2(A,order,domain) r eplaces each element in A by t he order-t h
element in t he sor t ed set of neighbor s specified by t he nonzer o element s in
domain.
B = ordfilt2(A,order,domain,S), wher e S is t he same size as domain, uses
t he values of S cor r esponding t o t he nonzer o values of domain as addit ive
offset s.
B = ordfilt2(...,padopt) cont r ols how t he mat r ix boundar ies ar e padded.
Set padopt t o 'zeros' (t he default ), or 'symmetric'. If padopt is 'zeros', A is
padded wit h zer os at t he boundar ies. If padopt is 'symmetric', A is
symmet r ically ext ended at t he boundar ies.
Class Support A can be of class uint8, uint16, or double. The class of B is t he same as t he class
of A, unless t he addit ive offset for m of ordfilt2 is used, in which case t he class
of B is double.
Remarks domain is equivalent t o t he st r uct ur ing element used for binar y image
oper at ions. It is a mat r ix cont aining only 1s and 0s; t he 1s define t he
neighbor hood for t he filt er ing oper at ion.
For example, B = ordfilt2(A,5,ones(3,3)) implement s a 3-by-3 median
filt er ; B = ordfilt2(A,1,ones(3,3)) implement s a 3-by-3 minimum filt er ;
and B = ordfilt2(A,9,ones(3,3)) implement s a 3-by-3 maximum filt er .
B = ordfilt2(A,1,[0 1 0; 1 0 1; 0 1 0]) r eplaces each element in A by t he
minimum of it s nor t h, east , sout h, and west neighbor s.
The synt ax t hat includes S (t he mat r ix of addit ive offset s) can be used t o
implement gr ayscale mor phological oper at ions, including gr ayscale dilat ion
and er osion.
See Also medfilt2
ordfilt2
1-176
Reference Har alick, Rober t M., and Linda G. Shapir o. Computer and Robot Vision,
Volume I. Addison-Wesley, 1992.
phantom
1-177
1phant om
Purpose Gener at e a head phant om image
Syntax P = phantom(def,n)
P = phantom(E,n)
[P,E] = phantom(...)
Description P = phantom(def,n) gener at es an image of a head phant om t hat can be used
t o t est t he numer ical accur acy of radon and iradon or ot her t wo-dimensional
r econst r uct ion algor it hms. P is a gr ayscale int ensit y image t hat consist s of one
lar ge ellipse (r epr esent ing t he br ain) cont aining sever al smaller ellipses
(r epr esent ing feat ur es in t he br ain).
def is a st r ing t hat specifies t he t ype of head phant om t o gener at e. Valid values
ar e:
'Shepp-Logan' a t est image used widely by r esear cher s in t omogr aphy.
'Modified Shepp-Logan' (default ) a var iant of t he Shepp-Logan phant om
in which t he cont r ast is impr oved for bet t er visual per cept ion.
n is a scalar t hat specifies t he number of r ows and columns in P. If you omit t he
ar gument , n default s t o 256.
P = phantom(E,n) gener at es a user -defined phant om, wher e each r ow of t he
mat r ix E specifies an ellipse in t he image. E has six columns, wit h each column
phantom
1-178
cont aining a differ ent par amet er for t he ellipses. This t able descr ibes t he
columns of t he mat r ix
For pur poses of gener at ing t he phant om, t he domains for t he x- and y-axes
span [1,1]. Columns 2 t hr ough 5 must be specified in t er ms of t his r ange.
[P,E] = phantom(...) r et ur ns t he mat r ix E used t o gener at e t he phant om.
Class Support All input s must be of class double. All out put s ar e of class double.
Remarks For any given pixel in t he out put image, t he pixels value is equal t o t he sum of
t he addit ive int ensit y values of all ellipses t hat t he pixel is a par t of. If a pixel
is not par t of any ellipse, it s value is 0.
The addit ive int ensit y value A for an ellipse can be posit ive or negat ive; if it is
negat ive, t he ellipse will be dar ker t han t he sur r ounding pixels. Not e t hat ,
depending on t he values of A, some pixels may have values out side t he r ange
[0,1].
Column Parameter Meaning
Column 1 A Addit ive int ensit y value of t he
ellipse
Column 2 a Lengt h of t he hor izont al semi-axis of
t he ellipse
Column 3 b Lengt h of t he ver t ical semi-axis of
t he ellipse
Column 4 x0 x-coor dinat e of t he cent er of t he
ellipse
Column 5 y0 y-coor dinat e of t he cent er of t he
ellipse
Column 6 phi Angle (in degr ees) bet ween t he
hor izont al semi-axis of t he ellipse
and t he x-axis of t he image
phantom
1-179
Example P = phantom('Modified Shepp-Logan',200);
imshow(P)
References J ain, Anil K. Fundamentals of Digital Image Processing. Englewood Cliffs, NJ :
Pr ent ice Hall, 1989. p. 439.
See Also radon, iradon
pixval
1-180
1pixval
Purpose Display infor mat ion about image pixels
Syntax pixval on
pixval off
pixval
pixval(fig,option)
Purpose pixval on t ur ns on int er act ive display of infor mat ion about image pixels in t he
cur r ent figur e. pixval inst alls a black bar at t he bot t om of t he figur e, which
displays t he r ow-column coor dinat es for what ever pixel t he cur sor is cur r ent ly
over , and t he color infor mat ion for t hat pixel. If t he image is binar y or int ensit y,
t he color infor mat ion is a single int ensit y value. If t he image is indexed or RGB,
t he color infor mat ion is an RGB t r iplet . The values displayed ar e t he act ual
dat a values, r egar dless of t he class of t he image ar r ay, or whet her t he dat a is
in nor mal image r ange.
If you click on t he image and hold down t he mouse but t on while you move t he
cur sor , pixval also displays t he Euclidean dist ance bet ween t he point you
clicked on and t he cur r ent cur sor locat ion. pixval dr aws a line bet ween t hese
point s t o indicat e t he dist ance being measur ed. When you r elease t he mouse
but t on, t he line and t he dist ance display disappear .
You can move t he display bar by clicking on it and dr agging it t o anot her place
in t he figur e.
pixval off t ur ns int er act ive display off in t he cur r ent figur e. You can also t ur n
off t he display by clicking t he but t on on t he r ight side of t he display bar .
pixval t oggles int er act ive display on or off in t he cur r ent figur e.
pixval(fig,option) applies t he pixval command t o t he figur e specified by
fig. option is st r ing cont aining 'on' or 'off'.
See Also impixel, improfile
qtdecomp
1-181
1qt decomp
Purpose Per for m quadt r ee decomposit ion
Syntax S = qtdecomp(I)
S = qtdecomp(I,threshold)
S = qtdecomp(I,threshold,mindim)
S = qtdecomp(I,threshold,[mindim maxdim])
S = qtdecomp(I,fun)
S = qtdecomp(I,fun,P1,P2,...)
Description qtdecomp divides a squar e image int o four equal-sized squar e blocks, and t hen
t est s each block t o see if it meet s some cr it er ion of homogeneit y. If a block
meet s t he cr it er ion, it is not divided any fur t her . If it does not meet t he
cr it er ion, it is subdivided again int o four blocks, and t he t est cr it er ion is applied
t o t hose blocks. This pr ocess is r epeat ed it er at ively unt il each block meet s t he
cr it er ion. The r esult may have blocks of sever al differ ent sizes.
S = qtdecomp(I) per for ms a quadt r ee decomposit ion on t he int ensit y image I,
and r et ur ns t he quadt r ee st r uct ur e in t he spar se mat r ix S. If S(k,m) is nonzer o,
t hen (k,m) is t he upper -left cor ner of a block in t he decomposit ion, and t he size
of t he block is given by S(k,m). By default , qtdecomp split s a block unless all
element s in t he block ar e equal.
S = qtdecomp(I,threshold) split s a block if t he maximum value of t he block
element s minus t he minimum value of t he block element s is gr eat er t han
threshold. threshold is specified as a value bet ween 0 and 1, even if I is of
class uint8 or uint16. If I is uint8, t he t hr eshold value you supply is
mult iplied by 255 t o det er mine t he act ual t hr eshold t o use; if I is uint16, t he
t hr eshold value you supply is mult iplied by 65535.
S = qtdecomp(I,threshold,mindim) will not pr oduce blocks smaller t han
mindim, even if t he r esult ing blocks do not meet t he t hr eshold condit ion.
S = qtdecomp(I,threshold,[mindim maxdim]) will not pr oduce blocks
smaller t han mindim or lar ger t han maxdim. Blocks lar ger t han maxdim ar e split
even if t hey meet t he t hr eshold condit ion. maxdim/mindim must be a power of 2.
S = qtdecomp(I,fun) uses t he funct ion fun t o det er mine whet her t o split a
block. qtdecomp calls fun wit h all t he cur r ent blocks of size m-by-m st acked int o
an m-by-m-by-k ar r ay, wher e k is t he number of m-by-m blocks. fun should r et ur n
qtdecomp
1-182
a k-element vect or , cont aining only 1s and 0s, wher e 1 indicat es t hat t he
cor r esponding block should be split , and 0 indicat es it should not be split . (For
example, if k(3) is 0, t he t hir d m-by-m block should not be split .) fun can be a
st r ing cont aining t he name of a funct ion, a st r ing cont aining an expr ession, or
an inline funct ion.
S = qtdecomp(I,fun,P1,P2,...) passes P1,P2,..., as addit ional ar gument s
t o fun.
Class Support For t he synt axes t hat do not include a funct ion, t he input image can be of class
uint8, uint16, or double. For t he synt axes t hat include a funct ion, t he input
image can be of any class suppor t ed by t he funct ion. The out put mat r ix is
always of class sparse.
Remarks qtdecomp is appr opr iat e pr imar ily for squar e images whose dimensions ar e a
power of 2, such as 128-by-128 or 512-by-512. These images can be divided
unt il t he blocks ar e as small as 1-by-1. If you use qtdecomp wit h an image
whose dimensions ar e not a power of 2, at some point t he blocks cannot be
divided fur t her . For example, if an image is 96-by-96, it can be divided int o
blocks of size 48-by-48, t hen 24-by-24, 12-by-12, 6-by-6, and finally 3-by-3. No
fur t her division beyond 3-by-3 is possible. To pr ocess t his image, you must set
mindim t o 3 (or t o 3 t imes a power of 2); if you ar e using t he synt ax t hat includes
a funct ion, t he funct ion must r et ur n 0 at t he point when t he block cannot be
divided fur t her .
qtdecomp
1-183
Example I = [1 1 1 1 2 3 6 6
1 1 2 1 4 5 6 8
1 1 1 1 10 15 7 7
1 1 1 1 20 25 7 7
20 22 20 22 1 2 3 4
20 22 22 20 5 6 7 8
20 22 20 20 9 10 11 12
22 22 20 20 13 14 15 16];
S = qtdecomp(I,5);
full(S)
ans =
4 0 0 0 2 0 2 0
0 0 0 0 0 0 0 0
0 0 0 0 1 1 2 0
0 0 0 0 1 1 0 0
4 0 0 0 2 0 2 0
0 0 0 0 0 0 0 0
0 0 0 0 2 0 2 0
0 0 0 0 0 0 0 0
See Also qtgetblk, qtsetblk
qtgetblk
1-184
1qt get blk
Purpose Get block values in quadt r ee decomposit ion
Syntax [vals,r,c] = qtgetblk(I,S,dim)
[vals,idx] = qtgetblk(I,S,dim)
Description [vals,r,c] = qtgetblk(I,S,dim) r et ur ns in vals an ar r ay cont aining t he
dim-by-dim blocks in t he quadt r ee decomposit ion of I. S is t he spar se mat r ix
r et ur ned by qtdecomp; it cont ains t he quadt r ee st r uct ur e. vals is a
dim-by-dim-by-k ar r ay, wher e k is t he number of dim-by-dim blocks in t he
quadt r ee decomposit ion; if t her e ar e no blocks of t he specified size, all out put s
ar e r et ur ned as empt y mat r ices. r and c ar e vect or s cont aining t he r ow and
column coor dinat es of t he upper -left cor ner s of t he blocks.
[vals,idx] = qtgetblk(I,S,dim) r et ur ns in idx a vect or cont aining t he
linear indices of t he upper -left cor ner s of t he blocks.
Class Support I can be of class uint8, uint16, or double. S is of class sparse.
Remarks The or der ing of t he blocks in vals mat ches t he columnwise or der of t he blocks
in I. For example, if vals is 4-by-4-by-2, vals(:,:,1) cont ains t he values fr om
t he fir st 4-by-4 block in I, and vals(:,:,2) cont ains t he values fr om t he second
4-by-4 block.
qtgetblk
1-185
Example This example cont inues t he qtdecomp example.
[vals,r,c] = qtgetblk(I,S,4)

vals(:,:,1) =

1 1 1 1
1 1 2 1
1 1 1 1
1 1 1 1


vals(:,:,2) =

20 22 20 22
20 22 22 20
20 22 20 20
22 22 20 20


r =

1
5
c =

1
1
See Also qtdecomp, qtsetblk
qtsetblk
1-186
1qt set blk
Purpose Set block values in quadt r ee decomposit ion
Syntax J = qtsetblk(I,S,dim,vals)
Description J = qtsetblk(I,S,dim,vals) r eplaces each dim-by-dim block in t he quadt r ee
decomposit ion of I wit h t he cor r esponding dim-by-dim block in vals. S is t he
spar se mat r ix r et ur ned by qtdecomp; it cont ains t he quadt r ee st r uct ur e. vals
is a dim-by-dim-by-k ar r ay, wher e k is t he number of dim-by-dim blocks in t he
quadt r ee decomposit ion.
Class Support I can be of class uint8, uint16, or double. S is of class sparse.
Remarks The or der ing of t he blocks in vals must mat ch t he columnwise or der of t he
blocks in I. For example, if vals is 4-by-4-by-2, vals(:,:,1) cont ains t he
values used t o r eplace t he fir st 4-by-4 block in I, and vals(:,:,2) cont ains t he
values for t he second 4-by-4 block.
Example This example cont inues t he qtgetblock example.
newvals = cat(3,zeros(4),ones(4));
J = qtsetblk(I,S,4,newvals)

J =

0 0 0 0 2 3 6 6
0 0 0 0 4 5 6 8
0 0 0 0 10 15 7 7
0 0 0 0 20 25 7 7
1 1 1 1 1 2 3 4
1 1 1 1 5 6 7 8
1 1 1 1 9 10 11 12
1 1 1 1 13 14 15 16
See Also qtdecomp, qtgetblk
radon
1-187
1radon
Purpose Comput e Radon t r ansfor m
Syntax R = radon(I,theta)
R = radon(I,theta,n)
[R,xp] = radon(...)
Description The radon funct ion comput es t he Radon t r ansfor m, which is t he pr oject ion of
t he image int ensit y along a r adial line or ient ed at a specified angle.
R = radon(I,theta) r et ur ns t he Radon t r ansfor m of t he int ensit y image I for
t he angle theta degr ees. If theta is a scalar , t he r esult R is a column vect or
cont aining t he Radon t r ansfor m for theta degr ees. If theta is a vect or , t hen R
is a mat r ix in which each column is t he Radon t r ansfor m for one of t he angles
in theta. If you omit theta, it default s t o 0:179.
R = radon(I,theta,n) r et ur ns a Radon t r ansfor m wit h t he pr oject ion
comput ed at n point s. R has n r ows. If you do not specify n, t he number of point s
at which t he pr oject ion is comput ed is:
2*ceil(norm(size(I)floor((size(I)1)/2)1))+3
This number is sufficient t o comput e t he pr oject ion at unit int er vals, even
along t he diagonal.
[R,xp] = radon(...) r et ur ns a vect or xp cont aining t he r adial coor dinat es
cor r esponding t o each r ow of R.
Class Support I can be of class double or of any int eger class. All ot her input s and out put s ar e
of class double.
Remarks The r adial coor dinat es r et ur ned in xp ar e t he values along t he x'-axis, which is
or ient ed at theta degr ees count er clockwise fr om t he x-axis. The or igin of bot h
axes is t he cent er pixel of t he image, which is defined as:
floor((size(I)+1)/2)
For example, in a 20-by-30 image, t he cent er pixel is (10,15).
radon
1-188
Example 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, J ae S. Two-Dimensional S ignal and Image Processing. Englewood Cliffs,
NJ : Pr ent ice Hall, 1990. pp. 42-45.
Br acewell, Ronald N. Two-Dimensional Imaging. Englewood Cliffs, NJ :
Pr ent ice Hall, 1995. pp. 505-537.
rgb2gray
1-189
1rgb2gr ay
Purpose Conver t an RGB image or color map t o gr ayscale
Syntax I = rgb2gray(RGB)
newmap = rgb2gray(map)
Description rgb2gray conver t s RGB images t o gr ayscale by eliminat ing t he hue and
sat ur at ion infor mat ion while r et aining t he luminance.
I = rgb2gray(RGB) conver t s t he t r uecolor image RGB t o t he gr ayscale int ensit y
image I.
newmap = rgb2gray(map) r et ur ns a gr ayscale color map equivalent t o map.
Class Support If t he input is an RGB image, it can be of class uint8, uint16, or double; t he
out put image I is of t he same class as t he input image. If t he input is a
color map, t he input and out put color maps ar e bot h of class double.
Algorithm rgb2gray conver t s t he RGB values t o NTSC coor dinat es, set s t he hue and
sat ur at ion component s t o zer o, and t hen conver t s back t o RGB color space.
See Also ind2gray, ntsc2rgb, rgb2ind, rgb2ntsc
rgb2hsv
1-190
1rgb2hsv
Purpose Conver t RGB values t o hue-sat ur at ion-value (HSV) color space
Syntax hsvmap = rgb2hsv(rgbmap)
HSV = rgb2hsv(RGB)
Description hsvmap = rgb2hsv(rgbmap) conver t s t he m-by-3 RGB values in RGB t o HSV
color space. hsvmap is an m-by-3 mat r ix t hat cont ains t he hue, sat ur at ion, and
value component s as columns t hat ar e equivalent t o t he color s in t he RGB
color map. Bot h rgbmap and hsvmap ar e of class double and cont ain values in
t he r ange 0 t o 1.0.
HSV = rgb2hsv(RGB) conver t s t he t r uecolor image RGB t o t he equivalent HSV
image HSV.
Class Support If t he input is an RGB image, it can be of class uint8, uint16, or double; t he
out put image is of class double. If t he input is a color map, t he input and out put
color maps ar e bot h of class double.
Remarks rgb2hsv is a funct ion in MATLAB.
See Also hsv2rgb, rgbplot
colormap in t he online MATLAB Funct ion Refer ence
rgb2ind
1-191
1rgb2ind
Purpose Conver t an RGB image t o an indexed image
Syntax [X,map] = rgb2ind(RGB,tol)
[X,map] = rgb2ind(RGB,n)
X = rgb2ind(RGB,map)
[...] = rgb2ind(...,dither_option)
Description rgb2ind conver t s RGB images t o indexed images using one of t hr ee differ ent
met hods: unifor m quant izat ion, minimum var iance quant izat ion, and
color map mapping. For all of t hese met hods, rgb2ind also dit her s t he image
unless you specify 'nodither' for dither_option.
[X,map] = rgb2ind(RGB,tol) conver t s t he RGB image t o an indexed image X
using unifor m quant izat ion. map cont ains at most (floor(1/tol)+1)^3 color s.
tol must be bet ween 0 and 1.0.
[X,map] = rgb2ind(RGB,n) conver t s t he RGB image t o an indexed image X
using minimum var iance quant izat ion. map cont ains at most n color s.
X = rgb2ind(RGB,map) conver t s t he RGB image t o an indexed image X wit h
color map map by mat ching color s in RGB wit h t he near est color in t he color map
map.
[...] = rgb2ind(...,dither_option) enables or disables dit her ing.
dither_option is a st r ing t hat can have one of t hese values:
'dither' (default ) dit her s, if necessar y, t o achieve bet t er color r esolut ion at
t he expense of spat ial r esolut ion.
'nodither' maps each color in t he or iginal image t o t he closest color in t he
new map. No dit her ing is per for med.
Class Support The input image can be of class uint8, uint16, or double. The out put image is
of class uint8 if t he lengt h of map is less t han or equal t o 256. It is double
ot her wise.
Remarks If you specify tol, rgb2ind uses unifor m quant izat ion t o conver t t he image.
This met hod involves cut t ing t he RGB color cube int o smaller cubes of lengt h
tol. For example, if you specify a tol of 0.1, t he edges of t he cubes ar e
one-t ent h t he lengt h of t he RGB cube. The t ot al number of small cubes is:
n = (floor(1/tol)+1)^3
rgb2ind
1-192
Each cube r epr esent s a single color in t he out put image. Ther efor e, t he
maximum lengt h of t he color map is n. rgb2ind r emoves any color s t hat dont
appear in t he input image, so t he act ual color map may be much smaller t han n.
If you specify n, rgb2ind uses minimum var iance quant izat ion. This met hod
involves cut t ing t he RGB color cube int o smaller boxes (not necessar ily cubes)
of differ ent sizes, depending on how t he color s ar e dist r ibut ed in t he image. If
t he input image act ually uses fewer color s t han t he number you specify, t he
out put color map is also smaller .
If you specify map, rgb2ind uses color map mapping, which involves finding t he
color s in map t hat best mat ch t he color s in t he RGB image.
Example RGB = imread('flowers.tif');
[X,map] = rgb2ind(RGB,128);
imshow(X,map)
See Also cmunique, dither, imapprox, ind2rgb, rgb2gray
rgb2ntsc
1-193
1rgb2nt sc
Purpose Conver t RGB values t o NTSC color space
Syntax yiqmap = rgb2ntsc(rgbmap)
YIQ = rgb2ntsc(RGB)
Description yiqmap = rgb2ntsc(rgbmap) conver t s t he m-by-3 RGB values in rbgmap t o
NTSC color space. yiqmap is an m-by-3 mat r ix t hat cont ains t he NTSC
luminance (Y) and chr ominance (I and Q) color component s as columns t hat ar e
equivalent t o t he color s in t he RGB color map.
YIQ = rgb2ntsc(RGB) conver t s t he t r uecolor image RGB t o t he equivalent NTSC
image YIQ.
rgb2ntsc defines t he NTSC component s using:
Class Support If t he input is an RGB image, it can be of class uint8, uint16, or double; t he
out put image is of class double. If t he input is a color map, t he input and out put
color maps ar e bot h of class double.
Remarks In t he NTSC color space, t he luminance is t he gr ayscale signal used t o display
pict ur es on monochr ome (black and whit e) t elevisions. The ot her component s
car r y t he hue and sat ur at ion infor mat ion.
See Also ntsc2rgb, rgb2ind, ind2rgb, ind2gray
Y
I
Q
0.299 0.587 0.114
0.596 0.274 0.322
0.211 0.523 0.312
R
G
B
=
rgb2ycbcr
1-194
1rgb2ycbcr
Purpose Conver t RGB values t o YCbCr color space
Syntax ycbcrmap = rgb2ycbcr(rgbmap)
YCBCR = rgb2ycbcr(RGB)
Description ycbcrmap = rgb2ycbcr(rgbmap) conver t s t he RGB values in rbgmap t o t he
YCbCr color space. ycbcrmap is an m-by-3 mat r ix t hat cont ains t he YCbCr
luminance (Y) and chr ominance (Cb and Cr) color component s as columns.
Each r ow r epr esent s t he equivalent color t o t he cor r esponding r ow in t he RGB
color map.
YCBCR = rgb2ycbcr(RGB) conver t s t he t r uecolor image RGB t o t he equivalent
image in t he YCbCr color space.
Class Support If t he input is an RGB image, it can be of class uint8, uint16, or double; t he
out put image is of t he same class as t he input image. If t he input is a color map,
t he input and out put color maps ar e bot h of class double.
See Also ntsc2rgb, rgb2ntsc, ycbcr2rgb
rgbplot
1-195
1rgbplot
Purpose Plot color map
Syntax rgbplot(map)
Description rgbplot(map) plot s t he t hr ee columns of map, wher e map is an m-by-3 color map
mat r ix. rgbplot dr aws t he fir st column in r ed, t he second in gr een, and t he
t hir d in blue.
Example rgbplot(jet)
See Also colormap in t he online MATLAB Funct ion Refer ence
roicolor
1-196
1roicolor
Purpose Select r egion of int er est , based on color
Syntax BW = roicolor(A,low,high)
BW = roicolor(A,v)
Description roicolor select s a r egion of int er est wit hin an indexed or int ensit y image and
r et ur ns a binar y image. (You can use t he r et ur ned image as a mask for masked
filt er ing using roifilt2.)
BW = roicolor(A,low,high) r et ur ns a r egion of int er est select ed as t hose
pixels t hat lie wit hin t he color map r ange [low high]:
BW = (A >= low) & (A <= high)
BW is a binar y image wit h 0s out side t he r egion of int er est and 1s inside.
BW = roicolor(A,v) r et ur ns a r egion of int er est select ed as t hose pixels in A
t hat mat ch t he values in vect or v. BW is a binar y image wit h 1s wher e t he
values of A mat ch t he values of v.
Class Support The input ar r ay A can be of class double or of any int eger class. The out put
ar r ay BW is of class uint8.
Example I = imread('rice.tif');
BW = roicolor(I,128,255);
imshow(I);
figure, imshow(BW)
See Also roifilt2, roipoly
roifill
1-197
1roifill
Purpose Smoot hly int er polat e wit hin an ar bit r ar y image r egion
Syntax 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 int ensit y image. It smoot hly
int er polat es inwar d fr om t he pixel values on t he boundar y of t he polygon by
solving Laplaces equat ion. roifill can be used, for example, t o er ase small
object s in an image.
J = roifill(I,c,r) fills in t he polygon specified by c and r, which ar e
equal-lengt h vect or s cont aining t he r ow-column coor dinat es of t he pixels on
ver t ices of t he polygon. The k-th ver t ex is t he pixel (r(k),c(k)).
J = roifill(I) displays t he image I on t he scr een and let s you specify t he
polygon using t he mouse. If you omit I, roifill oper at es on t he image in t he
cur r ent axes. Use nor mal but t on clicks t o add ver t ices t o t he polygon. Pr essing
Backspace or De lete r emoves t he pr eviously select ed ver t ex. A shift -click,
r ight -click, or double-click adds a final ver t ex t o t he select ion and t hen st ar t s
t he fill; pr essing Return finishes t he select ion wit hout adding a ver t ex.
J = roifill(I,BW) uses BW (a binar y image t he same size as I) as a mask.
roifill fills in t he r egions in I cor r esponding t o t he nonzer o pixels in BW. If
t her e ar e mult iple r egions, roifill per for ms t he int er polat ion on each r egion
independent ly.
[J,BW] = roifill(...) r et ur ns t he binar y mask used t o det er mine which
pixels in I get filled. BW is a binar y image t he same size as I wit h 1s for pixels
cor r esponding t o t he int er polat ed r egion of I and 0s elsewher e.
J = roifill(x,y,I,xi,yi) uses t he vect or s x and y t o est ablish a nondefault
spat ial coor dinat e syst em. xi and yi ar e equal-lengt h vect or s t hat specify
polygon ver t ices as locat ions in t his coor dinat e syst em.
roifill
1-198
[x,y,J,BW,xi,yi] = roifill(...) r et ur ns t he XData and YData in x and y;
t he out put image in J; t he mask image in BW; and t he polygon coor dinat es in xi
and yi. xi and yi ar e empt y if t he roifill(I,BW) for m is used.
If roifill is called wit h no out put ar gument s, t he r esult ing image is displayed
in a new figur e.
Class Support The input image I can of class uint8, uint16, or double. The binar y mask BW
can be of class uint8 or double. The out put image J is of t he same class as I.
All ot her input s and out put s ar e of class double.
Example 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)
See Also roifilt2, roipoly
roifilt2
1-199
1roifilt 2
Purpose Filt er a r egion of int er est
Syntax J = roifilt2(h,I,BW)
J = roifilt2(I,BW,fun)
J = roifilt2(I,BW,fun,P1,P2,...)
Description J = roifilt2(h,I,BW) filt er s t he dat a in I wit h t he t wo-dimensional linear
filt er h. BW is a binar y image t he same size as I t hat is used as a mask for
filt er ing. roifilt2 r et ur ns an image t hat consist s of filt er ed values for pixels
in locat ions wher e BW cont ains 1s, and unfilt er ed values for pixels in locat ions
wher e BW cont ains 0s. For t his synt ax, roifilt2 calls filter2 t o implement
t he filt er .
J = roifilt2(I,BW,fun) pr ocesses t he dat a in I using t he funct ion fun. The
r esult J cont ains comput ed values for pixels in locat ions wher e BW cont ains 1s,
and t he act ual values in I for pixels in locat ions wher e BW cont ains 0s.
fun can be a st r ing cont aining t he name of a funct ion, a st r ing cont aining an
expr ession, or an inline funct ion object . fun should t ake a mat r ix as a single
ar gument and r et ur n a mat r ix of t he same size:
y = fun(x)
J = roifilt2(I,BW,fun,P1,P2,...) passes t he addit ional par amet er s
P1,P2,..., t o fun.
Class Support For t he synt ax t hat includes a filt er h, t he input image I can be of class uint8,
uint16, or double, and t he out put ar r ay J is of class double. For t he synt ax
t hat includes a funct ion, I can be of any class suppor t ed by fun, and t he class
of J depends on t he class of t he out put fr om fun.
roifilt2
1-200
Example This example cont inues t he roipoly example.
h = fspecial('unsharp');
J = roifilt2(h,I,BW);
imshow(J)
See Also filter2, roipoly
roipoly
1-201
1roipoly
Purpose Select a polygonal r egion of int er est
Syntax 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 t o select a polygonal r egion of int er est wit hin an image. roipoly
r et ur ns a binar y image t hat you can use as a mask for masked filt er ing.
BW = roipoly(I,c,r) r et ur ns t he r egion of int er est select ed by t he polygon
descr ibed by vect or s c and r. BW is a binar y image t he same size as I wit h 0s
out side t he r egion of int er est and 1s inside.
BW = roipoly(I) displays t he image I on t he scr een and let s you specify t he
polygon using t he mouse. If you omit I, roipoly oper at es on t he image in t he
cur r ent axes. Use nor mal but t on clicks t o add ver t ices t o t he polygon. Pr essing
Backspace or De lete r emoves t he pr eviously select ed ver t ex. A shift -click,
r ight -click, or double-click adds a final ver t ex t o t he select ion and t hen st ar t s
t he fill; pr essing Return finishes t he select ion wit hout adding a ver t ex.
BW = roipoly(x,y,I,xi,yi) uses t he vect or s x and y t o est ablish a nondefault
spat ial coor dinat e syst em. xi and yi ar e equal-lengt h vect or s t hat specify
polygon ver t ices as locat ions in t his coor dinat e syst em.
[BW,xi,yi] = roipoly(...) r et ur ns t he polygon coor dinat es in xi and yi.
Not e t hat roipoly always pr oduces a closed polygon. If t he point s specified
descr ibe a closed polygon (i.e., if t he last pair of coor dinat es is ident ical t o t he
fir st pair ), t he lengt h of xi and yi is equal t o t he number of point s specified. If
t he point s specified do not descr ibe a closed polygon, roipoly adds a final point
having t he same coor dinat es as t he fir st point . (In t his case t he lengt h of xi and
yi is one gr eat er t han t he number of point s specified.)
[x,y,BW,xi,yi] = roipoly(...) r et ur ns t he XData and YData in x and y; t he
mask image in BW; and t he polygon coor dinat es in xi and yi.
If roipoly is called wit h no out put ar gument s, t he r esult ing image is displayed
in a new figur e.
roipoly
1-202
Class Support The input image I can be of class uint8, uint16, or double. The out put image
BW is of class uint8. All ot her input s and out put s ar e of class double.
Remarks For any of t he roipoly synt axes, you can r eplace t he input image I wit h t wo
ar gument s, m and n, t hat specify t he r ow and column dimensions of an ar bit r ar y
image. For example, t hese commands cr eat e a 100-by-200 binar y mask:
c = [112 112 79 79];
r = [37 66 66 37];
BW = roipoly(100,200,c,r);
If you specify m and n wit h an int er act ive for m of roipoly, an m-by-n black
image is displayed, and you use t he mouse t o specify a polygon wit hin t his
image.
Example 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)
See Also roifilt2, roicolor, roifill
std2
1-203
1st d2
Purpose Comput e t he st andar d deviat ion of t he element s of a mat r ix
Syntax b = std2(A)
Description b = std2(A) comput es t he st andar d deviat ion of t he values in A.
Class Support A is an ar r ay of class double or of any int eger class. b is a scalar of class double.
Algorithm std2 comput es t he st andar d deviat ion of t he ar r ay A using std(A(:)).
See Also corr2, mean2
std, mean in t he online MATLAB Funct ion Refer ence
subimage
1-204
1subimage
Purpose Display mult iple images in t he same figur e
Syntax subimage(X,map)
subimage(I)
subimage(BW)
subimage(RGB)
subimage(x,y,...)
h = subimage(...)
Description You can use subimage in conjunct ion wit h subplot t o cr eat e figur es wit h
mult iple images, even if t he images have differ ent color maps. subimage wor ks
by conver t ing images t o t r uecolor for display pur poses, t hus avoiding color map
conflict s.
subimage(X,map) displays t he indexed image X wit h color map map in t he
cur r ent axes.
subimage(I) displays t he int ensit y image I in t he cur r ent axes.
subimage(BW) displays t he binar y image BW in t he cur r ent axes.
subimage(RGB) displays t he t r uecolor image RGB in t he cur r ent axes.
subimage(x,y...) displays an image using a nondefault spat ial coor dinat e
syst em.
h = subimage(...) r et ur ns a handle t o an image object .
Class Support The input image can be of class uint8, uint16, or double.
subimage
1-205
Example load trees
[X2,map2] = imread('forest.tif');
subplot(1,2,1), subimage(X,map)
subplot(1,2,2), subimage(X2,map2)
See Also imshow
subplot in t he online MATLAB Funct ion Refer ence
truesize
1-206
1t ruesize
Purpose Adjust display size of an image
Syntax truesize(fig,[mrows mcols])
truesize(fig)
Description truesize(fig,[mrows ncols]) adjust s t he display size of an image. fig
is a figur e cont aining a single image or a single image wit h a color bar .
[mrows ncols] is a 1-by-2 vect or t hat specifies t he r equest ed scr een ar ea in
pixels t hat t he image should occupy.
truesize(fig) uses t he image height and widt h for [mrows ncols]. This
r esult s in t he display having one scr een pixel for each image pixel.
If you omit t he figur e ar gument , truesize wor ks on t he cur r ent figur e.
Remarks If t he'TruesizeWarning' t oolbox pr efer ence is 'on', truesize displays a
war ning if t he image is t oo lar ge t o fit on t he scr een. (The ent ir e image is st ill
displayed, but at less t han t r ue size.) If 'TruesizeWarning' is 'off', truesize
does not display t he war ning. Not e t hat t his pr efer ence applies even when you
call truesize indir ect ly, such as t hr ough imshow.
See Also imshow, iptsetpref, iptgetpref
uint8
1-207
1uint 8
Purpose Conver t dat a t o unsigned 8-bit int eger s
Syntax B = uint8(A)
Description B = uint8(A) cr eat es t he unsigned 8-bit int eger ar r ay B fr om t he ar r ay A. If A
is a uint8 ar r ay, B is ident ical t o A.
The element s of a uint8 ar r ay can r ange fr om 0 t o 255. Values out side t his
r ange ar e mapped t o 0 or 255. If A is alr eady an unsigned 8-bit int eger ar r ay,
uint8 has no effect .
The fr act ional par t of each value in A is discar ded on conver sion. This means,
for example, t hat uint8(102.99) is 102, not 103. Ther efor e, it is oft en a good
idea t o r ound off t he values in A befor e conver t ing t o uint8. For example,
B = uint8(round(A))
MATLAB suppor t s t hese oper at ions on uint8 ar r ays:
Displaying dat a values
Indexing int o ar r ays using st andar d MATLAB subscr ipt ing
Reshaping, r eor der ing, and concat enat ing ar r ays, using funct ions such as
reshape, cat, and permute
Saving t o and loading fr om MAT-files
The all and any funct ions
Logical oper at or s and indexing
Relat ional oper at or s
MATLAB also suppor t s t he find funct ion for uint8 ar r ays, but t he r et ur ned
ar r ay is of class double.
Most of t he funct ions in t he Image Pr ocessing Toolbox accept uint8 input . See
t he individual Refer ence ent r ies for infor mat ion about uint8 suppor t .
Remarks uint8 is a MATLAB built -in funct ion.
See Also double, im2double, im2uint8
uint8
1-208
Example a = [1 3 5];
b = uint8(a);
whos
Name Size Bytes Class
a 1x3 24 doublearray
b 1x3 3 uint8 array
uint16
1-209
1uint 16
Purpose Conver t dat a t o unsigned 16-bit int eger s
Syntax I = uint16(X)
Description I = uint16(X) conver t s t he vect or X int o an unsigned 16-bit int eger . X can be
any numer ic object (such as a double). The element s of a uint16 r ange fr om 0
t o 65535. Values out side t his r ange ar e mapped t o 0 or 65535. If X is alr eady an
unsigned 16-bit int eger ar r ay, uint16 has no effect .
The uint16 class is pr imar ily meant t o be used t o st or e int eger values. Hence
most oper at ions t hat manipulat e ar r ays wit hout changing t heir element s ar e
defined, for example, t he funct ions reshape and size, t he r elat ional oper at or s,
subscr ipt ed assignment , and subscr ipt ed r efer ence. While most MATLAB
ar it hmet ic oper at ions cannot be per for med on uint16 dat a, t he following
oper at ions ar e suppor t ed: sum, conv2, convn, fft2, and fftn. In t hese cases t he
out put will always be double. If you at t empt t o per for m an unsuppor t ed
oper at ion you will r eceive an er r or such as Function '+' not defined for
variables of class 'uint16'.
You can define your own met hods for uint16 (as you can for any object ) by
placing t he appr opr iat ely named met hod in an @uint16 dir ect or y wit hin a
dir ect or y on your pat h.
Ot her oper at ions and funct ions suppor t ed for uint16 dat a include:
Displaying dat a values
Indexing int o ar r ays using st andar d MATLAB subscr ipt ing
Logical oper at or s
Saving t o and loading fr om MAT-files
The funct ions cat, permute, all, and any
Most funct ions in t he Image Pr ocessing Toolbox accept uint16 input . See t he
individual r efer ence ent r ies for infor mat ion about uint16 suppor t .
Class Support The input image can be of class uint8 or double.
Remarks uint16 is a MATLAB built -in funct ion.
See Also double, datatypes, uint8, uint32, int8, int16, int32.
uint16
1-210
Example a = [1 3 5];
b = uint16(a);
whos
Name Size Bytes Class
a 1x3 24 double array
b 1x3 6 uint16 array
warp
1-211
1war p
Purpose Display an image as a t ext ur e-mapped sur face
Syntax warp(X,map)
warp(I,n)
warp(BW)
warp(RGB)
warp(z,...)
warp(x,y,z,...)
h = warp(...)
Description warp(X,map) displays t he indexed image X wit h color map map as a t ext ur e map
on a simple r ect angular sur face.
warp(I,n) displays t he int ensit y image I wit h gr ay scale color map of lengt h n
as a t ext ur e map on a simple r ect angular sur face.
warp(BW) displays t he binar y image BW as a t ext ur e map on a simple
r ect angular sur face.
warp(RGB) displays t he RGB image in t he ar r ay RGB as a t ext ur e map on a
simple r ect angular sur face.
warp(z,...) displays t he image on t he sur face z.
warp(x,y,z...) displays t he image on t he sur face (x,y,z).
h = warp(...) r et ur ns a handle t o a t ext ur e mapped sur face.
Class Support The input image can be of class uint8, uint16, or double.
Remarks Text ur e-mapped sur faces gener ally r ender mor e slowly t han images.
warp
1-212
Example This example t ext ur e maps an image of a t est pat t er n ont o a cylinder :
[x,y,z] = cylinder;
I = imread('testpat1.tif');
warp(x,y,z,I);
See Also imshow
image, imagesc, surf in t he online MATLAB Funct ion Refer ence
wiener2
1-213
1wiener2
Purpose Per for m t wo-dimensional adapt ive noise-r emoval filt er ing
Syntax J = wiener2(I,[m n],noise)
[J,noise] = wiener2(I,[m n])
Description wiener2 lowpass filt er s an int ensit y image t hat has been degr aded by const ant
power addit ive noise. wiener2 uses a pixel-wise adapt ive Wiener met hod based
on st at ist ics est imat ed fr om a local neighbor hood of each pixel.
J = wiener2(I,[m n],noise) filt er s t he image I using pixel-wise adapt ive
Wiener filt er ing, using neighbor hoods of size m-by-n t o est imat e t he local image
mean and st andar d deviat ion. If you omit t he [m n] ar gument , m and n default
t o 3. The addit ive noise (Gaussian whit e noise) power is assumed t o be noise.
[J,noise] = wiener2(I,[m n]) also est imat es t he addit ive noise power befor e
doing t he filt er ing. wiener2 r et ur ns t his est imat e in noise.
Class Support The input image I can be of class uint8, uint16, or double. The out put image
J is of t he same class as I.
Example Degr ade and t hen r est or e an int ensit y image using adapt ive Wiener filt er ing.
I = imread('saturn.tif');
J = imnoise(I,'gaussian',0,0.005);
K = wiener2(J,[5 5]);
imshow(J)
figure, imshow(K)
Algorithm wiener2 est imat es t he local mean and var iance ar ound each pixel
wiener2
1-214
wher e is t he N-by-M local neighbor hood of each pixel in t he image A. wiener2
t hen cr eat es a pixel-wise Wiener filt er using t hese est imat es
wher e
2
is t he noise var iance. If t he noise var iance is not given, wiener2 uses
t he aver age of all t he local est imat ed var iances.
See Also filter2, medfilt2
Reference Lim, J ae S. Two-Dimensional S ignal and Image Processing. Englewood Cliffs,
NJ : Pr ent ice Hall, 1990. pp. 536-540.

1
N M
---------- a n
1
n
2
, ( )
n
1
n
2
,

2 1
N M
---------- a
2
n
1
n
2
, ( )
2

n
1
n
2
,

=
b n
1
n
2
, ( )

2

2
------------------ a n
1
n
2
, ( ) ( ) + =
ycbcr2rgb
1-215
1ycbcr2r gb
Purpose Conver t YCbCr values t o RGB color space
Syntax rgbmap = ycbcr2rgb(ycbcrmap)
RGB = ycbcr2rgb(YCBCR)
Description rgbmap = ycbcr2rgb(ycbcrmap) conver t s t he YCbCr values in t he color map
ycbcrmap t o t he RGB color space. If ycbcrmap is m-by-3 and cont ains t he YCbCr
luminance (Y) and chr ominance (Cb and Cr) color component s as it s columns,
t hen rgbmap is r et ur ned as an m-by-3 mat r ix t hat cont ains t he r ed, gr een, and
blue values equivalent t o t hose color s.
RGB = ycbcr2rgb(YCBCR) conver t s t he YCbCr image YCBCR t o t he equivalent
t r uecolor image RGB.
Class Support If t he input is a YCbCr image, it can be of class uint8, uint16, or double; t he
out put image is of t he same class as t he input image. If t he input is a color map,
t he input and out put color maps ar e bot h of class double.
See Also ntsc2rgb, rgb2ntsc, rgb2ycbcr
zoom
1-216
1zoom
Purpose Zoom in and out of an image
Syntax zoom on
zoom off
zoom out
zoom reset
zoom
zoom xon
zoom yon
zoom(factor)
zoom(fig,option)
Description zoom on t ur ns on int er act ive zooming for t he cur r ent figur e. When zooming is
enabled, clicking t he mouse on a point wit hin an axes changes t he axes limit s
by a fact or of 2, t o eit her zoom in on or out fr om t he point :
For a single-but t on mouse, zoom in by clicking t he mouse but t on and zoom
out by shift -clicking.
For a t wo- or t hr ee-but t on mouse, zoom in by clicking t he left mouse but t on
and zoom out by clicking t he r ight mouse but t on.
Clicking and dr agging over an axes when int er act ive zooming is enabled dr aws
a r ubber -band box. When t he mouse but t on is r eleased, t he axes zoom in t o t he
r egion enclosed by t he r ubber -band box.
Double-clicking wit hin an axes r et ur ns t he axes t o it s init ial zoom set t ing.
zoom off t ur ns zoom off in t he cur r ent figur e.
zoom out r et ur ns t he plot t o it s init ial zoom set t ing.
zoom reset r emember s t he cur r ent zoom set t ing as t he init ial zoom set t ing.
Lat er calls t o zoom out , or double-clicks when int er act ive zoom mode is
enabled, r et ur n t o t his zoom level.
zoom t oggles t he int er act ive zoom st at us.
zoom xon and zoom yon set s zoom on for t he x- and y-axis, r espect ively.
zoom(factor) zooms in by t he specified factor, wit hout affect ing t he
int er act ive zoom mode. By default , factor is 2. A fact or bet ween 0 and 1
specifies zooming out by 1/factor.
zoom
1-217
zoom(fig,option) applies t he zoom command t o t he figur e specified by fig.
option is a st r ing cont aining any of t he above ar gument s. If you do not specify
a figur e, zoom wor ks on t he cur r ent figur e.
See Also imcrop
zoom
1-218
I-1
Index
A
adapt ive filt er ing 7-23, 11-209
aliasing 3-5
alpha channel 11-131
analyzing images
cont our plot s 7-7
edge det ect ion 7-10, 11-53
hist ogr ams 7-8, 11-120
int ensit y pr ofiles 7-4, 11-127
pixel values 7-3, 11-124
quadt r ee decomposit ion 7-11, 11-177
summar y st at ist ics 7-9
ant i-aliasing 3-5, 11-136
applylut 8-20, 11-10
ar ea of binar y images 8-18, 11-16
ar r ays
logical 1-7, 1-17
st or ing images 1-3
aver aging filt er 5-10, 11-71
B
bestblk 11-12
bicubic int er polat ion 3-3
bilinear int er polat ion 3-3
binar y image oper at ions 8-2
connect ed-component s labeling 8-15, 11-23
feat ur e measur ement 8-18
flood fill 8-13, 11-20
lookup-t able oper at ions 8-20, 11-10, 11-161
mor phological oper at ions 8-4, 11-25
neighbor hoods 8-2, 11-10
object -based oper at ions 8-10
padding bor der s 8-2
binar y images 11-157
4-connect ed neighbor hoods 8-10
8-connect ed neighbor hoods 8-10
about 1-6
conver t ing fr om ot her t ypes 11-98
displaying 2-6, 8-3
Euler number 8-19, 11-18
image ar ea 8-18, 11-16
object select ion 8-16, 11-30
per imet er det er minat ion 8-12, 11-29
pr ocessing 8-2
binar y masks 9-3
bit dept h 11-134
quer ying 11-118
suppor t 11-134
S ee also index ent r ies for individual file
for mat s
blkproc 4-8, 11-13
block pr ocessing 4-2
block size 11-12
column pr ocessing 4-11
dist inct blocks 4-8, 11-13
padding bor der s 4-5
sliding neighbor hoods 4-4, 11-169
BMP 1-11, 11-117, 11-131, 11-143
bit dept hs suppor t ed when r eading 11-134
bit dept hs suppor t ed when saving 11-147
bor der s
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-9, 11-25
bwperim 8-12, 11-29
bwselect 8-16, 11-30
Index
I-2
C
Canny edge det ect or 7-10, 11-53
cent er pixel 6-20
linear filt er ing 5-4
mor phological oper at ions 8-4
class suppor t 1-10
S ee also dat a t ypes
closur e 8-7, 11-25
cmpermute 11-32
cmunique 11-33
col2im 11-34
colfilt 4-11, 11-35
color 10-2
appr oximat ion 10-6, 11-50, 11-105, 11-187
dit her ing 10-8, 11-50
quant izat ion 10-6, 11-187
r educing number of color s 10-5
color dept h 10-3
color spaces
conver t ing bet ween 1-14, 10-9, 11-94, 11-170,
11-186, 11-189, 11-190, 11-211
HSV 10-10, 11-94
NTSC 10-9, 11-170, 11-189
RGB 10-9
YCbCr 10-10, 11-190, 11-211
colorbar 2-10, 11-37
color map mapping 10-7
color maps
br ight ening 11-15
dar kening 11-15
plot t ing RGB values 11-191
r ear r anging color s 11-32
r educing number of color s 10-8
r emoving duplicat e ent r ies 11-33
column pr ocessing 4-11, 11-35
r eshaping blocks int o columns 11-99
r eshaping columns int o blocks 11-34
comput at ional molecule 5-4
connect ed-component s labeling 8-15, 11-23
cont our plot s 7-7, 11-106
conv2 1-15, 5-3, 11-39, 11-205
convent ions in our document at ion (t able) ix
conver sions bet ween image t ypes 1-13
convmtx2 11-41
convn 1-15, 5-9, 11-42, 11-205
convolut ion
convolut ion mat r ix 11-41
Four ier t r ansfor m 6-12
higher -dimensional 5-9, 11-42
separ abilit y 5-8
t wo-dimensional 5-3, 11-39, 11-63
convolut ion ker nel 5-3
cent er pixel 5-4
coor dinat e syst ems
pixel coor dinat es 1-18
spat ial coor dinat es 1-19
corr2 7-9, 11-43
cor r elat ion 5-7, 11-63
Four ier t r ansfor m 6-13
cor r elat ion coefficient 11-43
cr opping an image 3-7, 11-108
D
dat a t ypes
16-bit int eger s 11-205
8-bit int eger s 1-3, 1-15, 11-203
conver t ing bet ween 1-16, 11-51, 11-203,
11-205
double-pr ecision 1-3, 11-51
summar y of image t ypes and numer ic classes
DC component 6-3
dct2 6-15, 11-44
dctmtx 6-16, 11-47
Index
I-3
dilate 8-6, 11-48
dilat ion 8-4, 11-26, 11-48
closur e 8-7
opening 8-7
discr et e cosine t r ansfor m 6-15, 11-44
image compr ession 6-17
inver se 11-95
t r ansfor m mat r ix 6-16, 11-47
discr et e Four ier t r ansfor m 6-8
display t echniques 2-2, 11-140
adding a color bar 2-10, 11-37
displaying at t r ue size 2-4, 11-202
mult iple images 2-14, 11-200
pr efer ences 2-4
t ext ur e mapping 2-17, 11-207
zooming 2-16, 11-212
dist inct block oper at ions 4-8
over lap 4-9, 11-13
zer o padding 4-8
dither 11-50
dit her ing 10-8, 11-50, 11-187
double 1-16, 11-51
E
edge 7-10, 11-52
edge det ect ion 7-10
met hods 11-53
enhancing images
int ensit y adjust ment 7-14, 11-103
noise r emoval 7-20
erode 8-6, 11-57
er osion 8-4, 11-26, 11-57
Euclidean dist ance 7-3, 11-176
Euler number 8-19, 11-18
F
fan beam pr oject ions 6-27
fast Four ier t r ansfor m 6-8
higher -dimensional 11-61
higher -dimensional inver se 11-97
S ee also Four ier t r ansfor m
t wo-dimensional 11-59
t wo-dimensional inver se 11-96
feat ur e measur ement 7-9, 11-111
binar y images 8-18
fft 6-8
fft2 1-15, 6-8, 11-59, 11-205
fftn 1-15, 6-8, 11-61, 11-205
fftshift 11-62
file for mat s 11-130, 11-142
file size
quer ying 11-118
files
displaying images in 2-8
r eading image dat a fr om 11-130
wr it ing image dat a t o 11-142
filling a r egion 9-8
filt er design 5-13
fr equency sampling met hod 5-15, 11-68
fr equency t r ansfor mat ion met hod 5-14, 11-75
windowing met hod 5-16, 11-78, 11-82
filter2 5-7, 11-63
filt er ed backpr oject ion algor it hm 6-28
filt er s
adapt ive 7-23, 11-209
aver aging 5-10, 11-71
binar y masks 9-6
designing 5-13
Finit e Impulse Response (FIR) 5-13
fr equency r esponse 5-19, 6-11
Infinit e Impulse Response (FIR) 5-14
Laplacian of Gaussian 11-71
Index
I-4
linear 5-3, 7-21, 11-63
median 7-21, 11-165
or der -st at ist ic 11-171
pr edefined t ypes 5-9, 11-71
Pr ewit t 11-71
Sobel 5-11, 11-71
unshar p 11-71
FIR filt er s 5-13
t r ansfor ming fr om one-dimensional t o t wo-di-
mensional 5-14
flood-fill oper at ion 8-13, 11-20
Four ier t r ansfor m 6-3
applicat ions of t he Four ier t r ansfor m 6-11
comput ing fr equency r esponse 6-11
convolut ion 6-12
cor r elat ion 6-13
DC component 6-3
DFT coefficient s 6-9
examples of t r ansfor m on simple shapes 6-7
fast convolut ion of 6-12
fr equency-domain 6-3
higher -dimensional 11-61
higher -dimensional inver se 11-97
r ear r anging out put 11-62
t wo-dimensional 11-59
t wo-dimensional Four ier t r ansfor m 6-3
t wo-dimensional inver se 11-96
freqspace 5-18, 11-65
fr equency r esponse
comput ing 5-19, 6-11, 11-66
desir ed r esponse mat r ix 5-18, 11-65
fr equency sampling met hod (filt er design) 5-15,
11-68
fr equency t r ansfor mat ion met hod (filt er design)
5-14, 11-75
fr equency-domain 6-3
freqz2 5-19, 6-11, 11-66
fsamp2 5-15, 11-68
fspecial 5-9, 11-71
ftrans2 11-75
fwind1 5-17, 11-78
fwind2 5-17, 11-82
G
gamma cor r ect ion 7-16
Gaussian convolut ion ker nel 6-11
Gaussian filt er 11-71
Gaussian noise 7-23
geomet r ic funct ions 3-2
cr opping 3-7, 11-108
int er polat ion 3-3
r esizing 3-5, 11-136
r ot at ion 3-6, 11-138
getimage 11-86
get t ing pr efer ence values 11-152
gr aphics file for mat s
list of for mat s suppor t ed by MATLAB 1-11
gr aphics images 1-12
conver t ing fr om one for mat t o anot her 1-17
r eading fr om file 1-11
r et ur ning file infor mat ion fr om 11-117
S ee also BMP, HDF, J PG, PCX, PNG, TIFF,
XWD
wr it ing t o file 1-12
gray2ind 11-88
gr ayscale 1-13
see also int ensit y images
gr ayscale mor phological oper at ions 11-171
grayslice 11-89
H
HDF 1-11, 11-117, 11-131, 11-143
Index
I-5
appending t o when saving (Wr it eMode)
11-143
bit dept hs suppor t ed when r eading 11-134
bit dept hs suppor t ed when saving 11-147
compr ession 11-143
par amet er s t hat can be set when saving
11-143
r eading wit h special imr ead synt ax 11-133
set t ing J PEG qualit y when saving 11-143
head phant om 6-28
histeq 11-91
hist ogr am equalizat ion 7-18, 11-91
hist ogr ams 7-8, 11-120
Hough t r ansfor m
det ect ing lines 6-23
HSV color space 10-10, 11-94, 11-186
hsv2rgb 10-10, 11-94
I
idct2 11-95
ifft 6-8
ifft2 6-8, 11-96
ifftn 6-8, 11-97
IIR filt er s 5-14
im2bw 1-14, 11-98
im2col 11-99
im2double 1-16, 11-100
im2uint16 1-16, 11-102, 11-102
im2uint8 1-16, 11-101
imadjust 7-14, 11-103
image analysis 7-10
S ee also analyzing images
image ar ea (binar y images) 8-18, 11-16
image class t ypes
conver t ing bet ween 1-13
S ee also dat a t ypes
image enhancement 7-14
S ee also enhancing images
image t ypes 1-4
binar y 1-6, 8-2
indexed 1-4
int ensit y 1-5
mult ifr ame images 1-8
quer ying 11-118
RGB (t r uecolor ) 1-7
S ee also indexed, int ensit y, binar y, RGB,
mult ifr ame
images
analyzing 7-3
color 10-2
color dept h 10-3
conver t ing t o binar y 11-98
dat a t ypes 1-3, 11-51, 11-203, 11-205
displaying 2-2, 11-140
displaying mult iple images 2-14, 11-200
enhancing 7-14
S ee also enhancing images
file for mat s 11-130, 11-142
get t ing dat a fr om axes 11-86
infor mat ion about files 1-12
mean value 11-164
r eading dat a fr om files 11-130
r educing number of color s 10-5, 11-105
RGB 1-7
st andar d deviat ion 11-199
st or ing in MATLAB 1-3
wr it ing t o files 11-142
imapprox 10-8, 11-105
imcontour 7-7, 11-106
imcrop 3-7, 11-108
imfeature 7-9, 8-18, 11-111
imfinfo 1-12
r et ur ning file infor mat ion 11-117
Index
I-6
imhist 7-8, 11-120
immovie 2-13, 11-121
imnoise 7-21, 11-122
impixel 7-3, 11-124
improfile 7-4, 11-127
imread 1-11, 1-15, 11-130
imresize 3-5, 11-136
imrotate 3-6, 11-138
imshow 1-15, 2-3, 11-140
imwrite 1-12, 1-15, 11-142
ind2gray 11-149
ind2rgb 1-14, 11-150
indexed images 11-159
about 1-4
conver t ing fr om int ensit y 11-88
conver t ing fr om RGB 11-187
conver t ing t o int ensit y 11-149
conver t ing t o RGB 11-150
displaying 2-5
r educing number of color s 10-5
Infinit e Impulse Response (IIR) filt er 5-14
infor mat ion
r et ur ning file infor mat ion 11-117
int ensit y adjust ment 7-14, 11-103
gamma cor r ect ion 7-16
hist ogr am equalizat ion 7-18
int ensit y images 11-158
about 1-5
conver t ing fr om indexed 11-149
conver t ing fr om mat r ices 11-163
conver t ing fr om RGB 11-185
conver t ing t o indexed 11-88
displaying 2-5
number of gr ay levels displayed 2-6
int ensit y pr ofiles 7-4, 11-127
int er polat ion 3-3
bicubic 3-3
bilinear 3-3
int ensit y pr ofiles 7-5
near est neighbor 3-3
inver se Radon t r ansfor m 6-25
algor it hm used by t oolbox 6-28
ir adon 6-28
iptgetpref 2-4, 11-151
iptsetpref 2-4, 11-152
iradon 6-25, 11-154
isbw 11-157
isgray 11-158
isind 11-159
isrgb 11-160
J
J PEG compr ession 6-17
J PEG files 1-11, 11-117, 11-131, 11-143
bit dept hs suppor t ed when r eading 11-134
bit dept hs suppor t ed when saving 11-147
par amet er s t hat can be set when saving
11-144
J PEG qualit y
set t ing when wr it ing a J PEG image 11-144
set t ing when wr it ing an HDF image 11-143
L
Laplacian of Gaussian edge det ect or 11-53
Laplacian of Gaussian filt er 11-71
linear filt er ing 4-5, 5-3, 11-63
aver aging filt er 5-10
cent er pixel 5-4
comput at ional molecule 5-4
convolut ion 5-3
convolut ion ker nel 5-3
cor r elat ion 5-7
Index
I-7
filt er design 5-13
FIR filt er s 5-13
IIR filt er s 5-14
noise r emoval 7-21
pr edefined filt er t ypes 5-9
Sobel filt er 5-11
logical ar r ays 1-7, 1-17
logical flag 1-7
lookup-t able oper at ions 8-20, 11-161
M
makelut 8-20, 11-161
masked filt er ing 9-6, 11-195
mat2gray 1-14, 11-163
mat r ices
conver t ing t o int ensit y images 11-163
st or ing images 1-3
McClellan t r ansfor m 11-75
mean2 7-9, 11-164
medfilt2 11-165
medfilt2 7-21
median filt er ing 7-21, 11-165
minimum var iance quant izat ion 10-6, 11-187
Moir pat t er ns 3-5
montage 2-12, 11-167
mor phological oper at ions 8-4, 11-25
cent er pixel 8-4
closur e 8-7, 11-25
diagonal fill 11-26
dilat ion 8-4, 11-26, 11-48
er osion 8-4, 11-26, 11-57
gr ayscale 11-171
opening 8-7, 11-26
pr edefined oper at ions 8-9
r emoving spur pixels 11-27
shr inking object s 11-26
skelet onizing object s 11-26
st r uct ur ing element s 8-4
t hickening object s 11-27
t hinning object s 11-27
movies
cr eat ing fr om images 2-13, 11-121
playing 2-14
mult ifr ame images
about 1-8
displaying 2-11, 2-13, 11-167
limit at ions 1-9
mult ilevel t hr esholding 11-89
N
near est neighbor int er polat ion 3-3
neighbor hoods
binar y image oper at ions 8-2, 8-10, 11-10
neighbor hood oper at ions 4-2
nlfilter 4-6, 11-169
noise r emoval 7-20
adding noise 11-122
Gaussian noise 7-23, 11-122
salt and pepper noise 7-21, 11-122
speckle noise 11-122
nonlinear filt er ing 4-5
NTSC color space 10-9, 11-170, 11-189
ntsc2rgb 10-9, 11-170
O
object select ion 8-16, 11-30
opening 8-7, 11-26
or der -st at ist ic filt er ing 11-171
ordfilt2 11-171
or t honor mal mat r i 6-17
out lier s 7-21
Index
I-8
P
padding bor der s
binar y image oper at ions 8-2
block pr ocessing 4-5
linear filt er ing 5-5
par allel beam pr oject ions 6-26
PCX 1-11, 11-117, 11-131, 11-143
bit dept hs suppor t ed when r eading 11-134
bit dept hs suppor t ed when saving 11-147
per imet er det er minat ion 8-12, 11-29
phantom 6-28, 6-28, 11-173
pixel coor dinat es 1-18
pixel values 7-3, 11-124, 11-176
pixels
definit ion 1-3
pixval 7-3, 11-176
plot t ing color map values 11-191
PNG 1-11
bit dept hs suppor t ed when r eading 11-134
bit dept hs suppor t ed when saving 11-147
int er lace t ype 11-145
par amet er s t hat can be set when saving
11-144
r eading wit h special imr ead synt ax 11-131
set t ing alpha channel when saving 11-146
set t ing backgr ound color when saving 11-146
set t ing chr omat icit ies value when saving
11-146
set t ing gamma value when saving 11-146
set t ing r esolut ion of when saving 11-146
set t ing significant bit s when saving 11-146
set t ing t r anspar ency pixel value when wr it ing
11-145
wr it ing as 16-bit using imwr it e 1-12
pr efer ences 2-4
get t ing values 11-152
set t ing values 11-151
Pr ewit t edge det ect or 11-53
Pr ewit t filt er 11-71
pr oject ions
fan beam 6-27
par allel beam 6-26
Q
qtdecomp 7-11, 11-177
qtgetblk 11-180
qtsetblk 11-182
quadt r ee decomposit ion 7-11, 11-177
get t ing block values 11-180
set t ing block values 11-182
quant izat ion
minimum var iance quant izat ion 10-6, 11-187
unifor m quant izat ion 10-6, 11-187
R
radon 6-19, 6-25, 11-183
Radon t r ansfor m 6-19, 11-183
det ect ing lines 6-23
inver se 11-154
inver se Radon t r ansfor m 6-25
of t he Shepp-Logan Head phant om 6-30
r eal or t honor mal mat r ix 6-17
r egion of int er est
binar y masks 9-3
filling 9-8, 11-193
filt er ing 9-6, 11-195
select ing 9-3, 9-5, 11-192, 11-197
r esizing images 3-5, 11-136
ant i-aliasing 3-5
RGB images 11-160
about 1-7
conver t ing fr om indexed 11-150
Index
I-9
conver t ing t o indexed 11-187
conver t ing t o int ensit y 11-185
displaying 2-7
r educing number of color s 10-5
rgb2gray 1-14, 11-185
rgb2hsv 10-10, 11-186
rgb2ind 1-14, 10-6, 11-187
rgb2ntsc 10-9, 11-189
rgb2ycbcr 10-10
rgbplot 11-191
Rober t s edge det ect or 11-53
roicolor 9-5, 11-192
roifill 9-8, 11-193
roifilt2 9-6, 11-195
roipoly 9-3, 9-5, 11-197
r ot at ing an image 3-6, 11-138
S
salt and pepper noise 7-21
separ abilit y in convolut ion 5-8
set t ing pr efer ence values 11-151
Shepp-Logan head phant om 6-28
Signal Pr ocessing Toolbox
hamming funct ion 5-17
sinusoids 6-3
skelet onizat ion 8-9
sliding neighbor hood oper at ions 4-4, 11-169
Sobel edge det ect or 11-53
Sobel filt er 5-11, 11-71
spat ial coor dinat es 1-19
std2 7-9, 11-199
st r uct ur ing element s 8-4
cent er pixel 8-4
subimage 2-15, 2-16, 11-200
subplot 2-15, 2-15
sum 1-15, 11-205
T
t emplat e mat ching 6-13
t ext ur e mapping 2-17, 11-207
t hr esholding 11-89, 11-98
TIFF 1-11, 11-117, 11-131, 11-143
bit dept hs suppor t ed when r eading 11-134
bit dept hs suppor t ed when saving 11-147
compr ession 11-144
par amet er s t hat can be set when saving
11-144
r eading wit h special imr ead synt ax 11-131
r esolut ion 11-144
t omogr aphy 6-25
t r ansfor mat ion mat r ix 5-14
t r ansfor ms 6-2
discr et e cosine 6-15, 11-44
discr et e Four ier t r ansfor m 6-8
Four ier 6-3, 11-59, 11-61, 11-62
inver se discr et e cosine 11-95
inver se Four ier 11-96, 11-97
inver se Radon 6-25, 11-154
Radon 6-19, 11-183
t wo-dimensional Four ier t r ansfor m 6-3
t r anspar ency 11-132
t r anspar ency chunk 11-131
t r uecolor images
about 1-7
truesize 11-202
U
uint16 11-205
uint16 ar r ays
suppor t ed oper at ions 11-205
uint8 11-203
uint8 ar r ays
st or ing images 1-3
Index
I-10
suppor t ed oper at ions 1-15, 11-203
unifor m quant izat ion 10-6, 11-187
unshar p filt er 11-71
W
warp 2-17, 11-207
wiener2 7-23, 11-209
windowing met hod (filt er design) 5-16, 11-78,
11-82
X
X-r ay absor pt ion t omogr aphy 6-25
XWD 1-11, 11-117, 11-131, 11-143
bit dept hs suppor t ed when r eading 11-134
bit dept hs suppor t ed when saving 11-147
Y
YCbCr color space 10-10, 11-190, 11-211
ycbcr2rgb 10-10
Z
zer o-cr oss edge det ect or 11-53
zoom 2-16, 11-212
zooming in 2-16, 11-212
Index
I-11
Index
I-12

You might also like