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

Bangladesh University of Engineering and Technology

Department of Biomedical Engineering


BME 404: Medical Imaging Sessional

Lab 01: Introduction to Image Processing with MATLAB

Introduction:
An image may be defined as a two-dimensional function, where x and y are spatial coordinates, and the
amplitude of at (x, y), any pair of coordinates is called the intensity or gray level of the image at that point.
When x, y, and the amplitude values of are all finite, discrete quantities, we call the image a digital image.
The field of digital image processing refers to processing digital images by means of a digital computer.
Note that a digital image is composed of a finite number of elements, each of which has a particular
location and value. These elements are referred to as picture elements, image elements, pels, and pixels.
Pixel is the term most widely used to denote the elements of a digital image. The term gray level refers to
the intensity of monochrome images. Color images are formed by a combination of individual 2D images.
For example, in RGB color system, a color image has 3 component images e.g. red, green and blue. For
this reason, many of the techniques developed for monochrome image processing may also be extended to
color images by processing the component images individually.

An image may be continuous with respect to the x- and y-coordinates and in amplitude. Converting such
an image to digital form requires the coordinates and amplitude to be digitized. Digitizing the coordinates
is called sampling and digitizing the amplitudes is called quantization.

Figure: Generating a digital image: (a) Continuous image. (b) A scan line from A to B in the continuous image. (c)
Sampling and quantization. (d) Digital scan line

© 2022, Department of Biomedical Engineering, BUET Page 1


Coordinate Convention:

The result of sampling and quantization is a matrix of real numbers. Assume that an image is sampled
such that the resulting image, f (x, y), has M rows and N columns. We say that the image is of size M ꓫ N.
The values of coordinates are discrete quantities. The image origin is defined to be at (x, y) = (0, 0). The
next coordinate values along the first row of the image are (x, y) = (0, 1). Note that x ranges from 0 to M-
1 and y ranges from 0 to N-1, in integer increments. The coordinate convention in MATLAB image
processing toolbox is different in two minor ways. First, instead of using (x, y) the toolbox uses notation
(r, c) to indicate row and column. The other difference is that the origin of the coordinate system is at (r,
c) = (1, 1); thus r ranges from 1 to M and c ranges from 1 to N. This coordinate convention is shown in
the following figure.

The coordinate system in the figure above leads to the following representation for a digitized image
function as a MATLAB matrix:

Image Processing Toolbox: Basic Image Import, Processing and Export

 imread (‘filename’): images are read into the workspace.

>> I = imread('pout.tif');

 The whos function gives additional information about an array. For example,

>> whos I
Name Size Bytes Class Attributes

I 291x240 69840 uint8

© 2022, Department of Biomedical Engineering, BUET Page 2


 Displaying Images: Images are displayed on the MATLAB desktop using imshow function.

>> imshow(f)

Here f is the image array. If not mentioned otherwise, 256 intensity levels will be used to display
it.

>> figure, imshow(f, [low high])

This syntax displays as black all values less than or equal to low and white as all values greater
than or equal to high. An image with low dynamic range can be improved for display purposes by
using the following syntax:

>> imshow(f, [ ])

montage displays multiple image frames as rectangular montage as shown in the example below.
Example:

fileFolder = fullfile(matlabroot,'toolbox','images','imdata');
dirOutput = dir(fullfile(fileFolder,'AT3_1m4_*.tif'));
fileNames = {dirOutput.name}';
montage(fileNames, 'Size', [2 5]);

Output:

 Writing Images: Images are written to the disk using imwrite, which has the following basic
syntax:
imwrite (f, ‘filename’)

With this syntax, the string contained in filename must include a recognized file format
extension. For example, the following command writes f to a file called pout2.tif

>> imwrite(I, 'pout2.jpg')

Exercise 1:
Load the image file named ‘knee1.dcm’ into MATLAB workspace. Use dicomread function to read the
image. Scale the image so that the pixel values ranges from 0 to 1. Display the image in a montage.
Image Types:

© 2022, Department of Biomedical Engineering, BUET Page 3


The toolbox deals with four types of images:
 Intensity images
 Binary Images
 Indexed Images
 RGB Images

Most monochrome image processing are carried out using binary and intensity images.

Converting between classes and Image types:

The toolbox provides specific functions (Table 1) that perform the scaling necessary to convert between
image classes and types.

Table 1

For example, function im2uint8 detects the data class of the input image and performs necessary scaling to
recognize the data as the valid image data. For example, consider the following 2 ꓫ 2 matrix, f of class
double,

f=

-0.5000 0.5000
0.7500 1.5000

>> g = im2uint8(f)

Would yield the result

g=

2×2 uint8 matrix

0 128

© 2022, Department of Biomedical Engineering, BUET Page 4


191 255

