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

Bangladesh University of Engineering and Technology

Department of Biomedical Engineering


BME 404: Medical Imaging Sessional

Lab 02: Introduction to Image Processing with MATLAB-II

Histogram Processing and Function Plotting:

The histogram of a digital image with L total possible intensity levels in the range [0, G] is defined
as the discrete function
ℎ(𝑟 ) = 𝑛
where 𝑟 is the kth intensity level in the interval [0, L-1] and 𝑛 is the number of pixels in the
image whose intensity level is 𝑟 . The value of L-1 is 255 for images of class uint8, 65535 for
images of class uint16, and 1.0 for images of class double.
Normalized histograms, obtained simply by dividing all elements of by the total number of pixels
in the image, which we denote by n:
ℎ(𝑟 ) 𝑛
𝑝(𝑟 ) = =
𝑛 𝑛
Here k = 1, 2, 3… L. From basic probability, we recognize 𝑝(𝑟 ) as an estimate of the probability
of occurrence of intensity level 𝑟 . The core function in the toolbox for dealing with image
histograms is imhist, which has the following basic syntax:

h = imhist(f)

where f is the input image, and h is its histogram. We obtain the normalized histogram simply by
using the expression

p = imhist(f)/numel(f)
Various ways to plot an image histogram is shown below:

Example 1:

Load the image ‘grains.jpg’. Convert it to grayscale and then plot the normalized histogram using
bar plots.
I=imread('grains.jpg');
f=rgb2gray(I);
h=imhist(f);
p=h/numel(f);
horz=1:length(p);
imshow(I)
figure
bar(horz, p);

Histogram Equalization:

Histogram equalization is a technique for adjusting image intensities to enhance contrast. The
histogram equalized image g will be defined by
,

𝑔 , = 𝑓𝑙𝑜𝑜𝑟((𝐿 − 1) 𝑝 )

where floor () rounds down to the nearest integer. This is equivalent to transforming the pixel
intensities, k, of f by the function

𝑇(𝑘) = 𝑓𝑙𝑜𝑜𝑟((𝐿 − 1) 𝑝 )

The net result of this intensity-level equalization process is an image with increased dynamic
range, which will tend to have higher contrast. Note that the transformation function is really
nothing more than the cumulative distribution function (CDF). Histogram equalization is
implemented in the toolbox by function histeq, which has the syntax

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, 𝑇(𝑘) 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.

Example 2:

Implement the histogram equalization scheme on the previous image.

g=histeq(f,256);
h1=imhist(g);
p1=h1/numel(g);
horz=1:length(p1);
imshow(g)
figure
bar(horz, p1);

Linear Spatial Filter:

Linear spatial filtering operations are directly performed on image pixels. These operations work
with the values of the image pixels in the neighborhood and the corresponding values of a
subimage that has the same dimensions as the neighborhood. The subimage is called a filter,
mask, kernel, template, or window. In general, linear filtering of an image f of size M*N with a
filter mask of size m*n is given by the expression:

𝑔(𝑥, 𝑦) = 𝑤(𝑠, 𝑡)𝑓(𝑥 + 𝑠, 𝑦 + 𝑡)

where, a=(m-1)/2 and b=(n-1)/2. To generate a complete filtered image this equation must be
applied for x=0, 1, 2 … M-1 and y=0, 1, 2 … N-1. There are two closely related concepts that
must be understood clearly when performing linear spatial filtering. One is correlation; the other is
convolution. The equation above defines a correlation operation. Convolution is the same process,
except that the filter is rotated by 180o prior to the operation.

The toolbox implements linear spatial filtering using function imfilter, which has the following
syntax:
g = imfilter(f, w, filtering_mode, boundary_options, size_options)

Options for function imfilter is given in the table below:


Example 3:

This example implements a MATLAB code which illustrates the effect of different boundary
options of imfilter on an image.

Code:

close all;
clear all;
clc;
im = imread('checkerboard.jpg');
f = mat2gray(rgb2gray(im));
w = ones(31);
f1 = imfilter(f,w,0,'full'); % default zero padding
f2 = imfilter(f,w, 'replicate','full');
f3 = imfilter(f,w, 'symmetric','full');
f4 = imfilter(f,w, 'circular','full');
figure, subplot(2, 3, 1), imshow(f);
title('Original Image');
subplot(2, 3, 2), imshow(f1,[]);
title('Default');
subplot(2, 3, 3), imshow(f2,[]);
title('Replicate');
subplot(2, 3, 4), imshow(f3,[]);
title('Symmetric');
subplot(2, 3, 5), imshow(f4,[]);
title('Circular');
Output:

