Lab 2
Lab 2
Lab 02
Objective:
This experiment introduces MATLAB Operator and Operations
Student Information
Student Name
Student ID
Date
Assessment
Marks Obtained
Remarks
Signature
1
UIT University
Department of Computer Science
CSC321 – Digital Image Processing
Lab 02
Instructions
Come to the lab in time. Students who are late more than 15 minutes, will not be allowed to attend the lab.
Students have to perform the examples and exercises by themselves.
Raise your hand if you face any difficulty in understanding and solving the examples or exercises.
Lab work must be submitted on or before the submission date.
Operator Description
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
~= Not equal to
& AND operator
| OR operator
~ NOT operator
Table 3.4: Relational and logical operators
3
It is a good idea to indent the loops for readability, especially when they are nested. Note that MATLAB
editor does it automatically. Multiple for loops can be nested, in which case indentation helps to improve
the readability. The following statements from the 5-by-5 symmetric matrix A with (i; j) element i=j for j
¸ i:
n = 5; A = eye(n);
for j=2:n
for i=1:j-1
A(i,j)=i/j;
A(j,i)=i/j;
end
end
It is important to note that if the condition inside the looping is not well defined, the looping will continue
indefinitely. If this happens, we can stop the execution by pressing Ctrl-C.
Operator precedence
We can build expressions that use any combination of arithmetic, relational, and logical operators.
Precedence rules determine the order in which MATLAB evaluates an expression. Here we add other
operators in the list. The precedence rules for MATLAB are shown in this list (Table 3.5), ordered from
highest (1) to lowest (9) precedence level. Operators are evaluated from left to right.
Precedence Operator
1 Parentheses ()
2 Transpose (: 0), power (.^), matrix power (^)
3 Unary plus (+), unary minus (¡), logical negation (»)
4 Multiplication (: ¤), right division (: =), left division (:n), matrix multiplication (¤), matrix
right division (=), matrix left division (n)
5 Addition (+), subtraction (¡)
6 Colon operator (:)
7 Less than (<), less than or equal to (·), greater (>), greater than or equal to (¸), equal to
(==), not equal to (»=)
4
8 Element-wise AND, (&)
9 Element-wise OR, (j)
Table: Operator precedence
A script file is an external file that contains a sequence of MATLAB statements. Script files have a
filename extension .m and are often called M-files. M-files can be scripts that simply execute a series of
MATLAB statements, or they can be functions that can accept arguments and can produce one or more
outputs.
2.4.1 Examples
Here are two simple scripts.
Example 1
Consider the system of equations:
x + 2y + 3z = 1
3x + 3y + 4z = 1
2x + 3y + 3z = 2
5
Find the solution x to the system of equations.
Solution:
o Use the MATLAB editor to create a file: File → New → M-File.
o Enter the following statements in the
file: A = [1 2 3; 3 3 4; 2 3 3];
b = [1; 1; 2];
x = A\b
o Save the file, for example, example1.m.
o Run the file, in the command line, by typing:
>> example1
x=
-0.5000
1.5000
-0.5000
When execution completes, the variables (A, b, and x) remain in the workspace. To see a listing of them,
enter whos at the command prompt.
Note: The MATLAB editor is both a text editor specialized for creating M-files and a graphical
MATLAB debugger. The MATLAB editor has numerous menus for tasks such as saving, viewing, and
debugging. Because it performs some simple checks and also uses color to differentiate between various
elements of codes, this text editor is recommended as the tool of choice for writing and editing M-files.
There is another way to open the editor:
>> edit
or
>> edit filename.m
to open filename.m.
a value to the variable in the command prompt. This is done by using the input command. Here is an
example.
% This script file calculates the average of points
% scored in three games.
% The point from each game are assigned to a variable
% by using the `input' command.
game1 = input('Enter the points scored in the first game ');
game2 = input('Enter the points scored in the second game ');
game3 = input('Enter the points scored in the third game ');
average = (game1+game2+game3)/3
6
The following shows the command prompt when this script file (saved as example3) is executed.
>> example3
>> Enter the points scored in the first game 15
>> Enter the points scored in the second game 23
>> Enter the points scored in the third game 10
average =
16
Output commands
As discussed before, MATLAB automatically generates a display when commands are executed. In
addition to this automatic display, MATLAB has several commands that can be used to generate displays
or outputs.
Two commands that are frequently used to generate output are: disp and fprintf. The main di®erences
between these two commands can be summarized as follows (Table 3.7).
disp . Simple to use.
. Provide limited control over the appearance of output
fprintf . Slightly more complicated than disp.
. Provide total control over the appearance of output
Table: disp and fprintf commands
Images as Matrices
The coordinate system in and the preceding discussion lead to the following representation for a digitized
image function:
The image processing may be done simply by matrix calculation or matrix manipulation.
To read an image, use the imread command. The example reads one of the sample images included with
the Image Processing Toolbox, pout.tif, and stores it in an array named I.
I = imread('pout.tif');
Now display the image. The toolbox includes two image display functions: imshow and imview. You can
use either one to display an image.
imshow(I)
Whos I
Name Size Bytes Class
ans =
Filename: 'pout2.png'
FileModDate: '29-Dec-2003 09:34:39'
FileSize: 36938
Format: 'png'
FormatVersion: []
Width: 240
Height: 291
BitDepth: 8
ColorType: 'grayscale'
8
Convert RGB image or Color map to grayscale
I = rgb2gray(RGB);
newmap = rgb2gray(map);
I = rgb2gray(RGB) converts the truecolor image RGB to the grayscale intensity image I. The rgb2gray
function converts RGB images to grayscale by eliminating the hue and saturation information while
retaining the luminance. If you have Parallel Computing Toolbox™ installed, rgb2gray can perform
this conversion on a GPU.
newmap = rgb2gray(map) returns a grayscale colormap equivalent to map.
Examples
RGB = imread('peppers.png');
imshow(RGB)
I = rgb2gray(RGB);
figure
imshow(I)
BW = im2bw(I, level)
BW = im2bw(X, map, level)
BW = im2bw(RGB, level)
BW = im2bw(I, level) converts the grayscale image I to a binary image. The output image BW
replaces all pixels in the input image with luminance greater than level with the value 1 (white) and
replaces all other pixels with the value 0 (black). Specify level in the range [0,1]. This range is relative
to the signal levels possible for the image's class. Therefore, a level value of 0.5 is midway between
black and white, regardless of class. To compute the level argument, you can use the function
graythresh. If you do not specify level, im2bw uses the value 0.5.
BW = im2bw(X, map, level) converts the indexed image X with colormap map to a binary image.
BW = im2bw(RGB, level) converts the true color image RGB to a binary image.
If the input image is not a grayscale image, im2bw converts the input image to grayscale, and then
converts this grayscale image to binary by thresholding.
Examples
load trees
BW = im2bw (X,map,0.4);
imshow(X,map), figure, imshow (BW)
9
Convert image, increasing apparent color resolution by
dithering
X = dither(RGB, map)
X = dither(RGB, map, Qm, Qe)
BW = dither(I)
X = dither(RGB, map) creates an indexed image approximation of the RGB image in the array RGB
by dithering the colors in the colo rmap map. The colormap cannot have more than 65,536 colors.
X = dither(RGB, map, Qm, Qe) creates an indexed image from RGB, where Qm specifies the number
of quantization bits to use along each color axis for the inverse color map, and Qe specifies the number
of quantization bits to use for the color space error calculations. If Qe < Qm, dithering cannot be
performed, and an un dithered indexed image is returned in X. If you omit these parameters, dither uses
the default values Qm = 5, Qe = 8.
BW = dither(I) converts the grayscale image in the matrix I to the binary (black and white)
image BW by dithering.
Examples
I = imread('cameraman.tif');
figure; imagesc(I);
colormap(gray);
Apply dithering to get an indexed image as,
BW = dither(I);
figure; imagesc(BW);
colormap(gray);
Syntax
• I = uint8(X)
• I = uint16(X)
• I = uint32(X)
• I = uint64(X)
10
Description
I = uint*(X) converts the elements of array X into unsigned integers. X can be any numeric object
(such as a double). The results of a uint* operation are shown in the next table.
double and single values are rounded to the nearest uint* value on conversion. A value of X
that is above or below the range for an integer class is mapped to one of the endpoints of the
range. For example,
• uint16(70000)
• ans =
65
53
A particularly efficient way to initialize a large array is by specifying the data type (i.e., class name)
for the array in the zeros, ones, or eye function. For example, to create a 100-by-100 uint64 array
initialized to zero, type
An easy way to find the range for any MATLAB integer type is to use the intmin and intmax
functions as shown here for uint32:
• intmin('uint32') intmax('uint32'
• ans = )
• 0 ans =
4294967295
11
Image Quantization
Quantization refers to number of bits per pixel of an image. 1:8 bits are available to quantized
an image.
If gray level is equal to 256, we have 256 different shades of gray and 8 bits per pixel, hence the image
would be a gray scale image.
Now we will reduce the gray levels of the image to see the effect on the
image.
For example
Let’s say you have an image of K=8bpp, that has L=256 different levels. It is a grayscale image and
the image look something like this:
L=256 Gray L=128 Gray
Levels Levels
K=8 K=7
K=6 K=5
K=4 K=3
K=2 K=1
Now before reducing it, further levels, we can easily see that the image has been distorted badly
by reducing the gray levels. Now we will reduce it to 2 levels, which is nothing but a simple black
and white level.
Student Exercise:
1. Select any two grayscale/color images and implement the functions you have just practiced
2. Write MATLAB code to show ‘parrot.jpg’ as increase brightness and 50% contrast using gamma
correction
3. Write MATLAB code to show gray levels of gray scale image for 𝐾 = 1:8
4. Select any three gray scale and color images and implement the functions you have just practiced.