From which we see that function im2uint8 sets to 0 all values in the input that are less than 0, sets to 255
all values in the input that are greater than 1, and multiplies all other values by 255. Rounding the results
of the multiplication to the nearest integer completes the conversion.

Function im2double converts an input to class double. If the input is of class uint8, uint16, or logical,
function im2double converts it to class double with values in the range [0, 1]. As an illustration, consider
the class uint8 image.

>> h = uint8([25 50; 128 200]);

Performing the conversion

>> g = im2double(h)

yields the result

g=

0.0980 0.1961
0.5020 0.7843

from which we infer that the conversion when the input is of class uint8 is done simply by dividing each
value of the input array by 255. If the input is of class uint16 the division is by 65535.

Toolbox function mat2gray converts an image of any of the classes in Table 1 to an array of class double
scaled to the range [0, 1]. The calling syntax is

g = mat2gray (A, [Amin, Amax])

where image g has values in the range 0 (black) to 1 (white). The specified parameters, Amin and Amax,
are such that values less than Amin in A become 0 in g, and values greater than Amax in A correspond to
1 in g. The syntax
g = mat2gray(A)

Function logical converts an input array to a logical array. In the process, nonzero elements in the input
are converted to 1s, and 0s are converted to 0s in the output. An alternative conversion procedure that
often is more useful is to use a relational operator, such as >, with a threshold value. For example, the
syntax
g=f>T
produces a logical matrix containing 1s wherever the elements of f are greater than T and 0s elsewhere.

Toolbox function im2bw performs this thresholding operation in a way that automatically scales the
specified threshold in different ways, depending on the class of the input image. The syntax is
g = im2bw (f, T)

Values specified for the threshold T must be in the range [0, 1], regardless of the class of the input. The
function automatically scales the threshold value according to the input image class. For example, if f is
uint8 and T is 0.4, then im2bw thresholds the pixels in f by comparing them to 255 * 0.4 = 102.

We wish to convert the following small, double image

© 2022, Department of Biomedical Engineering, BUET Page 5


>> f = [1 2; 3 4]
f=
1 2
3 4

to binary, such that values 1 and 2 become 0 and the other two values become 1. First we convert it to the
range [0, 1]:

>> g = mat2gray(f)

g=
0 0.3333
0.6667 1.0000

Then we convert it to binary using a threshold, say, of value 0.6:

>> gb = im2bw(g, 0.6)

gb =
0 0
1 1

As mentioned earlier, we can generate a binary array directly using relational operators. Thus we get the
same result by writing

>> gb = f > 2

gb =
0 0
1 1

Image Operators:

The image arithmetic functions supported by IPT are given in the following table:

The use of different functions and operators of MATLAB are illustrated using the following examples:

© 2022, Department of Biomedical Engineering, BUET Page 6


Example 1:

This example multiplies two input images and outputs the product of the images, the maximum and
minimum values of the product and a normalized product image whose values are in the range [0, 1].
The inputs can be of class uint8, uint16 or double. The outputs are of class double.

function [p, pmax, pmin, pn] = improd(f, g)

fd = double(f);
gd = double(g);
p = fd.*gd;
pmax = max(p(:));
pmin = min(p(:));
pn = mat2gray(p);

Example 2:

This example compared several images using different JPEG quality values. Here we show how to write
these images to disc using a for loop. Suppose, we have an image f and we want to write it to a series of
JPEG files with quality factors ranging from 0 to 100 in increments of 5.

close all;
clear all;
clc;
f = imread('pout.tif');
for q = 0:5:100
filename = sprintf('series_%3d.jpg', q);
imwrite(f, filename, 'quality', q);
end

Example 3:

In this example we write an M-file to extract a rectangular subimage from the input image. The inputs to
the function are an image, the size of the subimage we want to extract and the coordinate of the top and
left corner of the subimage.

function s = subim(f, m, n, rx, ry)

s = zeros(m,n);

rxend = rx+m-1;
ryend = ry+n-1;

s = f(rx:rxend,ry:ryend);
imshow(s);

Intensity Transformation and Spatial filtering:

© 2022, Department of Biomedical Engineering, BUET Page 7


The spatial domain processes are denoted by the following expression:

𝑔(𝑥, 𝑦) = 𝑇[𝑓(𝑥, 𝑦)]

Where f (x, y) is the input image and g (x, y) is the output image and T is an operator on f, defined over a
specified neighborhood about point (x, y). In addition, T can operate on a set of images, such as
performing the addition of K images for noise reduction.

The principal approach for defining spatial neighborhoods about a point (x, y) is to use a square or
rectangular region centered at (x, y) as Fig. 2 shows. The center of the region is moved from pixel to pixel
starting, say, at the top, left corner, and, as it moves, it encompasses different neighborhoods. Operator T
is applied at each location to yield the output, g, at that location. Only the pixels in the neighborhood are
used in computing value of g at (x, y).

