Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Chapter 7

The Image Processing Toolbox

Aims and Objectives

• To provide a tutorial guide to the Image Processing Toolbox


• To show how to manipulate images
• To provide tools to analyze images
• To introduce fast Fourier transforms
On completion of this chapter the reader should be able to
• use the Image Processing Toolbox;
• load and save images;
• perform analysis on color, gray scale, and black and white images;
• plot power spectra of discrete dynamical systems.
As the MathWorks state: “The Image Processing Toolbox provides a com-
prehensive set of reference-standard algorithms, functions, and apps for image
processing, analysis, visualization, and algorithm development. You can perform
image enhancement, image deblurring, feature detection, noise reduction, image
segmentation, geometric transformations, and image registration. Many toolbox
functions are multithreaded to take advantage of multicore and multiprocessor
computers.”

7.1 Image Processing and Matrices

There is extensive online documentation accompanying the Image Processing


Toolbox. Probably the most popular textbooks specializing to date are [4, 6, 10],
whereas [1, 9] specialize in bio-signal and medical image processing. The reader
will be shown how to read and write image files and perform image processing
techniques on those images.

S. Lynch, Dynamical Systems with Applications using MATLAB


R
, 139
DOI 10.1007/978-3-319-06820-6__7,
© Springer International Publishing Switzerland 2014
140 7 The Image Processing Toolbox

Fig. 7.1 (a) A weight distribution motif; (b) the multifractal image. The weights are related to the
gray scale, for example, p1 D 1 would be white and p1 D 0 would be black on this scale

As a simple introduction, let us construct a multifractal image using a simple


motif.
>> % Generating a matrix to produce a multifractal image.
>> M=[0.3 0.4;0.25 0.05]
>> MM=[0.3*M 0.4*M;0.25*M 0.05*M]
>> % MM is a 4 by 4 matrix.
>> MM(1,4) % Gives the value in row 1, column 4.
>> for i=1:8 M=[0.3*M 0.4*M;0.25*M 0.05*M];end;
>> % M is now a 512 by 512 matrix.
>> % To save the data to a file use the save command.
>> save temp.dat M -ascii
>> % To load the data use the load command.
>> Data=load(’temp.dat’);
>> imtool(Data)

Move the cursor across the Image Tool window to see the pixel values of the 512 
512 image Data. Check that the value of the pixel .500; 10/ is 1:54E  05.
You will note that the value of most pixels is close to zero, and this is why the
screen looks black. One may alter the contrast of the image by hitting the Adjust
contrast button. Click on Eliminate outliers, Apply and Adjust data to see an
image similar to that shown in Fig. 7.1b.
>> % Loading image files. Use the imread command.
>> % The image peppers.png is stored in an array named Image1.
>> Image1=imread(’peppers.png’);

A true color image, or RGB image, is an image in which each pixel is defined by
three numerical values for red, green, and blue (Fig. 7.2a). MATLAB stores true
color images as m  n  3 matrices. A true color matrix can be of class uint8 and
uint16, single or double. See the MATLAB help pages for more information.
7.1 Image Processing and Matrices 141

Fig. 7.2 (a) The image peppers.png. (b) The red pixels

>> % To see the properties of an image use the whos command.


>> whos Image1 % Has dimensions 384 by 512 by 3 and is of class
uint8.

>> % Use the imtool command to work with the image.


>> imtool(Image1)

Note that the coordinate system used in the Image Processing Toolbox is ordered
from top to bottom and from left to right from the top left corner of the image. So
the pixel coordinate .500; 10/ refers to x D 500 (going left to right) and y D 10
(going top to bottom). Note that M.500; 10/ denotes the element in matrix M in row
500 and column 10. Check that the RGB value for the pixel coordinate .500; 10/ is
Œ61; 27; 63.
Suppose that one wanted to establish the number of red pixels in the image.
A simple program is listed below:

% To establish the number of red pixels in


