0% found this document useful (0 votes)
6 views13 pages

Lab 2

Lab 02 of the Digital Image Processing course focuses on introducing MATLAB operators and operations, including control flow structures like loops and conditional statements. Students are required to perform exercises independently and submit their lab work on time. The lab also covers image processing concepts, such as reading, displaying, and converting images using MATLAB functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views13 pages

Lab 2

Lab 02 of the Digital Image Processing course focuses on introducing MATLAB operators and operations, including control flow structures like loops and conditional statements. Students are required to perform exercises independently and submit their lab work on time. The lab also covers image processing concepts, such as reading, displaying, and converting images using MATLAB functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Department of Computer Science

Course Code: CSC321


Course Title: Digital Image Processing
Spring 2025

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.

Objectives: MATLAB Operators and Operation


Loops, subplot function, image information

Control flow and operators


MATLAB is also a programming language. Like other computer programming languages, MATLAB has
some decision making structures for control of command execution. These decision making or control
flow structures include for loops, while loops, and if-else-end constructions. Control flow structures are
often used in script M-files and function M-files.
By creating a file with the extension .m, we can easily write and run programs. We do not need to
compile the program since MATLAB is an interpretative (not compiled) language. MATLAB has
thousands of functions, and you can add your own using m-files.
MATLAB provides several tools that can be used to control the flow of a program (script or function). In
a simple program as shown in the previous Chapter, the commands are executed one after the other. Here
we introduce the flow control structure that make possible to skip commands or to execute specific group
of commands.
MATLAB has four control flow structures: the if statement, the for loop, the while loop, and the switch
statement.

The ``if...end'' structure


MATLAB supports the variants of \if" construct.
 if ... end
 if ... else ... end
 if ... elseif ... else ... end
The simplest form of the if statement is
if expression
statements
end

Here are some examples based on the familiar quadratic formula.


1. discr = b*b - 4*a*c;
if discr < 0
disp ('Warning: discriminant is negative, roots are imaginary');
end

2. discr = b*b - 4*a*c;


if discr < 0
2
disp ('Warning: discriminant is negative, roots are imaginary');
else
disp ('Roots are real, but may be repeated')
end

3. discr = b*b - 4*a*c;


if discr < 0
disp ('Warning: discriminant is negative, roots are imaginary');
elseif discr == 0

disp ('Discriminant is zero, roots are repeated')


else
disp ('Roots are real')
end
It should be noted that:

o elseif has no space between else and if (one word)


o no semicolon (;) is needed at the end of lines containing if, else, end
o indentation of if block is not required, but facilitate the reading.
o the end statement is required

Relational and logical operators


A relational operator compares two numbers by determining whether a comparison is true or false.
Relational operators are shown in Table

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

The ``for...end'' loop


In the for ... end loop, the execution of a command is repeated at a fixed and predetermined number of
times. The syntax is
for variable = expression
statements
end
Usually, expression is a vector of the form i:s:j. A simple example of for loop is
for ii=1:5
x=ii*ii
end

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

The while...end loop


This loop is used when the number of passes is not specified. The looping continues until a stated
condition is satisfied. The while loop has the form:
while expression
statements
end

The statements are executed as long as expression is true.


x=1
while x <= 10
x = 3*x
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

2.4 M-File Scripts


So far in these lab sessions, all the commands were executed in the Command Window. The problem is
that the commands entered in the Command Window cannot be saved and executed again for several
times. Therefore, a different way of executing repeatedly commands with MATLAB is:
1. to create a file with a list of commands,
2. save the file, and
3. run the file.
If needed, corrections or changes can be made to the commands in the file. The files that are used for this
purpose are called script files or scripts for short. This section covers the following topics:
o M-File Scripts
o M-File Functions

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.

Input to a script file


When a script file is executed, the variables that are used in the calculations within the file must have
assigned values. The assignment of a value to a variable can be done in three ways.
1. The variable is defined in the script file.
2. The variable is defined in the command prompt.
3. The variable is entered when the script is executed.
We have already seen the two first cases. Here, we will focus our attention on the third one. In this case,
the variable is defined in the script file. When the file is executed, the user is prompted to assign

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:

 An image I is a matrix of pixel values


 Pixel value at p = [x,y]T is I(p) or I(x,y)
 Origin is top left corner
o I is a matrix
o p is a vector
o x, y, I(p), I(x,y) are scalars

The image processing may be done simply by matrix calculation or matrix manipulation.

What Is the Image Processing Toolbox?


The Image Processing Toolbox is a collection of functions that extend the capability of the MATLAB®
numeric computing environment. The toolbox supports a wide range of image processing operations,
including
 Spatial image transformations
 Morphological operations
 Neighborhood and block operations
 Linear filtering and filter design Transforms
 Image analysis and enhancement
 Image registration
 Deblurring
 Region of interest operations
7
Read and Display an Image
Clear the MATLAB workspace of any variables and close open figure windows.

clear, close all

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)

Check How the Image Appears in the Workspace


You can also get information about variables in the workspace by calling the whos command.

Whos I
Name Size Bytes Class

I 291x240 69840 uint8 array

Grand total is 69840 elements using 69840 bytes

Write the Image to a Disk File


To write the newly adjusted image I2 to a disk file, use the imwrite function. If you include the filename
extension '.png', the imwrite function writes the image to a file in Portable Network Graphics (PNG)
format, but you can specify other formats.
imwrite (I2, 'pout2.png');

Check the Contents of the Newly Written File


To see what imwrite wrote to the disk file, use the imfinfo function. This function returns information
about the image in the file, such as its format, size, width, and height.
imfinfo('pout2.png')

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)

Convert image to binary image, based on threshold

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);

uint8, uint16, uint32, uint64


Convert to unsigned integer

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.

Operation Output Range Output Type Bytes per Output Class


Element
uint8 0 to 255 Unsigned 8-bit 1 uint8
integer
uint16 0 to 65,535 Unsigned 16-bit 2 uint16
integer
uint32 0 to 4,294,967,295 Unsigned 32-bit 4 uint32
integer
uint64 0 to 18,446,744,073,709,551,615 Unsigned 64-bit 8 uint64
integer

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

• I = zeros(100, 100, 'uint64');

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.

Image Brightness and Contrast Adjustment

Relation of Quantization with gray level resolution:


Gray level resolution of an image can be formed using
formula,
L = 2k

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.

Reducing the gray


level

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

L=64 Gray L=32 Gray


Levels Levels

K=6 K=5

L=16 Gray L=8 Gray


Levels Levels

K=4 K=3

L=4 Gray L=2 Gray


Levels Levels

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.

You might also like