Figure: A neighborhood of size 3 x 3 about a point (x, y) in an image.

Intensity Transformation:

The simplest form of the transformation T is when the neighborhood in is of size 1 x 1(a single pixel). In
this case, the value of g at (x,y) depends only on the intensity of at that point, and T becomes an intensity
or gray-level transformation function. These two terms are used interchangeably, when dealing with
monochrome (i.e., gray-scale) images. Because they depend only on intensity values, and not explicitly
on (x, y) intensity transformation functions frequently are written in simplified form as
𝑠 = 𝑇(𝑟)
where r denotes the intensity of f and s the intensity of g, both at any corresponding point (x, y) in the
images.

Function imadjust: Function imadjust is the basic IPT tool for intensity transformations of grayscale
images. It has the syntax

g = imadjust(f, [low_in high_in], [low_out high_out], gamma)

As illustrated below, this function maps the intensity values in image f to new values in g, such that values
between low_in and high_in map to values between low_out and high_out.

© 2022, Department of Biomedical Engineering, BUET Page 8


The input image can be of class uint8, uint16, or double, and the output image has the same class as the
input. All inputs to function imadjust, other than f, are specified as values between 0 and 1, regardless of
the class of f. If f is of class uint8, imadjust multiplies the values supplied by 255 to determine the actual
values to use; if f is of class uint16, the values are multiplied by 65535. Using the empty matrix ([ ]) for
[low_in high_in] or for [low_out high_out] results in the default values [0 1]. If high_out is less than
low_out, the output intensity is reversed. Parameter gamma specifies the shape of the curve that maps the
intensity values in f to create g.

Example 4:

A digital mammogram image is given showing a small lesion. A photographic negative of the image is
obtained using imadjust command shown in Fig (b). An intensity band of interest is highlighted shown in
Fig (c). Fig (d) shows the result of enhancing the image using gamma =2 which compresses the low end
but expands the high end of the image.

Figure: (a) Original digital mammogram. (b) Negative image. (c) Result of expanding the intensity range
[0.5, 0.75]. (d) Result of enhancing the image with gamma = 2.

© 2022, Department of Biomedical Engineering, BUET Page 9


Matlab Code:

close all;
clear all;
clc;

f = imread('mammogram1.jpg');
[r c h] = size(f);
I = uint8(zeros(r, c, h, 4));
I(:,:,:,1)= f;
I(:,:,:,2)= imadjust(f,[0 1],[1 0],1);
I(:,:,:,3)= imadjust(f,[0.5 .75],[0 1],1);
I(:,:,:,4)= imadjust(f,[0.5 0.75],[0 1],2);

figure,montage(I, 'Size', [2 2])

Exercise 2:

Write a MATLAB function to implement the intensity transformation function s = T(r) which will yield a
photographic negative of an input image.

Logarithmic and Contrast stretching Transformation

Logarithmic and contrast-stretching transformations are basic tools for dynamic range manipulation.
Logarithm transformations are implemented using the expression
g = c*log(1 + double(f))
where c is a constant. Note, however, that the shape of the gamma curve is variable, whereas the shape of
the log function is fixed.
One of the principal uses of the log transformation is to compress dynamic range. For example, it is not
unusual to have a Fourier spectrum with values in the range [0, 106] or higher. When displayed on a
monitor that is scaled linearly to 8 bits, the high values dominate the display, resulting in lost visual detail
for the lower intensity values in the spectrum. By computing the log, a dynamic range on the order of, for
example, is reduced to approximately 14, which is much more manageable.

Exercise 3:

(a) Write a MATLAB code to plot the logarithmic intensity mapping function for input intensity
values ranging from 0 to 255.
(b) Write a MATLAB code to implement the logarithmic function on a given image.

Contrast Stretching Function

The contrast stretching function is expressed as


1
𝑠=
1 + (𝑚/𝑟)𝐸

where r represents the intensities of the input image, s the corresponding intensity values in the output
image, and E controls the slope of the function. This equation is implemented in MATLAB for an entire
image as

© 2022, Department of Biomedical Engineering, BUET Page 10


g = 1./(1 + (m./(double(f) + eps)).^E)

This function compresses the input levels lower than m into a narrow range of dark levels in the output
image; similarly, it compresses the values above m into a narrow band of light levels in the output. The
result is a higher contrast.

Exercise 4:

Write a MATLAB code to compute a contrast stretching transformation on an input image ‘skeleton.jpg’ for values
of m = M/2, M, 2M where M is the average intensity of the input image and E=.5, .9, 2. Show the resulting images
in a montage.

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.

© 2022, Department of Biomedical Engineering, BUET Page 11

You might also like