Fig. 7.2(a).
clear
figure
P=imread(’peppers.png’);
for i=1:512
for j=1:384
if P(j,i,1)>140 && P(j,i,2)<80 && P(j,i,3)<80
RedP(j,i)=1;
else RedP(j,i)=0;
end
end
end
Num_Red_Pixels=sum(sum(RedP))
imshow(RedP)

The next example demonstrates how one may obtain a binary image from a gray
scale image (Fig. 7.3).
>> % Load the image of rice, look at its properties and view
the image.
>> clear
>> I=imread(’rice.png’);
142 7 The Image Processing Toolbox

Fig. 7.3 (a) The image rice.png. (b) A binary image of rice.png.

>> whos I
>> imshow(I)
>> % Remove the rice grains using the strel function.
>> background=imopen(I,strel(’disk’,15));
>> % Subtract the background.
>> I2=imsubtract(I,background);
>> % Increase the image contrast.
>> I3=imadjust(I2);
>> % Convert the image to a binary image.
>> level=graythresh(I3);
>> bw=im2bw(I3,level);
>> imshow(bw)
>> whos

You can now perform some statistical analysis on the image. For example,

>> % To determine the number of rice grains.


>> [labeled,numObjects]=bwlabel(bw,4);
>> numObjects
>> % Object properties in the image.
>> graindata=regionprops(labeled,’basic’);
>> % To find the area of the largest grain and its label.
>> max([graindata.Area])
>> biggrain=find([graindata.Area]==404)
>> % Plot a histogram with 20 bins of this data.
>> hist([graindata.Area],20)
>> % To find the centres of the grains of rice.
>> bw2 = imfill(bw,’holes’);
>> L = bwlabel(bw2);
>> s = regionprops(L,’centroid’);
>> centroids = cat(1,s.Centroid);
>> imtool(I)
>> hold(imgca,’on’)
>> plot(imgca,centroids(:,1), centroids(:,2), ’r.’)
>> hold(imgca,’off’)
7.2 The Fast Fourier Transform 143

7.2 The Fast Fourier Transform

The Fourier transform is a mathematical transform with many applications in image


processing, mathematics, engineering, and the physical sciences. An introduction to
fast Fourier transforms and their applications can be found in references [2, 5, 7].
Definition 1. The continuous Fourier transform is defined by
Z 1
F .!/ D f .t /e 2 i!t dt;
1

which transforms a mathematical function of time, f .t /, into a function of


frequency, F .!/. The new function is the Fourier transform or the Fourier spectrum
of the function f .
Definition 2. The inverse Fourier transform is defined by
Z 1
f .t / D F .!/e 2 i!t d!:
1

The continuous Fourier transform converts an infinitely long time-domain signal


into a continuous spectrum of an infinite number of sinusoidal curves. In many
physical applications, scientists deal with discretely sampled signals, usually at
constant intervals. For such data, the discrete Fourier transform is appropriate.
Definition 3. The discrete Fourier transform and its inverse for vectors of length N
are defined by

X
N
.n1/.k1/
Xk D tn !N ;
nD1

and

1 X
N
.n1/.k1/
xn D Xk !N ;
N
kD1

where

!N D e .2 i/=N ;

and each Xk is a complex number that encodes both amplitude and phase of a
sinusoidal component of function xn .
A fast Fourier transform, or FFT, is an algorithm to compute the discrete
Fourier transform. The FFT was first discovered by Gauss in 1805 but the modern
incarnation is attributed to Cooley and Tukey [3] in 1965. Computing a set of N data
144 7 The Image Processing Toolbox

a b
8 1

|Y(f)|
0.5
y

−2

−4

−6 0
0 10 20 30 40 50 0 100 200 300 400 500
time ms Frequency (Hz)