The toolbox supports a number of predefined 2-D linear spatial filters, obtained by using function
fspecial, which generates a filter mask, w, using the syntax
w = fspecial('type', parameters)

The spatial filters supported by fspecial are summarized in the table overleaf, including applicable
parameters for each filter.
Sharpening Filter

The Laplacian of an image, f(x, y), denoted ∇ 𝑓(𝑥, 𝑦) is defined as

𝜕 𝑓(𝑥, 𝑦) 𝜕 𝑓(𝑥, 𝑦)
∇ 𝑓(𝑥, 𝑦) = +
𝜕𝑥 𝜕𝑦
Commonly used digital approximations of the second derivatives are
𝜕 𝑓(𝑥, 𝑦)
= 𝑓(𝑥 + 1, 𝑦) + 𝑓(𝑥 − 1, 𝑦) − 2𝑓(𝑥, 𝑦)
𝜕𝑥
And
𝜕 𝑓(𝑥, 𝑦)
= 𝑓(𝑥, 𝑦 + 1) + 𝑓(𝑥, 𝑦 − 1) − 2𝑓(𝑥, 𝑦)
𝜕𝑦
So that
∇ 𝑓 = [𝑓(𝑥 + 1, 𝑦) + 𝑓(𝑥 − 1, 𝑦) + 𝑓(𝑥, 𝑦 + 1) + 𝑓(𝑥, 𝑦 − 1)] − 4𝑓(𝑥, 𝑦)

This expression can be implemented at all points (x, y) in an image by convolving the image with
the following spatial mask:

0 1 0
1 −4 1
0 1 0
The enhanced image using the Laplacian is obtained from the following equation:
𝑔(𝑥, 𝑦) = 𝑓(𝑥, 𝑦) + 𝑐∇ 𝑓(𝑥, 𝑦)
Here, c is 1 if the center coefficient of the mask is positive, or -1 if it is negative.

Example 4:

Figure shows the image of the north pole of the moon. Figure below shows the result of filtering
this image with the Laplacian mask. The image shown in the Laplacian filtered image was scaled
in the manner just described for display purposes. Note that the dominant features of the image
are edges and sharp gray-level discontinuities of various gray-level values. The background,
previously near black, is now gray due to the scaling. This grayish appearance is typical of
Laplacian images that have been scaled properly. Adding the image to the Laplacian restored the
overall gray level variations in the image, with the Laplacian increasing the contrast at the
locations of gray-level discontinuities. The net result is an image in which small details were
enhanced and the background tonality was perfectly preserved. Results like these have made
Laplacian-based enhancement a fundamental tool used frequently for sharpening digital images.

Matlab Code:

close all;
clear all;
clc;

f = imread('moon.jpg');
f1 = rgb2gray(f);

w = fspecial('laplacian',0);
display(w);

f2 = imfilter(f1, w, 'replicate');

g1 = im2double(f1);
g2 = imfilter(g1, w, 'replicate');

im = g1-g2;
figure, subplot(2,2,1), imshow(f);
title('Original image');
subplot(2,2,2), imshow(f2,[]);
title('Laplacian Filtered image (uint8)');
subplot(2,2,3), imshow(g2,[]);
title('Laplacian Filtered image (double)');
subplot(2,2,4), imshow(im);
title('Enhanced image');

Nonlinear Spatial Filter:


A commonly-used tool for generating nonlinear spatial filters in IPT is function ordfilt2, which generates
order-statistic filters (also called rank filters). These are nonlinear spatial filters whose response is based on
ordering (ranking) the pixels contained in an image neighborhood and then replacing the value of the center
pixel in the neighborhood with the value determined by the ranking result.

Because of its practical importance, the toolbox provides a specialized implementation of the 2-D median
filter:
g = medfilt2(f, [m n], padopt)
The default form of this function is
g = medfilt2(f)
which uses a neighborhood to compute the median, and pads the border of the input with 0s.
Example 5:

Median filtering is a useful tool for reducing salt-and-pepper noise in an image. The image in the
figure below is an X-ray image, f, of an industrial circuit board taken during automated inspection
of the board. The same image corrupted by salt-and-pepper noise in which both the black and
white points have a probability of occurrence of 0.2. This image was generated using function
imnoise. The bottom-left figure is the result of median filtering this noisy image. Considering the
level of noise in the top-right figure, median filtering using the default settings did a good job of
noise reduction. Note, however, the black specks around the border. These were caused by the
black points surrounding the image (recall that the default pads the border with 0s). This type of
effect can often be reduced by using the ‘symmetric' option.

