MATLAB Practice PDF
MATLAB Practice PDF
Budapest Tech
MATLAB p. 1/333
Contents
1. Fundamentals
2. MATLAB Graphics
3. Intensity Transformations and Spatial Filtering
4. Frequency Domain Processing
5. Edge Detection
6. Morphological Image Processing
7. Color Image Processing
MATLAB p. 2/333
Chapter 1
Fundamentals
MATLAB p. 3/333
Content
Digital Image Representation
Reading Images
Displaying Images
Writing Images
Data Classes
Image Types
Converting between Data Classes and Image Types
Array Indexing
Some Important Standard Arrays
Introduction to M-Function Programming
MATLAB p. 4/333
Digital Image Representation
An image may be defined as a two-dimensional function,
f (x, y),
MATLAB p. 5/333
Coordinate Conventions
MATLAB p. 7/333
Reading Images
imread(filename)
Some examples:
f=imread(chestxray.jpg);
f=imread(D:\myimages\chestxray.jpg);
f=imread(.\myimages\chestxray.jpg);
MATLAB p. 8/333
Supported Image Formats
MATLAB p. 9/333
size function
size(imagematrix)
>> size(f)
ans =
494 600
>> [M,N]=size(f);
>> whos f
Name Size Bytes Class
f 494x600 296400 uint8 array
Grand total is 296400 elements using 296400 bytes
MATLAB p. 10/333
Displaying Images
imshow(f,G)
imshow(f, [low,high]) displays as black all
values less than or equal to low, and as white all
values greater than or equal to high.
imshow(f, []) sets variable low to the minimum
value of array f and high to its maximum value.
MATLAB p. 11/333
Displaying Images
An image with low dinamic range using by imshow(f),
and the result of scaling by using imshow(f, []).
MATLAB p. 12/333
Displaying Images
>> f=imread(rose_512.tif);
>> imshow(f)
MATLAB p. 13/333
Displaying Images
>> f=imread(rose_512.tif);
>> g=imread(cktboard.tif);
>> imshow(f), figure, imshow(g)
MATLAB p. 14/333
Writing Images
imwrite(f, filename)
imwrite(f, patient10_run1, tif)
imwrite(f, patient10_run1.tif)
MATLAB p. 15/333
Writing Images
q = 100 q = 50 q = 25
q = 15 q=5 q=0
MATLAB p. 16/333
Writing Images
imfinfo filename
>> imfinfo bubbles25.jpg
ans =
Filename: bubbles25.jpg
FileModDate: 02-Feb-2005 09:34:50
FileSize: 13354
Format: jpg
FormatVersion:
Width: 720
Height: 688
BitDepth: 8
ColorType: grayscale
FormatSignature:
NumberOfSamples: 1
CodingMethod: Huffman
CodingProcess: Sequential
Comment: {}
MATLAB p. 17/333
Writing Images
>> K=imfinfo(bubbles25.jpg);
>> image_bytes=K.Width*K.Height*K.BitDepth/8;
>> compressed_bytes=K.FileSize;
>> compression_ratio=image_bytes/compressed_bytes
compression_ratio =
37.0945
MATLAB p. 18/333
Writing Images
imwrite(g, filename.tif, ...
compression, parameter, ...
resolution, [colres rowres])
MATLAB p. 19/333
Writing Images
>> f=imread(cktboard.tif);
>> res=round(200*2.25/1.5);
>> imwrite(f, sf.tif, compression, ...
none, resolution, res)
MATLAB p. 20/333
Writing Images
MATLAB p. 21/333
Data Classes
Name Description
double Double-precision, floating-point numbers in the approximate range
10308 to 10308 (8 bytes per element).
uint8 Unsigned 8-bit integers in the range [0,255] (1 byte per element).
uint16 Unsigned 16-bit integers in the range [0,65535] (2 bytes per element).
uint32 Unsigned 32-bit integers in the range [0,4294967295] (4 bytes per ele-
ment).
int8 Signed 8-bit integers in the range [-128,127] (1 byte per element).
int16 Signed 16-bit integers in the range [-32768,32767] (2 bytes per element).
int32 Signed 32-bit integers in the range [-2147483648,2147483647] (4 bytes
per element).
single Single-precision floating-point numbers with values in the approximate
range 1038 to 1038 (4 bytes per element).
char Characters (2 bytes per element).
logical Values are 0 or 1 (1 byte per element).
MATLAB p. 22/333
Image Types
Intensity images
Binary images
Indexed images
RGB images
MATLAB p. 23/333
Intensity Images
An intensity image is a data matrix whose values have
been scaled to represent intensities. When the elements of
an intensity image are of class uint8, or class uint16,
they have integer values in the range [0,255] and
[0,65535], respectively. If the image is of class double, the
values are floating-point numbers. Values of scaled, class
double intensity images are in the range [0,1] by
convention.
MATLAB p. 24/333
Binary Images
A binary image is a logical array of 0s and 1s.
MATLAB p. 25/333
Converting between Data Classes
B=data_class_name(A)
MATLAB p. 26/333
Converting between Image Classes and Types
MATLAB p. 27/333
Converting between Image Classes and Types
f =
-0.5000 0.5000
0.7500 1.5000
>> g=im2uint8(f)
g =
0 128
191 255
MATLAB p. 28/333
Converting between Image Classes and Types
>> A=randn(252);
>> B=mat2gray(A);
>> subplot(1,3,1), imshow(A), ...
subplot(1,3,2), imshow(A, []), ...
subplot(1,3,3), imshow(B)
MATLAB p. 29/333
Converting between Image Classes and Types
g =
0.0980 0.1961
0.5020 0.7843
MATLAB p. 30/333
Converting between Image Classes and Types
>> f=[1 2; 3 4];
>> g=mat2gray(f)
g =
0 0.3333
0.6667 1.0000
gb =
0 0
1 1
MATLAB p. 31/333
Converting between Image Classes and Types
>> gb=f>2
gb =
0 0
1 1
>> gbv=islogical(gb)
gbv =
MATLAB p. 32/333
Array Indexing
Vector Indexing
Matrix Indexing
Selecting Array Dimensions
MATLAB p. 33/333
Vector Indexing
>> v=[1 3 5 7 9]
v =
1 3 5 7 9
>> v(2)
ans =
3
>> w=v.
w =
1
3
5
7
9
MATLAB p. 34/333
Vector Indexing
>> v(1:3)
ans =
1 3 5
>> v(2:4)
ans =
3 5 7
>> v(3:end)
ans =
5 7 9
MATLAB p. 35/333
Vector Indexing
>> v(:)
ans =
1
3
5
7
9
>> v(1:2:end)
ans =
1 5 9
>> v(end:-2:1)
ans =
9 5 1
MATLAB p. 36/333
Vector Indexing
linspace(a, b, n)
>> x=linspace(1,5,3)
x =
1 3 5
>> v(x)
ans =
1 5 9
ans =
1 7 9
MATLAB p. 37/333
Matrix Indexing
>> A=[1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9
>> A(2,3)
ans =
6
MATLAB p. 38/333
Matrix Indexing
>> C3=A(:,3)
C3 =
3
6
9
>> R2=A(2,:)
R2 =
4 5 6
>> T2=A(1:2,1:3)
T2 =
1 2 3
4 5 6
MATLAB p. 39/333
Matrix Indexing
>> B=A;
>> B(:,3)=0
B =
1 2 0
4 5 0
7 8 0
MATLAB p. 40/333
Matrix Indexing
>> A(end,end)
ans =
9
>> A(end,end-2)
ans =
7
>> A(2:end,end:-2:1)
ans =
6 4
9 7
MATLAB p. 41/333
Matrix Indexing
>> D=logical([1 0 0; 0 0 1; 0 0 0])
D =
1 0 0
0 0 1
0 0 0
>> A(D)
ans =
1
6
MATLAB p. 42/333
Matrix Indexing
>> v=T2(:)
v =
1
4
2
5
3
6
MATLAB p. 43/333
Matrix Indexing
>> s=sum(A(:))
s =
45
>> s1=sum(A)
s1 =
12 15 18
>> s2=sum(sum(A))
s2 =
45
MATLAB p. 44/333
Matrix Indexing
>> f=imread(rose.tif);
>> fp=f(end:-1:1,:);
MATLAB p. 45/333
Matrix Indexing
>> fc=f(257:768,257:768);
MATLAB p. 46/333
Matrix Indexing
>> fs=f(1:8:end,1:8:end);
MATLAB p. 47/333
Matrix Indexing
>> plot(f(512,:))
MATLAB p. 48/333
Selecting Array Dimensions
operation(A, dim)
where operation denotes an applicable MATLAB
operation, A is an array and dim is a scalar.
>> k=size(A,1);
gives the size of A along its first dimension.
MATLAB p. 50/333
Some Important Standard Arrays
>> A=5*ones(3)
A =
5 5 5
5 5 5
5 5 5
>> magic(3)
ans =
8 1 6
3 5 7
4 9 2
>> B=rand(2,4)
B =
0.9501 0.6068 0.8913 0.4565
0.2311 0.4860 0.7621 0.0185
MATLAB p. 51/333
M-Function Programming
M-Files
Operators
Flow Control
Code Optimization
Interactive I/O
Cell Arrays and Structures
MATLAB p. 52/333
M-Files
M-Files in MATLAB can be
scriptsthat simply execute a series of MATLAB
statements, or they can be
functionsthat can accept argumens and can produce one
or more outputs.
MATLAB p. 53/333
M-Files
The components of a function M-file are
The function definition line
The H1 line
Help text
The function body
Comments
MATLAB p. 54/333
M-Files
function [G,x] = planerot(x)
%PLANEROT Givens plane rotation.
% [G,Y] = PLANEROT(X), where X is a 2-component column vector,
% returns a 2-by-2 orthogonal matrix G so that Y=G*X has Y(2)=0.
%
% Class support for input X:
% float: double, single
if x(2) = 0
r = norm(x);
G = [x; -x(2) x(1)]/r;
x = [r; 0];
else
G = eye(2,class(x));
end
MATLAB p. 55/333
Operators
Arithmetic Operators
Relational Operators
Logical Operators and Functions
MATLAB p. 56/333
Arithmetic Operators
MATLAB p. 57/333
Arithmetic Operators
MATLAB p. 58/333
Arithmetic Operators
MATLAB p. 59/333
Arithmetic Operators
MATLAB p. 60/333
Image Arithmetic Functions
Function Description
imadd Adds two images; or adds a constant to an image.
imsubtract Subtracts two images; or subtracts a constant from an image.
immultiply Multiplies two image, where the multiplication is carried out be-
tween pairs of corresponding image elements; or multiplies a con-
stant times an image.
imdivide Divides two images, where the division is carried out between
pairs of corresponding image elements; or divides an image by
a constant.
imabsdiff Computes the absolute difference between two images.
imcomplement Complements an image.
imlincomb Computes a linear combination of two or more images.
MATLAB p. 61/333
An Example
function [p,pmax,pmin,pn]=improd(f,g)
%IMPROD Computes the product of two images.
% [P,PMAX,PMIN,PN]=IMPROD(F,G) outputs the
% element-by-element product of two images,
% F and G, the product maximum and minimum
% values, and a normalized product array with
% values in the range [0,1]. The input images
% must be of the same size. They can be of
% class uint8, uint 16, or double. The outputs
% are of class double.
MATLAB p. 62/333
An Example
fd=double(f);
gd=double(g);
p=fd.*gd;
pmax=max(p(:));
pmin=min(p(:));
pn=mat2gray(p);
MATLAB p. 63/333
An Example
>> f=[1 2;3 4]; g=[1 2;2 1];
>> [p,pmax,pmin,pn]=improd(f,g)
p =
1 4
6 4
pmax =
6
pmin =
1
pn =
0 0.6000
1.0000 0.6000
MATLAB p. 64/333
An Example
>> help improd
IMPROD Computes the product of two images.
[P,PMAX,PMIN,PN]=IMPROD(F,G) outputs the
element-by-element product of two images,
F and G, the product maximum and minimum
values, and a normalized product array with
values in the range [0,1]. The input images
must be of the same size. They can be of
class uint8, uint 16, or double. The outputs
are of class double.
MATLAB p. 65/333
Some Words about max
C=max(A) If A is a vector, max(A) returns its largest element; if A is a
matrix, then max(A) treats the columns of A as vectors and
returns a row vector containing the maximum element from
each column.
C=max(A,B) Returns an array the same size as A and B with the largest
elements taken from A or B.
C=max(A,[ ],dim) Returns the largest elements along the dimension of A spec-
ified by dim.
[C,I]=max(...) Finds the indices of the maximum values of A, and returns
them in output vector I. If there are several identical maxi-
mum values, the index of the first one found is returned. The
dots indicate the syntax used on the right of any of the previ-
ous three forms.
MATLAB p. 66/333
Relational Operations
Operator Name
< Less than
<= Less than or equal to
> Greater than
>= Greater than of equal to
== Equal to
~= Not equal to
MATLAB p. 67/333
Relational Operators
>> A=[1 2 3;4 5 6;7 8 9];
>> B=[0 2 4;3 5 6;3 4 9];
>> A==B
ans =
0 1 0
0 1 1
0 0 1
>> A>=B
ans =
1 1 0
1 1 1
1 1 1
MATLAB p. 68/333
Logical Operators
Operator Name
& AND
| OR
NOT
MATLAB p. 69/333
Logical Operators
>> A=[1 2 0;0 4 5];
>> B=[1 -2 3;0 1 1];
>> A&B
ans =
1 1 0
0 1 1
MATLAB p. 70/333
Logical Functions
Function Comments
xor The xor function returns a 1 only if both operands are
logically different; otherwise xor returns a 0.
all The all function returns a 1 if all the elements in a vec-
tor are nonzero; otherwise all returns a 0. This function
operates columnwise on matrices.
any The any function returns a 1 if any of the elements in
a vector is nonzero; otherwise any returns a 0. This
function operates columnwise on matrices.
MATLAB p. 71/333
Logical Functions
>> A=[1 2 3;4 5 6];
>> B=[0 -1 1;0 0 1];
>> xor(A,B)
ans =
1 0 0
1 1 0
>> all(A)
ans =
1 1 1
>> any(A)
ans =
1 1 1
>> all(B)
ans =
0 0 1
>> any(B)
ans =
0 1 1
MATLAB p. 72/333
Logical Functions
Function Description
iscell(C) True if C is a cell array.
iscellstr(s) True if s is a cell array of strings.
ischar(s) True if s is a character string.
isempty(A) True if A is the empty array,[].
isequal(A,B) True if A and B have identical elements and dimensions.
isfield(S,name) True if name is a field of structure S.
isfinite(A) True in the locations of array A that are finite.
isinf(A) True in the locations of array A that are infinite.
isletter(A) True in the locations of A that are letters of the alphabet.
MATLAB p. 73/333
Logical Functions
Function Description
islogical(A) True if A is a logical array.
ismember(A,B) True in locations where elements of A are also in B.
isnan(A) True in the locations of A that are NaNs.
isnumeric(A) True if A is a numeric array.
isprime(A) True in locations of A that are prime numbers.
isreal(A) True if the elements of A have no imaginary parts.
isspace(A) True at locations where the elements of A are whitespace char-
acters.
issparse(A) True if A is a sparse matrix.
isstruct(A) True if S is a structure.
MATLAB p. 74/333
Some Important Variables and Constants
MATLAB p. 75/333
Flow Control
Statement Description
if if, together with else and elseif, executes a group of state-
ments based on a specified logical condition.
for Executes a group of statements a fixed (specified) number of times.
while Executes a group of statements an indefinite number of times,
based on a specified logical condition.
break Terminates execution of a for or while loop.
continue Passes control to the next iteration of a for or while loop, skipping
any remaining statements in the body of the loop.
switch switch, together with case and otherwise, executes different
groups of statements, depending on a specified value or string.
return Causes execution to return to the invoking function.
try...catch Changes flow control if an error is detected during execution.
MATLAB p. 76/333
if, else, and elseif
if expression
statements
end
if expression1
statements1
elseif expression2
statements2
else
statements3
end
MATLAB p. 77/333
if, else, and elseif
function av=average(A)
%AVERAGE Computes the average value of an array.
% AV=AVERAGE(A) computes the average value of
% input array, A, which must be a 1-D or 2-D
% array.
MATLAB p. 78/333
for
for index=start:increment:end
statements
end
MATLAB p. 79/333
for
count=0;
for k=0:0.1:1
count=count+1;
end
MATLAB p. 80/333
for
for q=0:5:100
filename=sprintf(series_%3d.jpg,q);
imwrite(f,filename,quality,q);
end
MATLAB p. 81/333
for
function s=subim(f,m,n,rx,cy)
%SUBIM Extracts a subimage, s, from a given image, f.
% The subimage is of size m-by-n, and the coordinates
% of its top, left corner are (rx,cy).
s=zeros(m,n);
rowhigh=rx+m-1;
colhigh=cy+n-1;
xcount=0;
for r=rx:rowhigh
xcount=xcount+1;
ycount=0;
for c=cy:colhigh
ycount=ycount+1;
s(xcount,ycount)=f(r,c);
end
end
MATLAB p. 82/333
while
while expression
statements
end
MATLAB p. 83/333
while
a=10;
b=5;
while a
a=a-1;
while b
b=b-1;
end
end
MATLAB p. 84/333
break
fid = fopen(fft.m,r);
s = ;
while feof(fid)
line = fgetl(fid);
if isempty(line)
break
end
s = strvcat(s,line);
end
disp(s)
MATLAB p. 85/333
continue
fid = fopen(magic.m,r);
count = 0;
while feof(fid)
line = fgetl(fid);
if isempty(line) | strncmp(line,%,1)
continue
end
count = count + 1;
end
disp(sprintf(%d lines,count));
MATLAB p. 86/333
switch
switch switch_expression
case case_expression
statement(s)
case {case_expression1, case_expression2,. . . }
statement(s)
otherwise
statement(s)
end
MATLAB p. 87/333
switch
switch newclass
case uint8
g=im2uint8(f);
case uint16
g=im2uint16(f);
case double
g=im2double(f);
otherwise
error(Unknown or improper image class.)
end
MATLAB p. 88/333
return
function d = det(A)
%DET det(A) is the determinant of A.
if isempty(A)
d = 1;
return
else
...
end
MATLAB p. 89/333
try...catch
function matrix_multiply(A, B)
try
A * B
catch
errmsg = lasterr;
if(strfind(errmsg, Inner matrix dimensions))
disp(** Wrong dimensions for matrix
multiplication)
elseif(strfind(errmsg, not defined for variables
of class))
disp(** Both arguments must be double matrices)
end
end
MATLAB p. 90/333
Code Optimization
Vectorizing Loops
Preallocating Arrays
MATLAB p. 91/333
Vectorizing Loops
Vectorizing simply means converting for and while loops
to equivalent vector or matrix operations.
MATLAB p. 92/333
A Simple Example
Suppose that we want to generate a 1-D function of the
form
f (x) = A sin(x/2)
for x = 0, 1, 2, . . . , M 1.
function [rt,f,g]=twodsin(A,u0,v0,M,N)
%TWODSIN Compares for loops vs. vectorization.
% The comparison is based on implementing the function
% f(x,y)=Asin(u0x+v0y) for x=0,1,2,...,M-1 and
% y=0,1,2,...,N-1. The inputs to the function are
% M and N and the constants in the function.
MATLAB p. 95/333
Comparison for loops vs. vectorization
for r=1:M
u0x=u0*(r-1);
for c=1:N
v0y=v0*(c-1);
f(r,c)=A*sin(u0x+v0y);
end
end
MATLAB p. 96/333
Comparison for loops vs. vectorization
%Now implement using vectorization. Call the image g.
r=0:M-1;
c=0:N-1;
[C,R]=meshgrid(c,r);
g=A*sin(u0*R+v0*C);
MATLAB p. 97/333
Comparison for loops vs. vectorization
>> [rt,f,g]=twodsin(1,1/(4*pi),1/(4*pi),512,512);
>> rt
rt =
19.5833
>> g=mat2gray(g);
>> imshow(g)
MATLAB p. 98/333
Preallocating Arrays
tic
for i=1:1024
for j=1:1024
f(i,j)=i+2*j;
end
end
toc
Elapsed time is 30.484000 seconds.
tic
g=zeros(1024); %Preallocation
for i=1:1024
for j=1:1024
g(i,j)=i+2*j;
end
end
toc
Elapsed time is 0.221000 seconds.
MATLAB p. 99/333
Interactive I/O
disp(argument)
>> A=[1 2;3 4];
>> disp(A)
1 2
3 4
MATLAB p. 100/333
Interactive I/O
t=input(message)
t=input(messages,s)
>> t=input(Enter your data: ,s)
Enter your data: 1, 2, 4
t =
1, 2, 4
>> class(t)
ans =
char
>> size(t)
ans =
1 7
MATLAB p. 101/333
Interactive I/O
>> n=str2num(t)
n =
1 2 4
>> size(n)
ans =
1 3
>> class(n)
ans =
double
MATLAB p. 102/333
Interactive I/O
[a,b,c,...]=strread(cstr,format,...
param,value)
MATLAB p. 103/333
Save variables on disk
save(filename, -struct, s)
saves all fields of the scalar structure s as individual
variables within the file filename.mat.
MATLAB p. 104/333
Load variables from disk
load(filename)
loads all the variables from filename.mat.
load(filename, X, Y, Z)
loads just the specified variables from the MAT-file.
S=load(...)
returns the contents of a MAT-file in the variable S. S is a
struct containing fields that match the variables retrieved.
MATLAB p. 105/333
Display directory listing
files=dir(match)
returns the list of files with name match in the current
directory to an m-by-1 structure with the fields
name: Filename
date: Modification date
bytes: Number of bytes allocated to the file
isdir: 1 if name is a directory; 0 if not
MATLAB p. 106/333
Cell Arrays
Cell array is a multidimensional array whose elements are
copies of other arrays.
MATLAB p. 107/333
Pass or return variable numbers of arguments
function varargout = foo(n)
returns a variable number of arguments from function
foo.m.
function y = bar(varargin)
accepts a variable number of arguments into function
bar.m.
>> S.char_string=gauss;
>> S.matrix=[1 0;1 0];
>> S.scalar=3;
>> S
S =
char_string: gauss
matrix: [2x2 double]
scalar: 3
>> S.matrix
ans =
1 0
1 0
MATLAB p. 109/333
Chapter 2
MATLAB Graphics
MATLAB p. 110/333
Plotting Your Data
>> x=0:0.2:12;
>> y1=bessel(1,x);
>> y2=bessel(2,x);
>> y3=bessel(3,x);
>> h=plot(x,y1,x,y2,x,y3);
>> set(h,LineWidth,2,{LineStyle},{--;:;-.})
>> set(h,{Color},{r;g;b})
>> axis([0 12 -0.5 1])
>> grid on
>> xlabel(Time)
>> ylabel(Amplitude)
>> legend(h,First,Second,Third)
>> title(Bessel Functions)
>> [y,ix]=min(y1);
>> text(x(ix),y,First Min \rightarrow,...
HorizontalAlignment,right)
>> print -depsc -tiff -r200 myplot
MATLAB p. 111/333
Plotting Your Data
Bessel Functions
1
First
Second
Third
0.5
Amplitude
First Min
0.5
0 2 4 6 8 10 12
Time
MATLAB p. 112/333
Creating Plots
>> t=0:pi/100:2*pi;
>> y=sin(t);
>> plot(t,y) 1
0.6
0.4
0.2
0.2
0.4
0.6
0.8
1
0 1 2 3 4 5 6 7
MATLAB p. 113/333
Creating Plots
>> y2=sin(t-0.25);
>> y3=sin(t-0.5);
>> plot(t,y,t,y2,t,y3) 1
0.8
0.6
0.4
0.2
0.2
0.4
0.6
0.8
1
0 1 2 3 4 5 6 7
MATLAB p. 114/333
Specifying Line Style
>> plot(t,y,-,t,y2,--,t,y3,:)
0.8
0.6
0.4
0.2
0.2
0.4
0.6
0.8
1
0 1 2 3 4 5 6 7
MATLAB p. 115/333
Specifying the Color and Size of Lines
>> x=-pi:pi/10:pi;
>> y=tan(sin(x))-sin(tan(x));
>> plot(x,y,--rs,LineWidth,2,...
MarkerEdgeColor,k,...
MarkerFaceColor,g,...
MarkerSize,10)
3
4 3 2 1 0 1 2 3 4
MATLAB p. 116/333
Adding Plots to an Existing Graph
>> semilogx(1:100,+)
>> hold on
>> plot(1:3:300,1:100,--)
>> hold off
100
90
80
70
60
50
40
30
20
10
0
0 1 2 3
10 10 10 10
MATLAB p. 117/333
Plotting Only the Data Points
>> x=0:pi/15:4*pi;
>> y=exp(2*cos(x));
8
>> plot(x,y,r+)
7
0
0 2 4 6 8 10 12 14
MATLAB p. 118/333
Plotting Markers and Lines
>> x=0:pi/15:4*pi;
>> y=exp(2*cos(x));
>> plot(x,y,-r,x,y,ok)
0
0 2 4 6 8 10 12 14
MATLAB p. 119/333
Line Plots of Matrix Data
>> Z=peaks;
>> plot(Z)
10
8
0 5 10 15 20 25 30 35 40 45 50
MATLAB p. 120/333
Plotting with Two Y-Axes
>> t=0:pi/20:2*pi;
>> y=exp(sin(t));
>> plotyy(t,y,t,y,plot,stem)
3 3
2.5 2.5
2 2
1.5 1.5
1 1
0.5 0.5
0 0
0 1 2 3 4 5 6 7
MATLAB p. 121/333
Combining Linear and Logarithmic Axes
>> t=0:900;
>> A=1000;
>> a=0.005;
>> b=0.005;
>> z1=A*exp(-a*t);
>> z2=sin(b*t);
>> [haxes,hline1,hline2]=plotyy(t,z1,t,z2,semilogy,plot);
>> axes(haxes(1))
>> ylabel(Semilog Plot)
>> axes(haxes(2))
>> ylabel(Linear Plot)
>> set(hline2,LineStyle,--)
MATLAB p. 122/333
Combining Linear and Logarithmic Axes
3
10 1
0.8
0.6
0.4
0.2
Semilog Plot
Linear Plot
2
10 0
0.2
0.4
0.6
0.8
1
10 1
0 100 200 300 400 500 600 700 800 900
MATLAB p. 123/333
Specifying Ticks and Tick Labels
>> x=-pi:.1:pi;
>> y=sin(x);
>> plot(x,y)
>> set(gca,XTick,-pi:pi/2:pi)
>> set(gca,XTickLabel,{-pi,-pi/2,0,pi/2,pi})
>> xlabel(-\pi \leq \Theta \leq \pi)
>> ylabel(sin(\Theta))
>> title(Plot of sin(\Theta))
>> text(-pi/4,sin(-pi/4),\leftarrow sin(-\pi\div4),...
HorizontalAlignment,left)
MATLAB p. 124/333
Specifying Ticks and Tick Labels
Plot of sin()
1
0.8
0.6
0.4
0.2
sin()
0.2
0.4
0.6
sin(4)
0.8
1
pi pi/2 0 pi/2 pi
MATLAB p. 125/333
Setting Line Properties on an Existing Plot
Plot of sin()
1
0.8
0.6
0.4
0.2
sin()
0.2
0.4
0.6
sin(4)
0.8
1
pi pi/2 0 pi/2 pi
MATLAB p. 126/333
Chapter 3
Intensity Transformations
and Spatial Filtering
MATLAB p. 127/333
Content
Background
Intensity Transformation Functions
Histogram Processing and Function Plotting
Spatial Filtering
Image Processing Toolbox Standard Spatial Filters
MATLAB p. 128/333
Background
The spatial domain processes are denoted by the
expression
g(x, y) = T [f (x, y)]
where f (x, y) is the input image, g(x, y) is the output
(processed) image, and T is an operator on f , defined over
a specified neighborhood about point (x, y).
MATLAB p. 129/333
Intensity Transformation Functions
The simplest form of the transformation T is when the
neighborhood is of size 1 1 (a single pixel). In this case,
the value of g at (x, y) depends only on the intensity of f at
that point, and T becomes an intensity or gray-level
transformation function.
MATLAB p. 130/333
Function imadjust
g=imadjust(f,[low_in high_in],...
[low_out high_out],gamma)
MATLAB p. 131/333
Function imadjust
>> f=imread(breast.tif);
MATLAB p. 132/333
Function imadjust
>> g1=imadjust(f,[0 1],[1 0]);
MATLAB p. 133/333
Function imadjust
>> g2=imadjust(f,[0.5 0.75],[0 1]);
MATLAB p. 134/333
Function imadjust
>> g3=imadjust(f,[],[],2);
MATLAB p. 135/333
Histogram Processing and Function Plotting
MATLAB p. 136/333
Generating and Plotting Image Histograms
The histogram of a digital image with L total possible
intensity levels in the range [0, G] is defined as the discrete
function
h(rk ) = nk
where rk is the kth intensity level in the interval [0, G] and
nk is the number of pixels in the image whose intensity
level is rk . The value of G is 255 for images of class
uint8, 65535 for images of class uint16, and 1.0 for
images of class double. Keep in mind that indices in
MATLAB cannot be 0, so r1 corresponds to intensity level
0, r2 corresponds to intensity level 1, and so on, with rL
corresponding to level G. Note also that G = L 1 for
images of class uint8 and uint16.
MATLAB p. 137/333
Generating and Plotting Image Histograms
h(rk ) nk
p(rk ) = =
n n
for k = 1, 2, . . . , L.
MATLAB p. 138/333
Generating and Plotting Image Histograms
h=imhist(f,b)
where f is the input image, h is its histogram, h(rk ), and b
is the number of bins used in forming the histogram (if b is
not included in the argument, b=256 is used by default). A
bin is simply a subdivision of the intensity scale. For
example, if we are working with uint8 images and we let
b=2, then the intensity scale is subdivided into two ranges:
0 to 127 and 128 to 255. The resulting histogram will have
two values: h(1) equal to the number of pixels in the
image with values in the interval [0, 127], and h(2) equal to
the number of pixels with values in the interval [128, 255].
MATLAB p. 139/333
Generating and Plotting Image Histograms
>> f=imread(breast.tif);
>> imshow(f), imhist(f)
MATLAB p. 140/333
Generating and Plotting Image Histograms
>> h=imhist(f);
>> h1=h(1:10:256);
>> horz=1:10:256;
>> bar(horz,h1)
>> axis([0 255 0 15000])
>> set(gca,xtick,0:50:255)
>> set(gca,ytick,0:2000:15000)
MATLAB p. 141/333
Generating and Plotting Image Histograms
>> h=imhist(f);
>> h1=h(1:10:256);
>> horz=1:10:256;
>> stem(horz,h1,fill)
>> axis([0 255 0 15000])
>> set(gca,xtick,0:50:255)
>> set(gca,ytick,0:2000:15000)
MATLAB p. 142/333
Generating and Plotting Image Histograms
>> h=imhist(f);
>> plot(h)
>> axis([0 255 0 15000])
>> set(gca,xtick,0:50:255)
>> set(gca,ytick,0:2000:15000)
MATLAB p. 143/333
Some Useful Plotting Function
plot(horz,v,color_linestyle_marker)
bar(horz,v,width)
stem(horz,v,color_linestyle_marker,fill)
axis([horzmin horzmax vertmin vertmax])
xlabel(text string,fontsize,size)
ylabel(text string,fontsize,size)
text(xloc,yloc,text string,fontsize,size)
title(titlestring)
MATLAB p. 144/333
Some Useful Plotting Function
MATLAB p. 145/333
Histogram Equalization
k
X nj
sk = k = 0, 1, 2, . . . , L 1
j=0
n
MATLAB p. 146/333
Histogram Equalization
g=histeq(f,nlev)
where f is the input image and nlev is the number of
intensity levels specified for the output image. If nlev is
equal to L (the total number of possible levels in the input
image), then histeq implements the transformation
function (described on the previous slide), directly. If nlev
is less than L, then histeq attempts to distribute the
levels so that they will approximate a flat histogram. Unlike
imhist, the default value in histeq is nlev=64.
MATLAB p. 147/333
Histogram Equalization
>> f=imread(pollen.tif);
>> imshow(f)
>> figure, imhist(f)
>> ylim(auto)
>> g=histeq(f,256);
>> figure, imshow(g)
>> figure, imhist(g)
>> ylim(auto)
MATLAB p. 148/333
Histogram Equalization
18000
16000
14000
12000
10000
8000
6000
4000
2000
18000
16000
14000
12000
10000
8000
6000
4000
2000
MATLAB p. 149/333
Histogram Equalization
>> hnorm=imhist(f)./numel(f);
>> %Cummulative distribution function:
>> cdf=cumsum(hnorm);
>> x=linspace(0,1,256);
>> plot(x,cdf)
>> axis([0 1 0 1])
>> set(gca,xtick,0:.2:1)
>> set(gca,ytick,0:.2:1)
>> xlabel(Input intensity values,fontsize,9)
>> ylabel(Output intensity values,fontsize,9)
>> %Specify text in the body of the graph:
>> text(0.18,0.5,Transformation function,...
>> fontsize,9)
MATLAB p. 150/333
Histogram Equalization
0.8
Output intensity values
0.6
Transformation function
0.4
0.2
0
0 0.2 0.4 0.6 0.8 1
Input intensity values
MATLAB p. 151/333
Histogram Matching
It is useful in some applications to be able to specify the
shape of the histogram that we wish the processed image
to have. The method used to generate a processed image
that has a specified histogram is called histogram
matching.
g=histeq(f,hspec)
where f is the input image, hspec is the specified
histogram (a row vector of specified values), and g is the
input image, whose histogram approximates the specified
histogram, hspec.
MATLAB p. 152/333
Histogram Matching
4
x 10
4
x 10
MATLAB p. 153/333
Histogram Matching
function p=twomodegauss(m1,sig1,m2,sig2,A1,A2,k)
%TWOMODEGAUSS Generates a bimodal Gaussian function.
% P=TWOMODEGAUSS(M1,SIG1,M2,SIG2,A1,A2,K) generates a bimodal,
% Gaussian-like function in the interval [0,1]. P is a
% 256-element vector normalized so that SUM(P) equals 1. The
% mean and standard deviation of the modes are (M1,SIG1) and
% (M2,SIG2), respectively. A1 and A2 are the amplitude values
% of the two modes. Since the output is normalized, only the
% relative values of A1 and A2 are important. K is an offset
% values that raises the "floor" of the function. A good set
% of values to try is M1=0.15, SIG1=0.05, M2=0.75, SIG2=0.05,
% A1=1, A2=0.07, and K=0.002.
MATLAB p. 154/333
Histogram Matching
c1=A1*(1/((2*pi)0.5)*sig1);
k1=2*(sig12);
c2=A2*(1/((2*pi)0.5)*sig2);
k2=2*(sig22);
z=linspace(0,1,256);
p=k+c1*exp(-((z-m1).2)./k1)+...
c2*exp(-((z-m2).2)./k2);
p=p./sum(p(:));
MATLAB p. 155/333
Histogram Matching
function p=manualhist
%MANUALHIST Generates a bimodal histogram interactively.
% P=MANUALHIST generates a bimodal histogram using
% TWOMODEGAUSS(m1,sig1,m2,sig2,A1,A2,k). m1 and m2 are the
% means of the two modes and must be in the range [0,1]. sig1
% and sig2 are the standard deviations of the two modes. A1
% and A2 are amplitude values, and k is an offset value that
% raises the "floor" of histogram. The number of elements in
% the histogram vector P is 256 and sum(P) is normalized to 1.
% MANUALHIST repeatedly prompts for the parameters and plots
% the resulting histogram until the user types an x to quit,
% and then it returns the last histogram computed.
%
% A good set of starting values is: (0.15, 0.05, 0.75, 0.05, 1,
% 0.07, 0.002).
MATLAB p. 156/333
Histogram Matching
%Initialize.
repeats=true;
quitnow=x;
MATLAB p. 157/333
Histogram Matching
%Convert the input string to a vector of numerical values and
%verify the number of inputs.
v=str2num(s);
if numel(v)=7
disp(Incorrect number of inputs.)
continue
end
p=twomodegauss(v(1),v(2),v(3),v(4),v(5),v(6),v(7));
%Start a new figure and scale the axes. Specifying only xlim
%leaves ylim on auto.
figure, plot(p)
xlim([0 255])
end
MATLAB p. 158/333
Histogram Matching
>> f=imread(moon_phobos.tif);
>> p=manualhist;
Enter m1, sig1, m2, sig2, A1, A2, k OR x to quit:x
>> g=histeq(f,p);
>> imshow(g)
>> figure, imhist(g)
MATLAB p. 159/333
Histogram Matching
4
x 10
0.02
0.018 6
0.016
5
0.014
4
0.012
0.01 3
0.008
2
0.006
0.004 1
0.002
0
0
0 50 100 150 200 250 0 50 100 150 200 250
MATLAB p. 160/333
Spatial Filtering
Neighborhood processing consists of
defining a center point, (x, y);
performing an operation that involves only the pixels in
a predefined neighborhood about that center point;
letting the result of that operation be the "response" of
the process at that point; and
repeating the process for every point in the image.
MATLAB p. 161/333
Linear Spatial Filtering
The mechanics of linear spatial filtering:
MATLAB p. 162/333
Linear Spatial Filtering
The process consists simply of moving the center of the
filter mask w from point to point in an image f . At each
point (x, y), the response of the filter at that point is the
sum of products of the filter coefficients and the
corresponding neighborhood pixels in the area spanned by
the filter mask. For a mask of size m n, we assume
typically that m = 2a + 1 and n = 2b + 1, where a and b are
nonnegative integers.
There are two closely related concepts that must be
understood clearly when performing linear spatial filtering.
Correlation is the process of passing the mask w by the
image array f in the manner described earlier.
Mechanically, convolution is the same process, except that
w is rotated by 180 prior to passing it by f .
MATLAB p. 163/333
Linear Spatial Filtering
MATLAB p. 164/333
Linear Spatial Filtering
MATLAB p. 165/333
Linear Spatial Filtering
MATLAB p. 166/333
Linear Spatial Filtering
The preceding concepts extend easily to images, as
illustrated in the following figures.
MATLAB p. 167/333
Linear Spatial Filtering
Correlation
MATLAB p. 168/333
Linear Spatial Filtering
Convolution
MATLAB p. 169/333
Linear Spatial Filtering
g=imfilter(f,w,filtering_mode,...
boundary_options,size_options)
MATLAB p. 170/333
Linear Spatial Filtering
Options Description
Filtering Mode
corr Filtering is done using correlation. This is the default.
conv Filtering is done using convolution.
Boundary Options
P The boundaries of the input image are extended by padding with a
value, P. This is the default, with value 0.
replicate The size of the image is extended by replicating the values in its
outer border.
symmetric The size of the image is extended by mirror-reflecting it across its
border.
circular The size of the image is extended by treating the image as one
period a 2-D periodic function.
Size Options
full The output is of the same size as the extended (padded) image.
same The output is of the same size as the input. This is the default.
MATLAB p. 171/333
Linear Spatial Filtering
>> f=imread(original_test_pattern.tif);
>> f=double(f);
>> w=ones(31);
MATLAB p. 172/333
Linear Spatial Filtering
>> gd=imfilter(f,w);
>> imshow(gd,[])
MATLAB p. 173/333
Linear Spatial Filtering
gr=imfilter(f,w,replicate);
imshow(gr,[])
MATLAB p. 174/333
Linear Spatial Filtering
>> gs=imfilter(f,w,symmetric);
>> imshow(gs,[])
MATLAB p. 175/333
Linear Spatial Filtering
>> gc=imfilter(f,w,circular);
>> imshow(gc,[])
MATLAB p. 176/333
Linear Spatial Filtering
>> f8=im2uint8(f);
>> g8r=imfilter(f8,w,replicate);
>> imshow(g8r,[])
MATLAB p. 177/333
Nonlinear Spatial Filtering
Nonlinear spatial filtering is based on neighborhood
operations also, and the mechanics of defining m n
neighborhoods by sliding the center point through an
image are the same as discussed in linear spatial filtering.
Nonlinear spatial filtering is based on nonlinear operations
involving the pixels of a neighborhood. For example, letting
the response at each center point be equal to the
maximum pixel value in its neighborhood is a nonlinear
filtering operation. Another basic difference is that the
concept of a mask is not as prevalent in nonlinear
processing. The ides of filtering carries over, but the "filter"
should be visualized as a nonlinear function that operates
on the pixels of a neighborhood, and whose response
constitutes the response of the operation at the center
pixel of the neighborhood.
MATLAB p. 178/333
Nonlinear Spatial Filtering
The IPT provides two functions for performing general
nonlinear filtering: nlfilter and colfilt. The former
performs operations directly in 2-D, while colfilt
organizes the data in the form of columns. Altough
colfilt requires more memory, it generally executes
significantly faster than nlfilter. In most image
processing applications speed is an overriding factor, so
colfilt is preferred over nlfilter for implementing
generalized nonlinear spatial filtering.
MATLAB p. 179/333
Nonlinear Spatial Filtering
Given an input image, f, of size M N , and a
neighborhood of size m n, function colfilt generates a
matrix, call it A, of maximum size mn M N , in which each
column corresponds to the pixels encompassed by the
neighborhood centered at a location in the image. For
example, the first column corresponds to the pixels
encompassed by the neighborhood when its center is
located at the top, leftmost point in f. All required padding
is handled transparently by colfilt.
MATLAB p. 180/333
Nonlinear Spatial Filtering
g=colfilt(f,[m n],sliding,@fun,parameters)
MATLAB p. 181/333
Nonlinear Spatial Filtering
fp=padarray(f,[r c],method,direction)
where f is the input image, fp is the padded image,
[r c] gives the number of rows and columns, by which to
pad f, and method and direction are as explained in
the next table.
MATLAB p. 182/333
Nonlinear Spatial Filtering
Options Description
Method
symmetric The size of the image is extended by mirror-reflecting it across its
border.
replicate The size of the image is extended by replicating the values in its
outer border.
circular The size of the image is extended by treating the image as one
period of a 2-D periodic function.
Direction
pre Pad before the first element of each dimension.
post Pad after the last element of each dimension.
both Pad before the first element and after the last element of each di-
mension. This is the default.
MATLAB p. 183/333
Nonlinear Spatial Filtering
>> f=[1 2;3 4];
>> fp=padarray(f,[3 2],replicate,post)
fp =
1 2 2 2
3 4 4 4
3 4 4 4
3 4 4 4
3 4 4 4
MATLAB p. 184/333
Nonlinear Spatial Filtering
function v=gmean(A)
MATLAB p. 185/333
Nonlinear Spatial Filtering
MATLAB p. 186/333
IPT Standard Spatial Filters
Linear Spatial Filters
Nonlinear Spatial Filters
MATLAB p. 187/333
Linear Spatial Filters
w=fspecial(type,parameters)
where type specifies the filter type, and parameters
further define the specified filter. The spatial filters
supported by fspecial are summarized in the following
table, including applicable parameters for each filter.
MATLAB p. 188/333
Linear Spatial Filters
Type Syntax and Parameters
average fspecial(average,[r c]). A rectangular averaging filter of
size rc. The default is 3 3. A single number instead of [r c]
specifies a square filter.
disk fspecial(disk,r). A circular averaging filter (within a square
of size 2r+1) with radius r. The default radius is 5.
gaussian fspecial(gaussian,[r c],sig). A Gaussian lowpass filter
of size rc and standard deviation sig (positive). The defaults are
3 3 and 0.5. A single number instead of [r c] specifies a square
filter.
laplacian fspecial(laplacian,alpha). A 3 3 Laplacian filter whose
shape is specified by alpha, a number in the range [0, 1]. The
default value for alpha is 0.5.
log fspecial(log,[r c],sig). Laplacian of a Gaussian (LoG)
filter of size rtimesc and standard deviation sig (positive). The de-
faults are 5 5 and 0.5. A single number instead of [r c] specifies
a square filter.
MATLAB p. 189/333
Linear Spatial Filters
Type Syntax and Parameters
motion fspecial(motion,len,theta). Outputs a filter that, when con-
volved with an image, approximates linear motion (of a camera with
respect to the image) of len pixels. The direction of motion is theta,
mesaured in degrees, counterclockwise from the horizontal. The de-
faults are 9 and 0, which represents a motion of 9 pixels in the hori-
zontal direction.
prewitt fspecial(prewitt). Outputs a 3 3 Prewitt mask, wv, that ap-
proximates a vertical gradient. A mask for the horizontal gradient is
obtained by transposing the result: wh=wv.
sobel fspecial(sobel). Outputs a 3 3 Sobel mask, sv, that ap-
proximates a vertical gradient. A mask for the horizontal gradient is
obtained by transposing the result: sh=sv.
unsharp fspecial(unsharp,alpha). Outputs a 3 3 unsharp filter. Pa-
rameter alpha controls the shape; it must be greater than or equal to
0 and less than or equal to 1.0; the default is 0.2.
MATLAB p. 190/333
Linear Spatial Filters
>> w=fspecial(laplacian,0)
w =
0 1 0
1 -4 1
0 1 0
MATLAB p. 191/333
Linear Spatial Filters
>> f=imread(moon.tif);
MATLAB p. 192/333
Linear Spatial Filters
>> g1=imfilter(f,w,replicate);
>> imshow(g1,[])
MATLAB p. 193/333
Linear Spatial Filters
>> f2=im2double(f);
>> g2=imfilter(f2,w,replicate);
>> imshow(g2,[])
MATLAB p. 194/333
Linear Spatial Filters
>> g=f2-g2;
>> imshow(g)
MATLAB p. 195/333
Linear Spatial Filters
>> f=imread(moon.tif);
>> w4=fspecial(laplacian,0);
>> w8=[1 1 1;1 -8 1;1 1 1];
>> f=im2double(f);
>> g4=f-imfilter(f,w4,replicate);
>> g8=f-imfilter(f,w8,replicate);
>> imshow(f)
>> figure, imshow(g4)
>> figure, imshow(g8)
MATLAB p. 196/333
Linear Spatial Filters
MATLAB p. 197/333
Nonlinear Spatial Filters
g=ordfilt2(f,order,domain
This function creates the output image g by replacing each
element of f by the order-th element in the sorted set of
neighbors specified by the nonzero elements in domain.
Here, domain is an m n matrix of 1s and 0s that specify
the pixel locations in the neighborhood that are to be used
in the computation. In this sense, domain acts like a mask.
The pixels in the neighborhood that corresponds to 0 in the
domain matrix are not used in the computation.
MATLAB p. 198/333
Nonlinear Spatial Filters
Min filter of size m n:
g=ordfilt2(f,1,ones(m,n))
MATLAB p. 199/333
Nonlinear Spatial Filters
g=medfilt2(f,[m n],padopt
where the tuple [m n] defines a neighborhood of size
m n over which the median is computed, and padopt
specifies one of three possible border padding options:
zeros (the default), symmetric in which f is
extended symmetrically by mirror-reflecting it across its
border, and indexed, in which f is padded with 1s if it
is of class double and with 0s otherwise. The default form
of this function is g=medfilt2(f) which uses a 3 3
neighborhood to compute the median, and pads the border
of the input with 0s.
MATLAB p. 200/333
Nonlinear Spatial Filters
>> f=imread(ckt-board.tif);
>> fn=imnoise(f,salt & pepper,0.2);
>> gm=medfilt2(fn);
>> gms=medfilt2(fn,symmetric);
>> subplot(2,2,1), imshow(f)
>> subplot(2,2,2), imshow(fn)
>> subplot(2,2,3), imshow(gm)
>> subplot(2,2,4), imshow(gms)
MATLAB p. 201/333
Nonlinear Spatial Filters
MATLAB p. 202/333
Chapter 4
Frequency Domain
Processing
MATLAB p. 203/333
Content
The 2-D Discrete Fourier Transform
Computing and Visualizing the 2-D DFT in MATLAB
Filtering in the Frequency Domain
MATLAB p. 204/333
The 2-D Discrete Fourier Transform
Let f (x, y), for x = 0, 1, 2, . . . , M 1 and
y = 0, 1, 2, . . . , N 1, denote an M N image. The 2-D,
discrete Fourier transform (DFT) of f , denoted by F (u, v),
is given by the equation
M
X 1 N
X 1
F (u, v) = f (x, y)ej2(ux/M +vy/N )
x=0 y=0
for u = 0, 1, 2, . . . , M 1 and v = 0, 1, 2, . . . , N 1.
MATLAB p. 205/333
The 2-D Discrete Fourier Transform
The frequency domain is simply the coordinate system
spanned by F (u, v) with u and v as (frequency) variables.
This is analogous to the spatial domain studied in the
previous lecture, which is the coordinate systam spanned
by f (x, y), with x and y as (spatial) variables. The M N
rectangular region defined by u = 0, 1, 2, . . . , M 1 and
v = 0, 1, 2, . . . , N 1 is often referred to as the frequency
rectangle.
MATLAB p. 206/333
The 2-D Discrete Fourier Transform
The inverse, discrete Fourier transform is given by
M 1 N 1
1 XX
f (x, y) = F (u, v)ej2(ux/M +vy/N )
M N u=0 v=0
MATLAB p. 207/333
The 2-D Discrete Fourier Transform
Because array indices in MATLAB start at 1, rather than 0,
F(1,1) and f(1,1) in MATLAB corresponds to the
mathematical quantities F (0, 0) and f (0, 0) in the transform
and its inverse.
MATLAB p. 208/333
The 2-D Discrete Fourier Transform
Even if f (x, y) is real, its transform in general is complex.
The principal method of visually analyzing a transform is to
compute its spectrum and display it as an image. Letting
R(u, v) and I(u, v) represent the real and imaginary
components of F (u, v), the Fourier spectrum is defined as
p
|F (u, v)| = R2 (u, v) + I 2 (u, v)
MATLAB p. 209/333
The 2-D Discrete Fourier Transform
The power spectrum is defined as the square of the
magnitude:
MATLAB p. 210/333
The 2-D Discrete Fourier Transform
If f (x, y) is real, its Fourier transform is conjugate
symmetric about the origin; that is,
F (u, v) = F (u, v)
MATLAB p. 211/333
The 2-D Discrete Fourier Transform
It can be shown by direct substitution into the equation for
F (u, v) that
F (u, v) = F (u + M, v) = F (u, v + N ) = F (u + M, v + N )
f (x, y) = f (x + M, y) = f (x, y + N ) = f (x + M, y + N )
MATLAB p. 212/333
The 2-D Discrete Fourier Transform
MATLAB p. 213/333
The 2-D Discrete Fourier Transform
MATLAB p. 214/333
Computing and Visualizing the 2-D DFT in MATLAB
MATLAB p. 216/333
Computing and Visualizing the 2-D DFT in MATLAB
MATLAB p. 217/333
Computing and Visualizing the 2-D DFT in MATLAB
>> F=fft2(f);
>> S=abs(F);
>> imshow(S,[])
MATLAB p. 218/333
Computing and Visualizing the 2-D DFT in MATLAB
MATLAB p. 219/333
Computing and Visualizing the 2-D DFT in MATLAB
>> Fc=fftshift(F);
>> imshow(abs(Fc),[])
MATLAB p. 220/333
Computing and Visualizing the 2-D DFT in MATLAB
>> S2=log(1+abs(Fc));
>> imshow(S2,[])
MATLAB p. 221/333
Computing and Visualizing the 2-D DFT in MATLAB
MATLAB p. 222/333
Computing and Visualizing the 2-D DFT in MATLAB
MATLAB p. 224/333
Computing and Visualizing the 2-D DFT in MATLAB
MATLAB p. 225/333
Computing and Visualizing the 2-D DFT in MATLAB
MATLAB p. 226/333
Filtering in the Frequency Domain
Fundamental Concepts
Basic Steps in DFT Filtering
An M-function for Filtering in the Frequency Domain
MATLAB p. 227/333
Fundamental Concepts
Formally, the discrete convolution of two function f (x, y)
and h(x, y) of size M N is denoted by f (x, y) h(x, y)
and is defined by the expression
M
X 1 N
X 1
f (x, y) h(x, y) = f (m, n)h(x m, y n).
m=0 n=0
MATLAB p. 228/333
Fundamental Concepts
MATLAB p. 229/333
Fundamental Concepts
X X
M 1 N 1
f g = f (m, n)g(x m, y n) =
!
m=0 n=0
X X
M 1 N 1
1 X X
M 1 N 1
= f (m, n) G(u, v)ej2(u(xm)/M +v(yn)/N ) =
m=0 n=0
MN u=0 v=0
1 X X
M 1 N 1
= G(u, v)ej2(ux/M +vy/N )
MN
!
u=0 v=0
X X
M 1 N 1
f (m, n)ej2(um/M +vn/N ) =
m=0 n=0
1 X X
M 1 N 1
= G(u, v)ej2(ux/M +vy/N ) F (u, v) =
MN u=0 v=0
MATLAB p. 230/333
Fundamental Concepts
The foundation for linear filtering in both spatial and
frequency domains is the convolution theorem, which may
be written as
and, conversely,
MATLAB p. 231/333
Fundamental Concepts
The previous equation is really nothing more than an
implementation for
1. flipping one function about the origin;
2. shifting that function with respect to the other by
changing the values of (x, y); and
3. computing a sum of products over all values of m and
n, for each displacement (x, y).
MATLAB p. 232/333
Fundamental Concepts
Filtering in the spatial domain consists of convolving an
image f (x, y) with a filter mask, h(x, y). According to the
convolution theorem, we can obtain the same result in the
frequency domain by multiplying F (u, v) by H(u, v), the
Fourier transform of the spatial filter. It is customary to
refer to H(u, v) as the filter transfer function.
MATLAB p. 233/333
Fundamental Concepts
Basically, the idea in frequency
domain filtering is to select a fil-
ter transfer function that modifies
F (u, v) in a specified manner. For
example, the filter in the figure has
a transfer function that, when mul-
tiplied by a centered F (u, v), at-
tenuates the high-frequency com-
ponents of F (u, v), while leaving
the low frequencies relatively un-
changed. Filters with this charac-
teristic are called lowpass filters.
MATLAB p. 234/333
Fundamental Concepts
Based on the convolution theorem, we know that to obtain
the corresponding filtered image in the spatial domain we
simply compute the inverse Fourier transform of the
product H(u, v)F (u, v). It is important to keep in mind that
the process just described is identical to what we would
obtain by using convolution in the spatial domain, as long
as the filter mask, h(x, y), is the inverse Fourier transform
of H(u, v). In practice, spatial convolution generally is
simplified by using small masks that attempt to capture the
salient features of their frequency domain counterparts.
MATLAB p. 235/333
Fundamental Concepts
As noted earlier images and their transforms are
automatically considered periodic if we elect to work with
DFTs to implement filtering. It is not difficult to visualize
that convolving periodic functions can cause interference
between adjacent periodics if the periods are close with
respect to the duration of the nonzero parts of the
functions. This interference, called wraparound error, can
be avoided by padding the functions with zeros, in the
followin manner.
MATLAB p. 236/333
Fundamental Concepts
Assume that functions f (x, y) and h(x, y) are of size A B
and C D, respectively. We form two expanded (padded)
functions, both of size P Q by appending zeros to f and
g. It can be shown that wraparound error is avoided by
choosing
P A+C 1
and
Y B+D1
Most of the work in this chapter deals with functions of the
same size, M N , in which case we use the following
padding values: P 2M 1 and Q 2N 1.
MATLAB p. 237/333
Fundamental Concepts
function PQ=paddedsize(AB,CD,PARAM)
%PADDEDSIZE Computes padded sizes useful for FFT-based filtering.
% PQ=PADDEDSIZE(AB), where AB is a two-element size vector,
% computes the two-element size vector PQ=2*AB.
%
% PQ=PADDEDSIZE(AB,PWR2) computes the vector PQ such that
% PQ(1)=PQ(2)=2nextpow2(2*m), where m is MAX(AB).
%
% PQ=PADDEDSIZE(AB,CD), where AB and CD are two-element size
% vectors, computes the two-element size vector PQ. The elements
% of PQ are the smallest even integers greater than or equal to
% AB+CD-1.
%
% PQ=PADDEDSIZE(AB,CD,PWR2) computes the vector PQ such that
% PQ(1)=PQ(2)=2nextpow2(2*m), where m is MAX([AB CD]).
MATLAB p. 238/333
Fundamental Concepts
if nargin==1
PQ=2*AB;
elseif nargin==2 & ischar(CD)
PQ=AB+CD-1;
PQ=2*ceil(PQ/2);
elseif nargin==2
m=max(AB); %Maximum dimension.
MATLAB p. 239/333
Fundamental Concepts
With PQ thus computed using function paddedsize, we use
the following syntax for fft2 to compute the FFT using
zero padding:
F=fft2(f,PQ(1),PQ(2))
This syntax simply appends enough zeros to f such that
the resulting image is of size PQ(1)PQ(2), and then
computes the FFT as previously described. Note that
when using padding the filter function in the frequency
domain must be of size PQ(1)PQ(2) also.
MATLAB p. 240/333
Fundamental Concepts
The image, f, in the figure is used to illustrate the
difference between filtering with and without padding. In
the following discussion we use function lpfilter to
generate a Gaussian lowpass filter with a specified value of
sigma (sig).
MATLAB p. 241/333
Fundamental Concepts
>> f=imread(square_original.tif);
>> [M,N]=size(f);
>> F=fft2(f);
>> sig=10;
>> H=lpfilter(gaussian,M,N,sig);
>> G=H.*F;
>> g=real(ifft2(G));
>> imshow(g,[])
MATLAB p. 242/333
Fundamental Concepts
>> PQ=paddedsize(size(f));
%Compute the FFT with padding.
>> Fp=fft2(f,PQ(1),PQ(2));
>> Hp=lpfilter(gaussian,PQ(1),PQ(2),2*sig);
>> Gp=Hp.*Fp;
>> gp=real(ifft2(Gp));
>> gpc=gp(1:size(f,1),1:size(f,2));
>> imshow(gp,[])
>> imshow(gpc,[])
MATLAB p. 243/333
Basic Steps in DFT Filtering
1. Obtain the padding parameters using function
paddedsize:
PQ=paddedsize(size(f));
2. Obtain the Fourier transform with padding:
F=fft2(f,PQ(1),PQ(2));
3. Generate a filter function, H, of size PQ(1)PQ(2)
using any of the methods discussed later. The filter
must be in the format shown in the left side figure on
the next slide. If it is centered instead, as in the right
side figure on the next slide, let H=fftshift(H)
before using the filter.
MATLAB p. 244/333
Basic Steps in DFT Filtering
MATLAB p. 245/333
Basic Steps in DFT Filtering
4. Multiply the transform by the filter:
G=H.*F
5. Obtain the real part of the inverse FFT of G:
g=real(ifft2(G));
6. Crop the top, left rectangle to the original size:
g=g(1:size(f,1),1:size(f,2));
MATLAB p. 246/333
Basic Steps in DFT Filtering
MATLAB p. 247/333
Basic Steps in DFT Filtering
It is well known from linear system theory that, under
certain mild conditions, inputting an impulse into a linear
system completely characterizes the system. When
working with finite, discrete data, as we do, the response of
a linear system, including the response to an impulse, also
is finite. If the linear system is just a spatial filter, then we
can completely determine the filter simply by observing its
response to an impulse. A filter determined in this manner
is called a finite-impulse-response (FIR) filter.
MATLAB p. 248/333
An M-function for Filtering in the Frequency Domain
function g=dftfilt(f,H)
%DFTFILT Performs frequency domain filtering.
% G=DFTFILT(F,H) filters F in the frequency domain using the
% filter transfer function H. The output, G, is the filtered
% image, which has the same size as F. DFTFILT automatically pads
% F to be the same size as H. Function PADDEDSIZE can be used
% to determine an appropriate size for H.
%
% DFTFILT assumes that F is real and that H is a real, uncentered,
% circularly-symmetric filter function.
%Perform filtering.
g=real(ifft2(H.*F));
MATLAB p. 250/333
Obtaining Frequency Domain Filters from Spatial Filters
>> f=imread(bld.tif);
MATLAB p. 251/333
Obtaining Frequency Domain Filters from Spatial Filters
>> F=fft2(f);
>> S=fftshift(log(1+abs(F)));
>> S=gscale(S);
>> imshow(S)
MATLAB p. 252/333
Obtaining Frequency Domain Filters from Spatial Filters
>> h=fspecial(sobel)
h =
1 0 -1
2 0 -2
1 0 -1
>> freqz2(h)
MATLAB p. 253/333
Obtaining Frequency Domain Filters from Spatial Filters
>> PQ=paddedsize(size(f));
>> H=freqz2(h,PQ(1),PQ(2));
>> H1=ifftshift(H);
MATLAB p. 254/333
Obtaining Frequency Domain Filters from Spatial Filters
>> imshow(abs(H),[])
>> figure, imshow(abs(H1),[])
MATLAB p. 255/333
Obtaining Frequency Domain Filters from Spatial Filters
>> gs=imfilter(double(f),h);
>> gf=dftfilt(f,H1);
>> imshow(gs,[])
>> figure,imshow(gf,[])
MATLAB p. 256/333
Obtaining Frequency Domain Filters from Spatial Filters
MATLAB p. 257/333
Obtaining Frequency Domain Filters from Spatial Filters
>> figure, imshow(abs(gs)>0.2*abs(max(gs(:))))
>> figure, imshow(abs(gf)>0.2*abs(max(gf(:))))
MATLAB p. 258/333
Obtaining Frequency Domain Filters from Spatial Filters
>> d=abs(gs-gf);
>> max(d(:))
ans =
5.5156e-013
>> min(d(:))
ans =
MATLAB p. 259/333
Chapter 5
Edge Detection
MATLAB p. 260/333
Edge detection
Edges can be found in an image, where sudden
intesity changing is sensed.
The changing can be determined from the derivatives
of the intensity function.
In an image we should use gradient instead of
derivates. " #
f
Gradient vector: x
f
y
s 2 2
f f
Length of the gradient vector: +
x y
MATLAB p. 261/333
edge function
MATLAB function:
[g,t]=edge(f,method,parameters)
MATLAB p. 262/333
Prewitt detector
1 1 1 1 0 1
Masks: 0 0 0 1 0 1
1 1 1 1 0 1
MATLAB function:
[g,t]=edge(f,prewitt,T,dir)
MATLAB p. 263/333
Sobel detector
1 2 1 1 0 1
Masks: 0 0 0 2 0 2
1 2 1 1 0 1
MATLAB function:
[g,t]=edge(f,sobel,T,dir)
MATLAB p. 264/333
Roberts detector
" # " #
1 0 0 1
Masks:
0 1 1 0
MATLAB function:
[g,t]=edge(f,roberts,T,dir)
MATLAB p. 265/333
Laplacion of Gaussian detector
2 2
r r2
Mask equation: e 2 2
4
MATLAB function:
[g,t]=edge(f,log,T,sigma)
MATLAB p. 266/333
Zero-crossing detector
It is very similar with the previous one, but the filter mask
(H) can be determined by the user.
MATLAB function:
[g,t]=edge(f,zerocross,T,H)
MATLAB p. 267/333
Canny detector
1. The image is smoothed using a Gaussian filter with a
specified standard deviation, , to reduce noise.
2. The local gradient and edge direction are computed at
each point.
3. The computed edges are thined by nonmaximal
suppression.
4. The ridge pixels are then thresholded using two
thresholds, T 1 and T 2, with T 1 < T 2. Ridge pixels with
values greater than T 2 are said to be "strong" edge
pixels. Ridge pixels with values between T 1 and T 2
are said to be "weak" edge pixels.
MATLAB p. 268/333
Canny detector
5. Finally, the algorithm performs edge linking by
incorporation the weak pixels that are 8-connected to
the strong pixels.
MATLAB function:
[g,t]=edge(f,canny,T,sigma)
MATLAB p. 269/333
Chapter 6
Morphological Image
Processing
MATLAB p. 270/333
Dilation
IPT function imdilate performs dilation. Its basic calling
syntax is
A2=imdilate(A,B)
where A and A2 are binary images, and B is a matrix of 0s
and 1s that specifies the structuring element.
MATLAB p. 271/333
Dilation
>> A=imread(broken-text.tif);
>> B=[0 1 0;1 1 1;0 1 0];
>> A2=imdilate(A,B);
MATLAB p. 272/333
Structuring Element
IPT function strel constructs structuring elements with a
variety of shapes and sizes. Its basic syntax is
se=strel(shape,parameters)
where shape is a string specifying the desired shape, and
parameters is a list of parameters that specify
information about the shape, such as its size.
MATLAB p. 273/333
Structuring Element
Syntax Forms Description
strel(diamond,R) Creates a flat, diamond-shaped structuring element,
where R specifies the distance from the structuring el-
ement origin to the extreme points of the diamond.
strel(disk,R) Creates a flat, disk-shaped structuring element with
radius R.
strel(line,LEN,DEG) Creates a flat, linear structuring element, where LEN
specifies the length, and DEG specifies the angle (in
degrees) of the line, as measured in a counterclock-
wise direction from the horizontal axes.
strel(octagon,R) Creates a flat, octagonal structuring element, where
R specifies the distance from the structuring element
origin to the sides of the octagon, as measured along
the horizontal and vertical axes. R must be a nonneg-
ative multiple of 3.
MATLAB p. 274/333
Structuring Element
Syntax Forms Description
strel(pair,OFFSET) Creates a flat structuring element containing two
members. One member is located at the origin.
The second members location is specified by
the vector OFFSET, which must be a two-element
vector of integers.
strel(periodicline,P,V) Creates a flat structuring element containing
2*P+1 members. V is a two-element vector con-
taining integer-valued row and column offsets.
One structuring element member is located at
the origin. The other members are located at
1*V, -1*V, 2*V, -2*V, ..., P*V, and -P*V.
MATLAB p. 275/333
Structuring Element
Syntax Forms Description
strel(rectangle,MN) Creates a flat, rectangle-shaped structuring element,
where MN specifies the size. MN must be a two-
element vector of nonnegative integers. The first ele-
ment of MN is the number of rows in the structuring el-
ement; the second element is the number of columns.
strel(square,W) Creates a square structuring element whose width is
W pixels. W must be a nonnegative integer scalar.
strel(NHOOD) Creates a structuring element of arbitrary shape.
NHOOD is a matrix of 0s and 1s that specifies the
shape.
MATLAB p. 276/333
Dilation
>> originalI=imread(cameraman.tif);
>> se=strel(disk,2);
>> dilatedI=imdilate(originalI,se);
MATLAB p. 277/333
Erosion
>> A=imread(wirebond-mask.tif);
>> se=strel(disk,10);
>> A2=imerode(A,se);
>> se=strel(disk,5);
>> A3=imerode(A,se);
>> A4=imerode(A,strel(disk,20));
>> subplot(2,2,1), imshow(A),...
subplot(2,2,2), imshow(A2),...
subplot(2,2,3), imshow(A3),...
subplot(2,2,4), imshow(A4)
MATLAB p. 278/333
Erosion
MATLAB p. 279/333
Labeling Connected Components
IPT function bwlabel computes all the connected
components in a binary image. The calling syntax is
[L,num]=bwlabel(f,conn)
where f is an input binary image and conn specifies the
desired connectivity (either 4 or 8). Output L is called a
label matrix, and num (optional) gives the total number of
connected components found. If parameter conn is
omitted, its value defaults to 8.
MATLAB p. 280/333
Labeling Connected Components
>> f=imread(ten-objects.tif);
>> [L,n]=bwlabel(f);
>> [r,c]=find(L==3);
>> rbar=mean(r);
>> cbar=mean(c);
>> imshow(f)
>> hold on
>> for k=1:n
[r,c]=find(L==k);
rbar=mean(r);
cbar=mean(c);
plot(cbar,rbar,Marker,o, MarkerEdgeColor,k,...
MarkerFaceColor,k, MarkerSize,10)
plot(cbar,rbar,Marker,*, MarkerEdgeColor,w)
end
MATLAB p. 281/333
Labeling Connected Components
MATLAB p. 282/333
Chapter 7
MATLAB p. 283/333
Content
Color Image Representation in MATLAB
Converting to Other Color Spaces
MATLAB p. 284/333
Color Image Representation in MATLAB
RGB Images
Indexed Images
IPT Functions for Manipulating RGB and Indexed
Images
MATLAB p. 285/333
RGB Images
An RGB color image is an M N 3 array of color pixels,
where each color pixel is a triplet corresponding to the red,
green, and blue components of an RGB image at a specific
spatial location.
MATLAB p. 286/333
RGB Images
The data class of the component images determines their
range of values. If an RGB images is of class double, the
range of values is [0, 1]. Similarly, the range of values is
[0, 255] of [0, 65535] for RGB images of class uint8 or
uint16, respectively. The number of bits used to
represent the pixel values of the component images
determines the bit depth of an RGB image.
MATLAB p. 287/333
RGB Images
Let fR, fG, and fB represent three RGB component
images. An RGB image is formed from these images by
using the cat (concatenate) operator to stack the images:
rgb_image=cat(3,fR,fG,fB)
The order in which images are placed in the operand
matters. In general, cat(dim,A1,A2,...) concatenates
the arrays along the dimension specified by dim. For
example, if dim=1, the arrays are arranged vertically, if
dim=2, they are arranged horizontally, and, if dim=3, they
are stacked in the third dimension.
MATLAB p. 288/333
RGB Images
If all component images are identical, the result is a
gray-scale image. Let rgb_image denote an RGB image.
The following commands extract the three component
images:
>> fR=rgb_image(:,:,1);
>> fG=rgb_image(:,:,2);
>> fB=rgb_image(:,:,3);
MATLAB p. 289/333
RGB Images
The RGB color space usually is shown graphically as an
RGB color cube, as depicted in the figure. The vertices of
the cube are the primary (red, green, and blue) and
secondary (cyan, magenta, and yellow) colors of light.
MATLAB p. 290/333
RGB Images
function rgbcube(vx,vy,vz)
%RGBCUBE Displays an RGB cube on the MATLAB desktop.
% RGBCUBE(VX,VY,VZ) displays an RGB color cube, viewed from point
% (VX,VY,VZ). With no input arguments, RGBCUBE uses (10,10,4)
% as the default viewing coordinates. To view individual color
% planes, use the following viewing coordinates, where the first
% color in the sequence is the closest to the viewing axis, and the
% other colors are as seen from that axis, proceeding to the right
% (ob above), and then moving clockwise.
%
% --------------------------------------------
% COLOR PLANE ( VX, VY, VZ)
% --------------------------------------------
% Blue-Magenta-White-Cyan ( 0, 0, 10)
% Red-Yellow-White-Magenta ( 10, 0, 0)
% Green-Cyan-White-Yellow ( 0, 10, 0)
% Black-Red-Magenta-Blue ( 0,-10, 0)
% Black-Blue-Cyan-Green (-10, 0, 0)
% Black-Red-Yellow-Green ( 0, 0,-10)
MATLAB p. 291/333
RGB Images
%Set up paramteres for function patch.
vertices_matrix=[0 0 0;0 0 1;0 1 0;0 1 1;1 0 0;1 0 1;1 1 0;1 1 1];
faces_matrix=[1 5 6 2;1 3 7 5;1 2 4 3;2 4 8 6;3 7 8 4;5 6 8 7];
colors=vertices_matrix;
%The order of the cube vertices was selected to be the same as
%the order of the (R,G,B) colors (e.g., (0,0,0) corresponds to
%black, (1,1,1) corresponds to white, and so on.)
MATLAB p. 292/333
RGB Images
%Set up viewing point.
if nargin==0
vx=10; vy=10; vz=4;
elseif nargin =3
error(Wrong number of inputs.)
end
axis off
view([vx, vy, vz])
axis square
MATLAB p. 293/333
Indexed Images
An indexed image has two components: a data matrix of integers, X,
and a colormap matrix, map. Matrix map is an m 3 array of class
double containing floating-point values in the range [0, 1]. The length,
m, of the map is equal to the number of colors it defines. Each row of
map specifies the red, green, and blue components of a single color.
An indexed images uses "direct mapping" of pixel intensity values to
colormap values. The color of each pixel is determined by using the
corresponding value of integer matrix X as a pointer into map. If X is of
class double, then all of its components with value 2 point to the
second row, and so on. If X is of class uint8 or uint16, then all
components with value 0 point to the first row in map, all components
with value 1 point to the second row, and so on.
MATLAB p. 294/333
Indexed Images
MATLAB p. 295/333
Indexed Images
To display an indexed image we write
>> imshow(X,map)
or, alternatively,
>> image(X)
>> colormap(map)
A colormap is stored with an indexed image and is
automatically loaded with the image when function imread
is used to load the image.
>>[X,map]=imread(...)
MATLAB p. 296/333
Indexed Image
Sometimes it is necessary to approximate an indexed
image by one with fewer colors. For this we use function
imapprox, whose syntax is
[Y,newmap]=imapprox(X,map,n)
This function returns an array Y with colormap newmap,
which has at most n colors. The input array X can be of
class uint8, uint16, or double. The output Y is of class
uint8 if n is less than or equal to 256. If n is greater than
256, Y is of class double.
MATLAB p. 297/333
Indexed Images
MATLAB provides several predefined color maps,
accessed using the command
>> colormap(map_name)
which sets the colormap to the matrix map_name; an
example is
>> colormap(copper)
where copper is one of the predefined MATLAB
colormaps. If the last image displayed was an indexed
image, this command changes its colormap to copper.
Alternatively, the image can be displayed directly with the
desired colormap:
>> imshow(X,copper)
MATLAB p. 298/333
Indexed Images
Name Description
autumn Varies smoothly from red, through orange, to yellow.
bone A gray-scale colormap with a higher value for the blue component.
This colormap is useful for adding an "electronic" look to gray-scale
images.
colorcube Contains as many regularly spaced colors in RGB color space as pos-
sible, while attempting to provide more steps of gray, pure red, pure
green, and pure blue.
cool Consists of colors that are shades of cyan and magenta. It varies
smoothly from cyan to magenta.
copper Varies smoothly from black to bright copper.
flag Consists of the colors red, white, blue, and black. This colormap com-
pletely changes color with each index increment.
gray Returns a linear gray-scale colormap.
hot Varies smoothly from black, through shades of red, orange, and yellow,
to white.
MATLAB p. 299/333
Indexed Images
Name Description
hsv Varies the hue component of the hue-saturation-value color model. The
colors begin with red, pass through yellow, green, cyan, blue, magenta,
and return to red. The colormap is particularly appropriate for displaying
periodic functions.
jet Ranges from blue to red, and passes through the colors cyan, yellow, and
orange.
lines Produces a colormap of colors specified by the ColorOrder property and
a shade of gray. Consult online help regarding function ColorOrder.
pink Contains pastel shades of pink. The pink colormap provides sepia tone
colorization of grayscale photographs.
prism Repeats the six colors red, orange, yellow, green, blue, and violet.
spring Consists of colors that are shades of magenta and yellow.
summer Consists of colors that are shades of green and yellow.
white This is an all white monochrome colormap.
winter Consists of colors that are shades of blue and green.
MATLAB p. 300/333
Manipulating RGB and Indexed Images
Function Purpose
dither Creates an indexed image from an RGB image by
dithering.
grayslice Creates an indexed image from a gray-scale intensity
image by multilevel thresholding.
gray2ind Creates an indexed image from a gray-scale intensity
image.
ind2gray Creates a gray-scale intensity image from an indexed
image.
rgb2ind Creates an indexed image from an RGB image.
ind2rgb Creates an RGB image from an indexed image.
rgb2gray Creates a gray-scale image from an RGB image.
MATLAB p. 301/333
Manipulating RGB and Indexed Images
>> f=imread(iris.tif);
MATLAB p. 302/333
Manipulating RGB and Indexed Images
>> [X1,map1]=rgb2ind(f,8,nodither);
>> imshow(X1,map1)
MATLAB p. 303/333
Manipulating RGB and Indexed Images
>> [X2,map2]=rgb2ind(f,8,dither);
>> imshow(X2,map2)
MATLAB p. 304/333
Manipulating RGB and Indexed Images
>> g=rgb2gray(f);
>> g1=dither(g);
>> figure, imshow(g); figure, imshow(g1)
MATLAB p. 305/333
Converting to Other Color Spaces
NTSC Color Space
The YCbCr Color Space
The HSV Color Space
The CMY and CMYK Color Spaces
The HSI Color Space
MATLAB p. 306/333
NTSC Color Space
The NTSC Color System is used in television in the United
States. One of the main advantages of this format is that
gray-scale information is separate from color data. In the
NTSC format, image data consists of three components:
luminance (Y)
hue (I)
saturation (Q)
MATLAB p. 307/333
NTSC Color Space
The YIQ components are obtained from the RGB
components of an image using the transfromation
Y 0.299 0.587 0.114 R
=
I 0.596 0.274 0.322 G
Q 0.211 0.523 0.312 B
Note that the elements of the first row sum to 1 and the
elements of the next two rows sum to 0. This is as
expected because for a gray-scale image all the RGB
components are equal, so the I and Q components should
be 0 for such an image.
MATLAB p. 308/333
NTSC Color Space
Function rgb2ntsc performs the transformation:
yiq_image=rgb2ntsc(rgb_image)
where the input RGB image can be of class uint8,
uint16, or double. The output image is an M N 3
array of class double. Component image
yiq_image(:,:,1) is the luminance,
yiq_image(:,:,2) is the hue, and yiq_image(:,:,3)
is the saturation image.
MATLAB p. 309/333
NTSC Color Space
Similarly, the RGB components are obtained from the YIQ
components using the transformation:
R 1.000 0.956 0.621 Y
G = 1.000 0.272 0.647 I
B 1.000 1.106 1.703 Q
MATLAB p. 310/333
The YCbCr Color Space
The YCbCr color space is used widely in digital video. In
this format, luminance information is represented by a
single component, Y, and color information is stored as two
color-difference components, Cb and Cr. Component Cb is
the difference between the blue component and a
reference value, and component Cr is the difference
between the red component and a reference value.
MATLAB p. 311/333
The YCbCr Color Space
The transformation used by IPT to convert from RGB to
YCbCr is
Y 16 65.481 128.553 24.966 R
Cb = 128 + 37.797 74.203 112.000 G
Cr 128 112.000 93.786 18.214 B
MATLAB p. 312/333
The YCbCr Color Space
The conversion function is
ycbcr_image=rgb2ycbcr(rgb_image)
The input RGB image can be of class uint8, uint16, or
double. The output image is of the same class as the
input. A similar transformation converts from YCbCr back
to RGB:
rgb_image=ycbcr2rgb(ycbcr_image)
The input YCbCr image can be of class uint8, uint16, or
double. The output image is of the same class as the
input.
MATLAB p. 313/333
The HSV Color Space
HSV (hue, saturation, value) is one of several color
systems used by people to select colors from a color wheel
or palette. This color system is considerably closer than
the RGB system to the way in which humans experience
and describe color sensations. In artists terminology, hue,
saturation, and value refer approximately to tint, shade,
and tone.
MATLAB p. 314/333
The HSV Color Space
MATLAB p. 315/333
The HSV Color Space
The MATLAB function for converting from RGB to HSV is
rgb2hsv, whose syntax is
hsv_image=rgb2hsv(rgb_image)
The input RGB image can be of class uint8, uint16, or
double; the output image is of class double. The function
for converting from HSV back to RGB is hsv2rgb:
rgb_image=hsv2rgb(hsv_image)
The input image must be of class double. The output also
is of class double.
MATLAB p. 316/333
The CMY Color Space
The conversion is performed using the simple equation
C 1 R
M = 1 G
Y 1 B
MATLAB p. 317/333
The CMY Color Space
Function imcomplement can be used to convert from
RGB to CMY:
cmy_image=imcomplement(rgb_image)
We use this function also to convert a CMY image to RGB:
rgb_image=imcomplement(cmy_image)
MATLAB p. 318/333
The HSI Color Space
When humans view a color object, we tend to describe it
by its hue, saturation, and brightness. Hue is an attribute
that describes a pure color, whereas saturation gives a
mesaure of the degree to which a pure color is diluted by
white light. Brightness is a subjective descriptor that is
practically impossible to measure. It embodies the
achromatic description of intensity and is a key factor in
describing color sensation. We do know that intensity (gray
level) is a most useful descriptor of monochromatic
images. This quantity definitely is measurable and easily
interpretable.
The color space we are about to present, called the HSI
(hue, saturation, intensity) color space.
MATLAB p. 319/333
Converting Colors from RGB to HSI
with
1
2
[(R G) + (R B)]
= cos 1
q
2
(R G) + (R B) (G B)
MATLAB p. 320/333
Converting Colors from RGB to HSI
MATLAB p. 321/333
Converting Colors from RGB to HSI
MATLAB p. 322/333
Converting Colors from RGB to HSI
function hsi=rgb2hsi(rgb)
%RGB2HSI Converts an RGB image to HSI.
% HSI=RGB2HSI(RGB) converts an RGB image to HSI. The input image
% is assumed to be of size M-by-N-by-3, where the third dimension
% accounts for three image planes: red, green, and blue, in that
% order. If all RGB component images are equal, the HSI conversion
% is undefined. The input image can be of class double (with values
% in the range [0,1]), uint8, or uint16.
%
% The output image, HSI, is of class double, where:
% hsi(:,:,1)=hue image normalized to the range [0,1] by
% dividing all angle values by 2*pi.
% hsi(:,:,2)=saturation image, in the range [0,1].
% hsi(:,:,3)=intensity image, in the range [0,1].
MATLAB p. 323/333
Converting Colors from RGB to HSI
% Extract the individual component images.
rgb=im2double(rgb);
r=rgb(:,:,1);
g=rgb(:,:,2);
b=rgb(:,:,3);
H=theta;
H(b>g)=2*pi-H(b>g);
H=H/(2*pi);
MATLAB p. 324/333
Converting Colors from RGB to HSI
num=min(min(r,g),b);
den=r+g+b;
den(den==0)=eps;
S=1-3.*num./den;
H(S==0)=0;
I=(r+g+b)/3;
MATLAB p. 325/333
Converting Color from HSI to RGB
Given values of HSI in the interval [0, 1], we now find the
corresponding RGB values in the same range. The
applicable equations depend on the values of H. There are
three sectors of interest, corresponding to the 120
intervals in the separation of primaries. We begin by
multiplying H by 360 , which returns the hue to its original
range of [0 , 360 ].
MATLAB p. 326/333
Converting Color from HSI to RGB
B = I (1 S)
S cos H
R=I 1+
cos(60 H)
and
G = 3I (R + B)
MATLAB p. 327/333
Converting Color from HSI to RGB
H = H 120
G = I (1 S)
S cos H
B =I 1+
cos(60 H)
R = 3I (G + B)
MATLAB p. 328/333
Converting Color from HSI to RGB
H = H 240
R = I (1 S)
S cos H
G=I 1+
cos(60 H)
B = 3I (R + G)
MATLAB p. 329/333
Converting Color from HSI to RGB
function rgb=hsi2rgb(hsi)
%HSI2RGB Converts an HSI image to RGB.
% RGB=HSI2RGB(HSI) converts an HSI image to RGB, where HSI
% is assumed to be of class double with:
% hsi(:,:,1)=hue image, assumed to be in the range
% [0,1] by having been divided by 2*pi.
% hsi(:,:,2)=saturation image, in the range [0,1].
% hsi(:,:,3)=intensity image, in the range [0,1].
%
% The components of the output image are:
% rgb(:,:,1)=red.
% rgb(:,:,2)=green.
% rgb(:,:,3)=blue.
MATLAB p. 330/333
Converting Color from HSI to RGB
% RG sector (0<=H<2*pi/3).
idx=find((0<=H)&(H<2*pi/3));
B(idx)=I(idx).*(1-S(idx));
R(idx)=I(idx).*(1+S(idx).*cos(H(idx))./...
cos(pi/3-H(idx)));
G(idx)=3*I(idx)-(R(idx)+B(idx));
MATLAB p. 331/333
Converting Color from HSI to RGB
% BG sector (2*pi/3<=H<4*pi/3).
idx=find((2*pi/3<=H)&(H<4*pi/3));
R(idx)=I(idx).*(1-S(idx));
G(idx)=I(idx).*(1+S(idx).*cos(H(idx)-2*pi/3)./...
cos(pi-H(idx)));
B(idx)=3*I(idx)-(R(idx)+G(idx));
% BR sector.
idx=find((4*pi/3<=H)&(h<=2*pi));
G(idx)=I(idx).*(1-S(idx));
B(idx)=I(idx).*(1+S(idx).*cos(H(idx)-4*pi/3)./...
cos(5*pi/3-H(idx)));
R(idx)=3*I(idx)-(G(idx)+B(idx));
MATLAB p. 332/333
References
MATLAB p. 333/333