Fig. 7.4 (a) Signal corrupted with zero-mean random noise. (b) Single-sided amplitude spectrum
of y(t). You can read off the amplitude and frequencies

 
points using the discrete Fourier transform requires O N 2 arithmetic operations,
whilst an FFT can compute the same discrete Fourier transform in only O.N log N /
operations. Luckily for the reader, MATLAB has both the fft function and the ifft
function for computing the FFT and inverse FFT built in. The most well-known use
of the Cooley-Tukey algorithm is to divide the transform into two pieces of size
N=2 at each step and is therefore limited to power-of-two sizes, hence the use of
the nextpow2 command in Program 7a.
FFT is a powerful signal analysis tool, applicable to a wide variety
of fields including acoustics, applied mechanics, communications, digital
filtering, instrumentation, medical imaging, modal analysis, numerical analysis,
seismography, and spectral analysis. The following example is taken from the
MATLAB Help pages for the fft function.
Example 1. A common use of Fourier transforms is to find the frequency compo-
nents of a signal buried in a noisy time-domain signal. Consider data sampled at
1,000 Hz. Form a signal containing a 50 Hz sinusoid of amplitude 0.7 and 120 Hz
sinusoid of amplitude 1 and corrupt it with some zero-mean random noise. Use
MATLAB to plot a graph of the signal and write a program that plots a single-sided
amplitude spectrum for the signal.

Solution. Figure 7.4a shows the sum of a 50 Hz sinusoid and a 120 Hz sinusoid
corrupted with zero-mean random noise and Fig. 7.4b displays the single-sided
amplitude spectrum of y.t /. The program for plotting the figures is listed below.

% Program 7a: Fast Fourier Transform of a Noisy Signal.


Fs=1000; % Sampling frequency.
T=1/Fs; % Sample time.
L=1000; % Length of signal.
t=(0:L-1)*T; % Time vector.
Amp1=0.7;Amp2=1;Freq1=50;Freq2=120;
7.2 The Fast Fourier Transform 145

% Sum of a 50 Hz sinusoid and a 120 Hz sinusoid.


x=Amp1*sin(2*pi*Freq1*t) + Amp2*sin(2*pi*Freq2*t);
y=x+2*randn(size(t)); % Sinusoids plus noise.
plot(Fs*t(1:50),y(1:50))
title(’Signal Corrupted with Zero-Mean Random Noise’)
xlabel(’time ms’)

NFFT=2^nextpow2(L); % Next higher power of 2 from length


of y.
Y=fft(y,NFFT)/L;
f=Fs/2*linspace(0,1,NFFT/2+1); % Linear spacing.
figure % Plot single-sided amplitude
spectrum.
plot(f,2*abs(Y(1:NFFT/2+1)))
title(’Single-Sided Amplitude Spectrum of y(t)’)
xlabel(’Frequency (Hz)’)
ylabel(’|Y(f)|’)
% You can read off the amplitudes and frequencies from the fft.

The main reason the amplitudes are not exactly at 0.7 and 1 is because of the
noise. Several executions of this code (including recomputation of y) will produce
different approximations to 0.7 and 1. The other reason for the error is due to
the finite length of the signal. Increasing L from 1,000 to 10,000 in the example
above will produce much better approximations on average.
The next example illustrates an application of FFT for finding the power spectra
of time series data. Interested readers should consult Melbourne and Gottwald [8],
who present results on the broadband nature of power spectra for diverse classes of
discrete dynamical systems. For many years, the power spectrum has been used
to distinguish periodic, quasiperiodic, and chaotic motions of certain dynamical
systems from a broad range of fields. The power spectrum plotted for a periodic or
quasiperiodic signal has discrete peaks at the harmonics and subharmonics, whilst
the chaotic signal has a broadband component in its power spectrum. In order to
illustrate these phenomena, consider the following simple example.
Example 2. Consider the two-dimensional discrete map defined by

xnC1 D 1 C ˇxn  ˛yn2


ynC1 D xn ; (7.1)

where ˛ and ˇ are constants. Suppose that ˛ D 1, plot iterative plots and power
spectra for system (7.1) when (i) ˇ D 0:05, (ii) ˇ D 0:12, and (iii) ˇ D 0:3.
Solution. The MATLAB program for producing the plots in Fig. 7.5 is listed below.

% Program 7b: Iteration of a 2D Map (see Figure 7.5(e)).