Exercise 1:
Write a MATLAB code to implement the example described above and produce the results as
shown in the figure. Load the image named ‘circuit.jpg’ as input image.

Fourier Domain Processing:


Let f (x, y) denote a M x N image, where x = 0, 1, 2, 3….M-1 and y = 0, 1, 2, 3…N-1. The 2D
discrete Fourier Transform (DFT), F (u, v) is denoted by the equation

( )
𝐹(𝑢, 𝑣) = 𝑓(𝑥, 𝑦)𝑒

For u = 0, 1, 2…M-1 and v = 0, 1, 2…N-1. The frequency domain is simply the coordinate
system spanned by F (u, v), with u and v as variables.
The inverse Fourier Transform is given by
1 ( )
𝑓(𝑥, 𝑦) = 𝐹(𝑢, 𝑣)𝑒
𝑀𝑁

Letting R (u, v) and I (u, v) denote the real and imaginary component of the Fourier transform,
the Fourier Spectrum is defined as
/
𝐹(𝑢, 𝑣) = [𝑅 (𝑢, 𝑣) + 𝐼 (𝑢, 𝑣)]
The phase angle of the transform is defined as
𝐼(𝑢, 𝑣)
∅(𝑢, 𝑣) = 𝑡𝑎𝑛 [ ]
𝑅(𝑢, 𝑣)
The power spectrum is defined as the square of the magnitude
𝑃(𝑢, 𝑣) = |𝐹(𝑢, 𝑣)|

If f (x, y) is real Fourier transform is conjugate symmetric around the origin 𝐹(𝑢, 𝑣) =
𝐹 ∗ (−𝑢, −𝑣)

That means Fourier spectrum is also symmetric about the origin, 𝐹(𝑢, 𝑣) = |𝐹(−𝑢, −𝑣)|
The DFT is infinitely periodic in both the u and v directions, with the periodicity determined by
M and N,

𝐹(𝑢, 𝑣) = 𝐹(𝑢 + 𝑀, 𝑣) = 𝐹(𝑢, 𝑣 + 𝑁) = 𝐹(𝑢 + 𝑀, 𝑣 + 𝑁)


Periodicity is also the property of the inverse DFT. That is, an image obtained by taking inverse
DFT is also infinitely periodic. The DFT implementation computes with only one period. So, we
work with arrays of size M x N.

Example 6:

Let us take a matrix of size 512 x 512. Here we write a MATLAB code to obtain the Discrete
Fourier Transfrom of the matrix and display the image of Fourier spectrum. 2D DFT produces 4
back to back quarter of a period, denoted by s. We want a full, properly ordered period which can
be achieved by applying fftshift on the Fourier Spectrum. The same result could be achieved if we
multiplied the input image with (−1) prior to the transform.
close all;
clear all;
clc;
f = zeros(512);
f(231:280, 231:280)= 1;
k=surf(f);
set(k,'LineStyle','none')
F = fft2(f,512,512);
s = abs(F);
Fc = fftshift(F);
sc = abs(Fc);
log_sc = log(1+sc);
figure, subplot(2,2,1), imshow(f);
subplot(2,2,2), imshow(s,[]);
subplot(2,2,3), imshow(sc,[]);
subplot(2,2,4),imshow(log_sc,[]);
figure, subplot(1,2,1)
h1=surf(s);
set(h1,'LineStyle','none')
subplot(1,2,2),surf(sc)
h2 = surf(sc);
set(h2,'LineStyle','none')

Output:

Filtering in Frequency Domain:


The foundation of linear filtering in both the spatial and frequency domains is the convolution
theorem which can be written as

𝑓(𝑥, 𝑦) ∗ ℎ(𝑥, 𝑦) ↔ 𝐻(𝑢, 𝑣)𝐹(𝑢, 𝑣)


And conversely

𝑓(𝑥, 𝑦)ℎ(𝑥, 𝑦) ↔ 𝐻(𝑢, 𝑣) ∗ 𝐹(𝑢, 𝑣)


Images and their transforms are automatically periodic, if we choose to work with DFT.
Convolving periodic function may cause interference between adjacent periods if the periods are
close with respect to the duration of the nonzero part of the functions. This interference called
wraparound error can be avoided by padding additional zeros to the functions.
Assume the functions f (x, y) and h (x, y) are of size A x B and C x D, respectively. We form two
functions, both of size P x Q by appending zeros to f and g, where