a=1;b=0.3;
N=100000;x=zeros(1,N);y=zeros(1,N);
x(1)=0.1;y(1)=0.1;
for n=1:N
x(n+1)=1-a*(y(n))^2+b*x(n);
146 7 The Image Processing Toolbox

a b
2 20

15
1

log(Power)
10
y

0
5

−1 0
−1 0 1 2 0 0.5 1
x Frequency (Hz)
c d
2 20

15
1
log(Power)

10
y

0
5

−1 0
−1 0 1 2 0 0.5 1
x Frequency (Hz)
e 2
f 20

15
1
log(Power)

10
y

0
5

−1 0
−1 0 1 2 0 0.5 1
x Frequency (Hz)

Fig. 7.5 Iterative plots and power spectra for system (7.1). (a) Periodic behavior when ˇ D 0:05.
(b) Power spectrum when ˇ D 0:05. (c) Quasiperiodic behavior when ˇ D 0:12. (d) Power
spectrum when ˇ D 0:12. (e) Chaotic behavior when ˇ D 0:3. (f) Power spectrum when ˇ D 0:3

y(n+1)=x(n);
end
plot(x(10:N),y(10:N),’.’,’MarkerSize’,1);
fsize=15;axis([-1 2 -1 2]);
set(gca,’XTick’,-1:1:2,’FontSize’,fsize)
7.3 The Fast Fourier Transform on Images 147

set(gca,’YTick’,-1:1:2,’FontSize’,fsize)
xlabel(’x’,’FontSize’,fsize)
ylabel(’y’,’FontSize’,fsize)

figure
% Power spectrum (Figure 7.5(f)).
f=-N/2+1:N/2;
freq=f*2/N;
Pow=abs(fft(x,N).^2);
plot(freq,log(Pow));
Pmax=20;axis([0 1 0 Pmax]);
set(gca,’XTick’,0:0.5:1,’FontSize’,fsize)
set(gca,’YTick’,0:5:20,’FontSize’,fsize)
xlabel(’Frequency (Hz)’);
ylabel(’log(Power)’);

7.3 The Fast Fourier Transform on Images

The two-dimensional discrete Fourier transform of an image X is computed with


the MATLAB command
>>Y=fft2(X),
computed with a fast Fourier transform algorithm. The result Y is the same size
as X. Amongst the many applications of the two-dimensional Fourier transform
there are some very interesting and useful image processing tools which include
image compression, blurring and de-blurring, sharpening, noise removal, and edge
detection, for example. Figure 7.6 depicts how to apply a low-pass filter to a jpeg
image of Lena, and Program 7c lists the MATLAB program to generate Fig. 7.6.
Note that the ideal low-pass filter applies a Gaussian function (interested readers
should consult some of the textbooks in the reference section of this chapter for
more details). By adopting the negated version of the low-pass filter one may obtain
a high pass filter that can be used for edge detection. This is left as an exercise for
the reader.

% Program 7c - Low pass filter.


input_lena = double(rgb2gray(imread(’lena.jpg’)));
% First the processing
fft_lena = fft2(input_lena);
% This bit builds an idea lowpass filter.
u = 0:(size(fft_lena,1)-1);
v = 0:(size(fft_lena,2)-1);
idx = find(u > size(fft_lena,1)/2);
u(idx) = u(idx)-size(fft_lena,1);
idy = find(v > size(fft_lena,2)/2);
v(idy) = v(idy)-size(fft_lena,2);
[V,U] = meshgrid(v,u);
D = sqrt(U.^2 + V.^2);
148 7 The Image Processing Toolbox

Fig. 7.6 Low-pass filtering of the Lena image. (a) Lena.jpg, (b) fast Fourier transform, (c) a
circular low-pass filter, and (d) a compressed image of Lena. Use the MATLAB Help pages for
function definitions and syntax

% The only parameter - 25 is the highest freqency allowed


through.
filter = double(D <= 50);
fft_lena_blurr = fft_lena.*filter;
lena_blurred = ifft2(fft_lena_blurr);
% The images.
lena_baa = [input_lena lena_blurred];
lena_baa = 255*mat2gray(lena_baa);
fft_lena_abs = log(abs(fftshift(fft_lena)));
fft_lena_blurr_abs = log(abs(fftshift(fft_lena_blurr)));
lena_ffts = [fft_lena_abs fft_lena_blurr_abs];
lena_ffts(lena_ffts==-Inf) = 0;
lena_ffts = 255*mat2gray(lena_ffts);
lena_combined = [lena_baa ; lena_ffts];
figure;
imagesc(lena_combined); axis image; colormap gray; axis off;

7.4 Exercises

1. Use the matrix M D Œ0:1; 0:2I 0:2; 0:5 to produce a multifractal image up to
stage 8. Use the Image Processing toolbox to adjust the contrast to obtain a clear
figure.
2. Use the matrix M D Œ0:1; 0:2; 0:05I 0:2; 0:05; 0:01I 0:3; 0:04; 0:05 to produce
a multifractal image up to stage 5. Use the Image Processing Toolbox to adjust
the contrast to obtain a clear figure.
References 149

3. Edit Program 7b, to produce a binary image of the green pixels in peppers.png.
Determine an approximate number of green pixels.
4. Using the MATLAB Help pages, write a MATLAB program to detect the edges
of the rice grains for rice.png.
5. Compute the first 10,000 iterates of the logistic map

xnC1 D 4xn .1  xn /;

given that x0 D 0:1. Use MATLAB to plot a power series spectrum.


6. Compute the first 10,000 iterates of the Gaussian map

xnC1 D e 8xn  0:6;


2

given that x0 D 0:1. Use MATLAB to plot a power series spectrum.


7. Compute the first 10,000 iterates of the Hénon map

xnC1 D 1 C yn  1:2xn2 ; ynC1 D 0:4xn

given that x0 D 0:1; y0 D 0. Use MATLAB to plot a power series spectrum.


8. Compute the first 10,000 iterates of the minimal chaotic neuromodule

xnC1 D 2 C 3:51 .xn /  42 .yn / ; ynC1 D 3 C 51 .xn / ;

where 1 .x/ D 2 .x/ D 1= .1 C e x /, given that x0 D 1; y0 D 0. Use


MATLAB to plot a power series spectrum.
9. Edit Program 7c to produce an ideal low-pass filter of the Lena.jpg image using
a suitable Gaussian function.
10. Carry out your own research and edit Program 7c to produce a high pass filter
used for edge detection on the Lena.jpg image.

References

1. W. Birkfellner, Applied Medical Image Processing: A Basic Course, 2nd edn. (Taylor &
Francis, New York, 2014)
2. E. Brigham, Fast Fourier Transform and Its Applications (Prentice-Hall, New Jersey, 1988)
3. J.W. Cooley, J.W. Tukey, An algorithm for the machine calculation of complex Fourier series.
Math. Comput. 19, 297–301 (1965)
4. O. Demirkaya, M.H. Asyali, P.K. Sahoo, Image Processing with MATLAB: Applications in
Medicine and Biology (CRC Press, Florida, 2008)
5. Z. Elhadj, J.C. Sprott, A minimal 2-D quadratic map with quasiperiodic route to chaos. Int.
J. Bifurcat. Chaos 18, 1567–1577 (2008)
6. R.C. Gonzalez, R.E. Woods, S.L. Eddins, Digital Image Processing Using MATLAB, 2nd edn.
(Gatesmark Publishing, Aurora, 2009)
7. E.F. James, A Student’s Guide to Fourier Transforms: With Applications in Physics and
Engineering (Cambridge University Press, Cambridge, 2011)
150 7 The Image Processing Toolbox

8. I. Melbourne, G.A. Gottwald, Power spectra for deterministic chaotic dynamical systems.
Nonlinearity 21, 279–292 (2008)
9. J.L. Semmlow, Biosignal and Medical Image Processing: MATLAB-Based Applications, 2nd
edn. (CRC Press, Florida, 2008)
10. C. Solomon, T. Breckon, Fundamentals of Digital Image Processing: A Practical Approach
with Examples in Matlab (Wiley, New Jersey, 2011)

You might also like