𝑃 ≥ 𝐴 + 𝐶 − 1 𝑎𝑛𝑑 𝑄 ≥ 𝐵 + 𝐷 − 1
Example: The following function, called paddedsize, computes the minimum even values of P and
Q required tosatisfy the preceding equations. It also has an option to pad the inputs to form
square images of size equal to the nearest integer power of 2. FFT algorithms are generally faster
when P and Q are powers of 2.
function PQ = paddedsize(AB, CD, param)
if nargin == 1
PQ = 2*AB;
elseif narqin ==2 & -ischar(CD)
PQ = AB+CD-1;
PQ = 2*ceil(PQ/2);
elseif nargin==2
m=max(AB);
p = 2^nextpow2(2*m);
PQ = [p p];
else
error('Wrong number of inputs.')
end

Example 7:

In this example an image is filtered with a Gaussian low pass filter. The paddedsize function is
used before performing the DFT.
close all;
clear all;
clc;
f = zeros(256);
f(1:128, 1:256)=1;
PQ = paddedsize(size(f));
Fp= fft2(f,PQ(1),PQ(2));
sc = abs(Fp);
log_sc = log(1+sc);
sig = 20;
h = fspecial('gaussian',15,sig);
H1 = freqz2(h,PQ);
Hp = ifftshift(H1);
Gp = Hp.*Fp;
gp = real(ifft2(Gp));
gpc = gp(1:size(f,1),1:size(f,2));
figure, subplot(231), imshow(f);
subplot(232),imshow(h,[]);
subplot(233), imshow(log_sc,[]);
subplot(234), imshow(H1,[]);
subplot(235),imshow(gp,[]);
subplot(236),imshow(gpc,[])
Basic Steps in DFT filtering: (summary)
1. Obtain the padding parameters using function paddedsize: PQ = paddedsize(size(f));
2. Obtain the Fourier transform with padding:
3. Generate a filter function H of the size PQ (1) x PQ (2). If the filter is centered use fftshift
before using the filter.
4. Multiply the transform by the filter: G = Hp.*Fp;
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: gc = g(1:size(f,1),1:size(f,2));

Exercise 4:
Write a MATLAB code to generate a frequency domain filter, H, corresponding to the Sobel
spatial filter that enhances vertical edges. Then compare the result of filtering f with a Sobel mask
in the spatial domain against the result obtained by performing the filtering in the frequency
domain.
Generating Filters in Frequency Domain:
Here we illustrate how to implement filter functions directly in the frequency domain. We focus on
circularly symmetric filters that are specified as various functions of distance from the origin of the
transform.
Low pass frequency domain filters:
Filter type Mathematical expression

Ideal LPF 1 𝑖𝑓 𝐷(𝑢, 𝑣) ≤ 𝐷


𝐻(𝑢, 𝑣) =
0 𝑖𝑓 𝐷(𝑢, 𝑣) ≥ 𝐷
Butterworth LPF 1
1 + [𝐷(𝑢, 𝑣/𝐷 )]
Gaussian LPF 𝐻(𝑢, 𝑣) = 𝑒 ( , )/

Here, D0 = cutoff frequency of the filter, n = order of the Butterworth filter.


Given the transfer function Hlp (u, v) of a low pass filter we obtain the transfer function of the
corresponding high pass filter using the following relationship
𝐻 (𝑢, 𝑣) = 1 − 𝐻 (𝑢, 𝑣)

Example 8:

The following function computes the meshgrid frequency matrices.


function [U, V]= dftuv(M,N)
u = 0:M-1;
v = 0:N-1;

idx = find(u>M/2);
u(idx)= u(idx)-M;
idy = find(v>N/2);
v(idy)= v(idy)-N;

[U,V]=meshgrid(u,v);

Exercise 5:
Using the above function compute the distance squared of every point in a 8 x 5 rectangle from
the origin of the rectangle.

Exercise 6:

Write a MATLAB code to implement a Gaussian low pass filter. The image size is given as 500 x
500. Use a value of D0 equal to 5% of the padded image width.

Exercise 7:
Write a MATLAB function to implement the ideal and Butterworth low pass filters in the
frequency domain. The function should take the size of the input image, cutoff frequency and filter
order as inputs. Show the image of the spectrum of the filters. Load the image, ‘letters.jpg’ from
the directory and apply the filters to the image. Show the Fourier Spectrum of the image and the
reconstructed image. Implement the ideal, Butterworth and Gaussian high pass filters from the
transfer functions of the respective low pass filters. Produce the image of the spectrum of the high
pass filters.
Report
A hand-written report (A4, both sides) needs to be handed in during the next lab class. The lab
report must be submitted individually. Any codes/images should be given in printed form. The
lab report should contain answer to the following problems. The lab report will be graded out of
10. For the report, you must solve all the exercise problems.

You might also like