Basic MATLAB Commands Practical No.: Date

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

Basic MATLAB commands

Practical No.: Date:


Aim: Study about basic MATLAB commands.

Theory:
MATLAB is a mathematical and graphical software package; it has numerical, graphical, and
programming capabilities. It has built-in functions to do many operations, and there are toolboxes
that can be added to augment these functions (e.g., for signal processing). There are versions
available for different hardware platforms, and there are both professional and student editions.

In the Command Window, MATLAB can be used interactively. At the prompt, any MATLAB
command or expression can be entered, and MATLAB will immediately respond with the result.

It is also possible to write programs in MATLAB, which are contained in script files or M-files.

The format of an assignment statement is variablename = expression. The variable is always on


the left, followed by the assignment operator, = (unlike in mathematics, the single equal sign does
not mean equality), followed by an expression. The expression is evaluated and then that value is
stored in the variable. For example, this is the way it would appear in the Command Window:

>> mynum = 6

mynum = 6

>>

MATLAB uses a default variable named ans if an expression is typed at the prompt and it is not
assigned to a variable. For example, the result of the expression 6 3 is stored in the variable ans:

>> 6 + 3

ans =

A short-cut for retyping commands is to press the up-arrow, which will go back to the previously
typed command(s).

 Initializing, Incrementing, and Decrementing

Gandhinagar Institute of Technology CV


Frequently, values of variables change. Putting the first or initial value in a variable is called
initializing the variable. Adding to a variable is called incrementing. For example, the statement

mynum = mynum + 1 increments the variable mynum by 1.

 Variable Names
 Variable names are an example of identifier names. The rules for identifier names are:
 The name must begin with a letter of the alphabet. After that, the name can contain letters,
digits, and the underscore character (e.g., value_1), but it cannot have a space.
 There is a limit to the length of the name; the built-in function namelengthmax tells how
many characters this is.
 MATLAB is case-sensitive. That means that there is a difference between upper- and
lowercase letters. So, variables called mynum, MYNUM, and Mynum are all different.
 There are certain words called reserved words that cannot be used as variable names.
 Names of built-in functions can, but should not, be used as variable names.

The following commands relate to variables:

 who shows variables that have been defined in this Command Window (this just shows the
names of the variables)
 whos shows variables that have been defined in this Command Window (this shows more
information on the variables, similar to what is in the Workspace Window)
 clear clears out all variables so they no longer exist
 clear variablename clears out a particular variable

If nothing appears when who is entered, that means there aren’t any variables! For example, in the
beginning of a MATLAB session, variables could be created and then selectively cleared
(remember that the semicolon suppresses output):

>> who

>> mynum = 3;

>> mynum + 5;

>> who

Gandhinagar Institute of Technology CV


Your variables are:

ans mynum

>> clear mynum

 Expressions and format functions

The default in MATLAB is to display numbers that have decimal places with

four decimal places


>> 2 * sin(1.4)
ans = 1.9709

The format command can be used to specify the output format of expressions. There are many
options, including making the format short (the default) or long. For example, changing the format
to long will result in 15 decimal places.

>> format long

>> 2 * sin(1.4)

ans =

1.970899459976920

>> 3 + 55 – 62 + 4 – 5 ...

+ 22 – 1

ans =

16

 Operators

There are in general two kinds of operators: unary operators, which operate on a single value or
operand; and binary operators, which operate on two values or operands. The symbol “–”, for
example, is both the unary operator for negation and the binary operator for subtraction.

Here are some of the common operators that can be used with numeric expressions:

Gandhinagar Institute of Technology CV


+ addition

– negation, subtraction

* multiplication

/ division (divided by e.g. 10/5 is 2)

\ division (divided into e.g. 5\10 is 2)

^ exponentiation (e.g., 5^2 is 25)

Operator Precedence Rules: Some operators have precedence over others. For example, in the
expression 4 5 * 3, the multiplication takes precedence over the addition, so first 5 is multiplied
by 3, then 4 is added to the result. Using parentheses can change the precedence in an expression:

>> 4 + 5 * 3

ans =19

 Types

MATLAB supports many types of values, which are called classes. A class is essentially a
combination of a type and the operations that can be performed on values of that type. For example,
there are types to store different kinds of numbers. For float or real numbers, or in other words
numbers with a decimal place (e.g., 5.3), there are two basic types: single and double. The name
of the type double is short for double precision; it stores larger numbers than single. MATLAB
uses a floating point representation for these numbers. For integers, there are many integer types
(e.g., int8, int16, int32, and int64).

>> intmin(‘int8’)

ans =

–128

>> intmax(‘int8’)

ans =

127

Gandhinagar Institute of Technology CV


The function rand can be used to generate random real numbers; calling it generates one random
real number in the range from 0 to 1. There are no arguments passed to the rand function. Here are
two examples of calling the rand function:

>> rand

ans =

0.9501

>> rand

ans =

0.2311

The seed for the rand function will always be the same each time MATLAB is started, unless the
state is changed, for example, by the following: rand(‘state’, sum(100*clock))

This uses the current date and time that are returned from the built-in clock function to set the seed.

To generate a random real number in the range from low to high, first create the variables low and
high. Then, use the expression rand*(high–low) low. For example, the sequence

>> low = 3;

>> high = 5;

>> rand*(high–low)+low would generate a random real number in the range from 3 to 5.

 Characters and encoding

Convert the character ‘a’ to its numeric equivalent, the following statement could be used:

>> numequiv = double(‘a’)

numequiv = 97

>> numequiv = double(‘a’);

Gandhinagar Institute of Technology CV


>> char(numequiv + 1)

ans = b

>> ‘a’ + 2

ans = 99

>> double(‘abcd’)

ans = 97 98 99 100

>> char(‘abcd’+ 1)

ans = bcde

Exercises:

1. Write and executes basic commands using MATLAB.

Review Questions:
1. What is MATLAB?
2. Explain fundamental steps in digital image processing.

Gandhinagar Institute of Technology CV


Perform functions on array using MATLAB
Practical No.: Date:
Aim: Write a program to perform functions on array using MATLAB.

Theory:

In this practical, we will understand the fundamentals related to matrix. Vectors and matrices are
used to store sets of values, all of which are the same type. A vector can be either a row vector or
a column vector. A matrix can be visualized as a table of values. The dimensions of a matrix are r
× c, where r is the number of rows and c is the number of columns. This is pronounced “r by c.” If
a vector has n elements, a row vector would have the dimensions 1 × n, and a column vector would
have the dimensions n × 1. A scalar (one value) has the dimensions 1 × 1. Therefore, vectors and
scalars are actually just subsets of matrices.

The scalar is 1 × 1, the column vector is 3 × 1 (3 rows by 1 column), the row vector is 1 × 4 (1 row
by 4 columns), and the matrix is 3 × 3. All the values stored in these matrices are stored in what
are called elements. MATLAB is written to work with matrices; the name MATLAB is short for
“matrix laboratory.” For this reason, it is very easy to create vector and matrix variables, and there
are many operations and functions that can be used on vectors and matrices.

 Creating Row Vectors

There are several ways to create row vector variables. The most direct way is to put the values that
you want in the vector in square brackets, separated by either spaces or commas. For example,
both of these assignment statements create the same vector v:

>> v = [1 2 3 4]

v=1234

>> v = [1, 2, 3, 4]

v=1234

The colon operator can be used to iterate through these values. For example, 1:5 results in all the
integers from 1 to 5:

Gandhinagar Institute of Technology CV


>> vec = 1:5

vec = 1 2 3 4 5

Note that in this case, the brackets [ ] are not necessary to define the vector. With the colon
operator, a step value can also be specified with another colon,

 Creating Column Vectors

One way to create a column vector is by explicitly putting the values in square brackets,
separated by semicolons:

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

c=

 Declaring matrices:

There is no need to declare variables; new variables are simply introduced as they are required.

A = [1 2 3; 4 5 6; 7 8 9]

The above command declares following matrix:

1 2 3

A= 4 5 6

7 8 9

Keep following things in mind while declaring variables/matrices:

No spaces

Don’t start with a number

Variable names are case sensitive

 Populating matrix elements with zeros:

Gandhinagar Institute of Technology CV


MATLAB also provides a number of functions which can be used to populate a new matrix with
particular values. For example to make a matrix full of zeroes we can use the function zeros(m, n)
which creates an m*n matrix of zeros as follows:

B = zeros(3,3)

0 0 0

B= 0 0 0

0 0 0

 Knowing size of matrix: Syntax:

[rows, cols] = size(A);

This command gives size of matrix

Above command gives result: rows=3, cols=3

The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript
arrays, and specify for iterations.

If you want to create a row vector, containing integers from 1 to 10, you write −1:10

Format Purpose

A(:,j) is the jth column of A.

A(i,:) is the ith row of A.

A(:,:) is the equivalent two-dimensional array. For matrices this is the same as A.

A(j:k) is A(j), A(j+1),...,A(k).

A(:,j:k) is A(:,j), A(:,j+1),...,A(:,k).

Gandhinagar Institute of Technology CV


A(:,:,k) is the kth page of three-dimensional array A.

A(i,j,k,:) is a vector in four-dimensional array A. The vector includes A(i,j,k,1),


A(i,j,k,2), A(i,j,k,3), and so on.

A(:) is all the elements of A, regarded as a single column. On the left side of an
assignment statement, A(:) fills A, preserving its shape from before. In this
case, the right side must contain the same number of elements as A.

Example:
A = [1 2 3 4; 4 5 6 7; 7 8 9 10]
A(:,2:3) % second and third column of A
A(:,2) % second column of A
A(:,2:3) % second and third column of A
A(2:3,2:3) % second and third rows and second and third columns

When you run the file, it displays the following result −

A=
1 2 3 4
4 5 6 7
7 8 9 10

ans =
2
5
8

ans =
2 3
5 6
8 9

ans =
5 6
8 9

Gandhinagar Institute of Technology CV


MATLAB provides the following functions to convert to various numeric data types −

Function Purpose

double Converts to double precision number

single Converts to single precision number

int8 Converts to 8-bit signed integer

int16 Converts to 16-bit signed integer

int32 Converts to 32-bit signed integer

int64 Converts to 64-bit signed integer

uint8 Converts to 8-bit unsigned integer

uint16 Converts to 16-bit unsigned integer

uint32 Converts to 32-bit unsigned integer

uint64 Converts to 64-bit unsigned integer

To plot the graph of a function, you need to take the following steps −

Define x, by specifying the range of values for the variable x, for which the function is to be plotted

Define the function, y = f(x)

Call the plot command, as plot(x, y)

Following example would demonstrate the concept. Let us plot the simple function y = x for the
range of values for x from 0 to 100, with an increment of 5.

Gandhinagar Institute of Technology CV


Create a script file and type the following code −

x = [0:5:100];
y = x;
plot(x, y)

MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to adjust
the axes to spruce up the graph.

 The xlabel and ylabel commands generate labels along x-axis and y-axis.

 The title command allows you to put a title on the graph.

 The grid on command allows you to put the grid lines on the graph.

 The axis equal command allows generating the plot with the same scale factors and the
spaces on both axes.

 The axis square command generates a square plot.

Exercises:

1. Perform plot graph for below example


x = [1 2 3 4 5 6 7 8 9 10];
x = [-100:20:100];
y = x.^2;

2. Perform commands related to graph.

Review Questions:
1. Write short notes on sampling and quantization.

Gandhinagar Institute of Technology CV


Looping concept using MATLAB
Practical No.: Date:
Aim: Write a program to perform looping concept using MATLAB.

Theory:

MATLAB provides following types of loops to handle looping requirements. Click the following
links to check their detail –
 While loop: Repeats a statement or group of statements while a given condition is true. It tests
the condition before executing the loop body.

The syntax of a while loop in MATLAB is −

while <expression>

<statements>

end

The while loop repeatedly executes program statement(s) as long as the expression remains true.
An expression is true when the result is nonempty and contains all nonzero elements (logical or
real numeric). Otherwise, the expression is false.

 For loop: Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.

Syntax

The syntax of a for loop in MATLAB is −

for index = values

<program statements>

Gandhinagar Institute of Technology CV


...

end

 Nested loops: You can use one or more loops inside any another loop. MATLAB allows to use
one loop inside another loop. Following section shows few examples to illustrate the concept.
Syntax: The syntax for a nested for loop statement in MATLAB is as follows −

for m = 1:j

for n = 1:k

<statements>;

end

end

The syntax for a nested while loop statement in MATLAB is as follows −

while <expression1>

while <expression2>

<statements>

end

end

 Break statement: break exits only from the loop in which it occurs. Control passes to the
statement following the end of that loop.

a = 10;

% while loop execution

while (a < 20 )

fprintf('value of a: %d\n', a);

a = a + 1;

if( a > 15)

% terminate the loop using break statement

break;

Gandhinagar Institute of Technology CV


end

end

When you run the file, it displays the following result −

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

Exercises:

1. Write a program to print 10 to 20 using while loop and for loop.


2. Perform image related operations on image using MATLAB.

Review Questions:
1. Discuss types of adjacency between pixels with example.

Gandhinagar Institute of Technology CV


[This page is intentionally left blank]

Gandhinagar Institute of Technology CV


Zoom in and zoom out of image using MATLAB
Practical No.: Date:
Aim: Write a program to zoom in and zoom out of image using MATLAB.

Theory:

 Reading Image file

We can use following command to read image file:

myImage=imread(‘File name with path’)

If name of the image file is test.bmp and if it is in /home/chv folder above commands can be written
as: myImage=imread(‘/home/chv/test.bmp’)

The image filename can be given as a full file path or as a file path relative to the SciLab current
directory. The current directory can be changed from the main SciLab interface window or by cd
(change directory command). The supported file formats include ‘bmp’, ‘gif’, ‘jpg’ and ‘png’.

After giving above command image data is available in myImage variable.

You can use any variable name.

 Displaying image

After reading image data using above function, we can display images in SciLab using imshow
function. This function simply takes the array storing the image values as its only parameter.
Syntax:

imshow(<variable name>)

Example:

imshow(myImage);

Knowing size of image in pixels:

Size of the image in pixels can be found out by following command:

[Rows, Cols] = size(myImage)

Gandhinagar Institute of Technology CV


The importdata function allows loading various data files of different formats. It has the
following five forms:

1. A = importdata(filename)

Loads data into array A from the file denoted by filename.

2. A = importdata('-pastespecial')

Loads data from the system clipboard rather than from a file.

3. A = importdata( , delimiterIn)

Interprets delimiterIn as the column separator in ASCII file, filename, or the clipboard data. You
can use delimiterIn with any of the input arguments in the above syntaxes.

4. A = importdata( , delimiterIn, headerlinesIn)

Loads data from ASCII file, filename, or the clipboard, reading numeric data starting from line
headerlinesIn+1.

5. [A, delimiterOut, headerlinesOut] = importdata( )

Returns the detected delimiter character for the input ASCII file in delimiterOut and the detected
number of header lines in headerlinesOut, using any of the input arguments in the previous
syntaxes.

 Image resizing

Image resizing can be done by following command:

imresize(Image,{Parameters});

For example:

Consider that we read the image in variable myImage using imread function than we can resize
the image stored in this variable by following command

 imresize(myImage,[256,256],’nearest’);

This command will convert image of any size into image of 256x256 using nearest neighbor
technique.

 Converting Color image into Grayscale image:

Color image can be converted into Grayscale image by matlab function rgb2gray.

Example: myGrayImage=rgb2gray(myImage)

Gandhinagar Institute of Technology CV


 Converting Color image into Binary Image:

Color image can be converted into Binary image using function im2bw:

Example: myBWImage=im2bw(myImage)

Where myImage is 2D image data

 Intensity profile along line given by two points on image

Drawing of intensity profile along single line on given image (Scan one line along the image and
draw intensity values (1-D signal)) can be done by function improfile()

Example: improfile(myImage,[0,150],[200,150]);

If given image is chess-board pattern, profile graph would be squarewave.

 Separate color image into three separate R,G,B planes

If we read given color image using imread() function, we get 3-D matrix. To separate out R,G
and B planes, we can read each plane separately as follows:

Example:

myImage=imread(‘RGBBar.bmp’);

RED=myImage(:,:,1);

GREEN=myImage(:,:,2);

BLUE=myImage(:,:,3);

 Combine three separate R,G,B planes to create color image

If we have three R,G and B planes separately and if we want to create color image from it, we
can use concatenate function: Example:

newImage=cat(3,RED,BLUE,GREEN)

Exercises:

1. Write a program to zoom in and zoom out of image using MATLAB.

Review Questions:
1. Explain how zooming and interpolation method work in images.

Gandhinagar Institute of Technology CV


[This page is intentionally left blank]

Gandhinagar Institute of Technology CV


Point processing method to obtain negative image, inverse image, log image
and gamma image
Practical No.: Date:
Aim: Write image processing programs using point processing method to obtain negative
image, inverse image, log image and gamma image.

Theory:

Image enhancement can be done in two domain:


[1] Spatial Domain and
[2] Transform domain.

In Spatial domain Image processing, there are two ways: Point processing (Single pixel is
processed at a time). Neighborhood processing (Mask processing) Convolution of 3x3 or 5x5 or
other size of mask with image

In point processing, Grey level transformation can be given by following equation


g(x,y)=T(f(x,y))  s=T(r)

Where, f(x,y) is original image, g(x,y) is transformed image


s = gray level of transformed image
r = gray level of original image
Threshold operation:

Gandhinagar Institute of Technology CV


In threshold operation, Pixel value greater than threshold value is made white and pixel value less
than threshold value is made black. If we consider image having gray levels r and if grey levels in
output image is s than,

S=0 if r ≤ m
S=255 if r > m
Where m=threshold

 Pseudocode for thresholding:


filename=input('Enter file name: ','s'); y=imread(filename);
T=input('Enter threshold value between 0 to 255: '); if(ndims(y)==3)
y=rgb2gray(y);
end [m,n]=size(y); imshow(y); for i=1:m
for j=1:n

if(y(i,j)>T)
y(i,j)=255;
else
y(i,j)=0;
end
end
end
figure;

imshow(y);
Run above program for different threshold values and find out optimum threshold value for which
you are getting better result.

 Horizontal flipping:
% Read in an image
filename=input('Enter file name: ','s'); imagedata = imread(filename); if(ndims(imagedata)==3)
imagedata=rgb2gray(imagedata);

Gandhinagar Institute of Technology CV


end
%Determine the size of the image [rows,cols] = size(imagedata);
%Declare a new matrix to store the newly created flipped image FlippedImageData =
zeros(rows,cols);
%Generate the flipped image
for r = 1:rows
for c = 1:cols
end FlippedImageData(r,cols+1-c) = imagedata(r,c);
end

%Display the original image and flipped image


subplot(2,1,1); imshow(imagedata) ;
subplot(2,1,2); imshow(FlippedImageData,[]);

%Write flipped image to a file


imwrite(mat2gray(FlippedImageData),'FlipTest.jpg','quality',99);

 Negative Image:
Negative Image can be obtained by subtracting each pixel value from 255.
255

s
s = 255-r

r 255

MATLAB Program to obtain Negative Image:


% To obtain Negative Image
[namefile,pathname]=uigetfile({'*.bmp;*.tif;*.jpg;*.gif','IMAGE Files
(*.bmp,*.tif,*.jpg,*.gif)'},'Choose GrayScale Image'); img=imread(strcat(pathname,namefile));
if(size(img,3)==3) img=rgb2gray(img); end

Gandhinagar Institute of Technology CV


[rows,cols]=size(img);
neg_img=zeros(rows,cols);
for r = 1:rows
for c = 1:cols
neg_img(r,c) = 255-img(r,c); %Calculate negative image
end

end
%Display original and negative images
subplot(2,1,1); imshow(img);
subplot(2,1,2); imshow(neg_img,[]);

 Contrast Stretching
Contrast Stretching means Darkening level below threshold value m and whitening level above
threshold value m. This technique will enhance contrast of given image. Thresholding is example
of extreme constrast stretching.

Practically contrast stretching is done by piecewise linear approximation of graph shown in left by
following equations:
s = x.r 0 ≤ r<a
s = y.r a ≤ r<b
s = z.r b ≤ r<255

Where x,y and z are different slopes


Pseudocode for contrast stretching:
% two threshold values a & b

Gandhinagar Institute of Technology CV


clc;
clear all;
[namefile,pathname]=uigetfile({'*.bmp;*.tif;*.tiff;*.jpg;*.jpeg;*.gif','IMAGEFiles
(*.bmp,*.tif,*.tiff,*.jpg,*.jpeg,*.gif)'},'Chose GrayScale Image');
img=imread(strcat(pathname,namefile));
if(size(img,3)==3)
img=rgb2gray(img);
end
[row, col]=size(img);
newimg=zeros(row,col);
a=input('Enter threshold value a: ');
b=input('Enter threshold value b: ');
for i=1:row

for j=1:col
if(img(i,j)<=a)
newimg(i,j)=img(i,j);
end
if (img(i,j)>a && img(i,j)<=b)
newimg(i,j)=2*img(i,j);
end
if(img(i,j)>b)
newimg(i,j)=img(i,j);
end

end
end
subplot(2,1,1); imshow(uint8(img)); subplot(2,1,2); imshow(uint8(newimg));

Gandhinagar Institute of Technology CV


Exercises:

1. Write image processing programs using point processing method to obtain negative image,
inverse image, log image and gamma image.

Review Questions:

1. What is contrast stretching?


2. Give the formula for negative, log transformation and Gamma transformation.

Gandhinagar Institute of Technology CV


Perform arithmetic operations on image using MATLAB
Practical No.: Date:
Aim: Write a program to perform arithmetic operations on image using MATLAB.

Theory:
Arithmetic operations like image addition, subtraction, multiplication and division is possible. If
there is two images I1 and I2 then addition of image can be given by:

I(x,y) = I1(x,y) + I2(x,y)

Where I(x,y) is resultant image due to addition of two images. x and y are coordinates of image.
Image addition is pixel to pixel. Value of pixel should not cross maximum allowed value that is
255 for 8 bit grey scale image. When it exceeds value 255, it should be clipped to 255.

To increase overall brightness of the image, we can add some constant value depending on
brightness required. In example program we will add value 50 to the image and compare brightness
of original and modified image.

To decrease brightness of image, we can subtract constant value. In example program, value 100
is subtracted for every pixel. Care should be taken that pixel value should not less than 0 (minus
value). Subtract operation can be used to obtain complement (negative) image in which every pixel
is subtracted from maximum value i.e. 255 for 8 bit greyscale image.

Multiplication operation can be used to mask the image for obtaining region of interest. Black and
white mask (binary image) containing 1s and 0s is multiplied with image to get resultant image.
To obtain binary image function im2bw() can be used. Multiplication operation can also be used
to increase brightness of the image

Division operation results into floating point numbers. So data type required is floating point
numbers. It can be converted into integer data type while storing the image. Division can be used
to decrease the brightness of the image. It can also used to detect change in image.

Program for image addition between two similar images:


clc
close all

Gandhinagar Institute of Technology CV


I1 = imread('cameraman.tif');
I2 = imread('rice.png');
subplot(2, 2, 1);
imshow(I1);title('Original image I1');
subplot(2, 2, 2);imshow(I2);title('Original image I2'); I=I1+I2;

% Addition of two images


subplot(2, 2, 3);imshow(I);title('Addition of image I1+I2'); I=I1-I2; %Subtraction of two images
subplot(2, 2, 4);imshow(I);title('Subtraction of image I1-I2'); figure;
subplot(2, 2, 1);imshow(I1);title('Original image I1'); I=I1+50;
subplot(2, 2, 2);imshow(I);title('Bright Image I'); I=I1-100;
subplot(2, 2, 3);imshow(I);title('Dark Image I'); M=imread('Mask.tif');
M=im2bw(M) % Converts into binary image having 0s and 1s I=uint8(I1).*uint8(M); %Type
casting before multiplication subplot(2, 2, 4);imshow(I);title('Masked Image I');

Result after execution of program:


Original image I1 Original image I2

Addition of image I1+I2 Subtraction of image I1-I2

Gandhinagar Institute of Technology CV


Original image I1 Bright Image I

Dark Image I Masked Image I

Display image with different brightness:


close all;
clear all;
[filename,pathname]=uigetfile({'*.bmp;*.jpg;*.gif','Choose Image File'});
myimage=imread(filename);
if(size(myimage,3)==3)
myimage =rgb2gray(myimage);
end
[Rows, Cols] = size(myimage)
newimage=zeros(Rows,Cols);
k=1;

while k<5,
for i = 1:Rows
for j = 1:Cols
if k==1

Gandhinagar Institute of Technology CV


newimage(i,j)=myimage(i,j)-100;
end

if k==2
newimage(i,j)=myimage(i,j)-50;
end
if k==3
newimage(i,j)=myimage(i,j)+50;
end
if k==4
newimage(i,j)=myimage(i,j)+50;
end
end
end
subplot(2,2,k); imshow(newimage,[]); k=k+1;
end

Result:

Calculate mean value:

Gandhinagar Institute of Technology CV


Mean value can be calculated by MATLAB function mean()
Alternately following code can be used to calculate mean value:
[Rows, Cols] = size(myimage)
newimage=zeros(Rows,Cols);
total = 0;
for i = 1:Rows
for j = 1:Cols
total = total + myimage(i,j);
end

end
average=total/(Rows*Cols)

Exercises:

1. Write a program to perform arithmetic operations on image using MATLAB.

Review Questions:
1. Explain arithmetic coding and Huffman coding.

Gandhinagar Institute of Technology CV


[This page is intentionally left blank]

Gandhinagar Institute of Technology CV


Histogram equalization and matching of image
Practical No.: Date:
Aim: Write a program for histogram equalization and matching of image.

Theory:
 Histogram is bar-graph used to profile the occurrence of each gray level in the
image

 Mathematically it is represented as h(rk)=nk

 Where rk is kth grey level and nk is number of pixel having that grey level

 Histogram can tell us whether image was scanned properly or not. It gives us idea
about tonal distribution in the image.
 Histogram equalization can be applied to improve appearance of the image
 Histogram also tells us about objects in the image. Object in an image

 have similar gray levels so histogram helps us to select threshold value for object
detection.

 Histogram can be used for image segmentation.

Pseudo code:
Calculate histogram
Loop over ROWS of the image

Loop over COLS of the image i=1 to rows


Pixel value j=1 to cols
hist(k)=hist(k)+1 k=data(i,j)
End COLS loop

End ROWS loop


Calculate sum of the hist:
Loop over gray levels
i = 0 to no. of gray levels

Gandhinagar Institute of Technology CV


sum=sum+hist(i);
sum_of_hist(i)=sum;
End loop
Area of image = rows*cols
Dm=Number of gray levels in the output image
Loop over ROWS

Loop over COLS


k = data(i,j)

data(i,j) = (Dm/area)*sum_of_hist(k)
End COLS oop
End ROWS Loop
Standard MATLAB function for histogram and histogram equalization:
[1] imhist function

It computes histogram of given image and plot Example:

myimage=imread(‘tier.jpg’)
imhist(myimage);

[2] histeq function

It computes histogram and equalize it. Example:

myimage = imread(‘rice.bmp’);
newimage= histeq(myimage);

Exercises:

1. Write a program for histogram equalization and matching of image.

Review Questions:
1. What is meant by histogram equalization?

Gandhinagar Institute of Technology CV


To understand various image noise models and to write programs for image
morphological operations using Minimum, maximum and average filter
Practical No.: Date:
Aim: To understand various image noise models and to write programs for image
morphological operations using Minimum, maximum and average filter.

Theory:
Morphological image processing is a technique introducing operations for transforming images in
a special way which takes image content into account. The most common morphological
operations are minimum (also known as dilation) and maximum (erosion) filters. The minimum
filter extends object boundaries, whereas the maximum filter erodes shapes on the image.

In morphological filters, each pixel is updated based on comparing it against surrounding pixels in
the running window. The running window is an image area around a current pixel with a defined
radius. For example, if we specify the radius = 1, the running window will be a 3x3 square around
the target pixel.

 In image processing, we use mathematical morphology to extract image components which


are useful in representation and description of region shape such as … Boundaries,
Skeletons, Convex hull, Thinning, Pruning etc.
 Two Fundamental morphological operations are: Erosion and dilation
 Dilation adds pixels to the boundaries of objects in an image, while erosion removes pixels
on object boundaries.
 Erosion and dilation are two fundamental image morphological operations.
 Dilation adds pixels to the boundaries of objects in an image, while erosion removes pixels
on object boundaries.
 Dilation operation: The value of the output pixel is the maximum value of all the pixels in
the input pixel’s neighborhood. In a binary image, if any of the pixels is set to the value 1,
the output pixel is set to 1.

Gandhinagar Institute of Technology CV


 Erosion operation: The value of the output pixel is the minimum value of all the pixels in
the input pixel’s neighborhood. In a binary image, if any of the pixels is set to 0, the output
pixel is set to 0.
 Opening and closing operations can be done by combination of erosion and dilation in
different sequence.
Transformations differ for all morphological operations.
 The Minimum Filter: The transformation replaces the central pixel with the darkest one in
the running window.
For example, if you have text that is lightly printed, the minimum filter makes letters
thicker.
 The Maximum Filter: The maximum and minimum filters are shift-invariant. Whereas the
minimum filter replaces the central pixel with the darkest one in the running window, the
maximum filter replaces it with the lightest one.
For example, if you have a text string drawn with a thick pen, you can make the sign skinnier.

Exercises:

1. Write programs for image morphological operations using Minimum, maximum and average
filter.

Review Questions:
1. Explain various noise model and how it can be defined?
2. Explain various spatial filter used in image restoration in detail.

Gandhinagar Institute of Technology CV


Image restoration methods using Laplacian filter and Median filter
Practical No.: Date:
Aim: Write a program to perform image restoration methods using Laplacian filter and
Median filter.

Theory:

Laplacian filters are derivative filters used to find areas of rapid change (edges) in images. Since
derivative filters are very sensitive to noise, it is common to smooth the image (e.g., using a
Gaussian filter) before applying the Laplacian. This two-step process is call the Laplacian of
Gaussian (LoG) operation.

There are different ways to find an approximate discrete convolution kernal that approximates the
effect of the Laplacian. A possible kernel is

This is called a negative Laplacian because the central peak is negative. It is just as appropriate to
reverse the signs of the elements, using -1s and a +4, to get a positive Laplacian. It doesn't matter.

To include a smoothing Gaussian filter, combine the Laplacian and Gaussian functions to obtain a
single equation:

A discrete kernel for the case of σ = 1.4 is given by

Gandhinagar Institute of Technology CV


The LoG operator takes the second derivative of the image. Where the image is basically uniform,
the LoG will give zero. Wherever a change occurs, the LoG will give a positive response on the
darker side and a negative response on the lighter side. At a sharp edge between two regions, the
response will be

 zero away from the edge


 positive just to one side
 negative just to the other side
 zero at some point in between on the edge itself

When using the filter given above, or any other similar filter, the output can contain values that
are quite large and may be negative, so it is important to use an image type that supports negatives
and a large range, and then scale the output. (ImageJ has a 32-bit floating point representation).
Alternatively, a scaling factor can be used on the filter to restrict the range of values.

The median filter is a nonlinear digital filtering technique, often used to remove noise from an
image or signal. Such noise reduction is a typical pre-processing step to improve the results of later
processing (for example, edge detection on an image). Median filtering is very widely used in
digital image processing because, under certain conditions, it preserves edges while removing
noise (but see discussion below), also having applications in signal processing.

Gandhinagar Institute of Technology CV


The main idea of the median filter is to run through the signal entry by entry, replacing each entry
with the median of neighboring entries. The pattern of neighbors is called the "window", which
slides, entry by entry, over the entire signal. For 1D signals, the most obvious window is just the
first few preceding and following entries, whereas for 2D (or higher-dimensional) signals such as
images, more complex window patterns are possible (such as "box" or "cross" patterns). Note that
if the window has an odd number of entries, then the median is simple to define: it is just the
middle value after all the entries in the window are sorted numerically. For an even number of
entries, there is more than one possible median, see median for more details.
Example
To demonstrate, using a window size of three with one entry immediately preceding and following
each entry, a median filter will be applied to the following simple 1D signal:

x = (2, 80, 6, 3).


So, the median filtered output signal y will be:
y1 = med(2, 2, 80) = 2,
y2 = med(2, 80, 6) = med(2, 6, 80) = 6,
y3 = med(80, 6, 3) = med(3, 6, 80) = 6,
y4 = med(6, 3, 3) = med(3, 3, 6) = 3,
i.e. y = (2, 6, 6, 3).

Exercises:

1. Write a program to perform image restoration methods using Laplacian filter and Median
filter.

Review Questions:
1. Explain Laplacian and Median filter in detail.

Gandhinagar Institute of Technology CV


[This page is intentionally left blank]

Gandhinagar Institute of Technology CV


Remove noise using any spatial filters
Practical No.: Date:
Aim: Write a program to remove noise using any spatial filters (Use 3x3 Mask for low pass
filter or high pass filter).

Theory:
Spatial Filtering is sometimes also known as neighborhood processing. Neighborhood processing
is an appropriate name because you define a center point and perform an operation (or apply a
filter) to only those pixels in predetermined neighborhood of that center point. The result of the
operation is one value, which becomes the value at the center point's location in the modified
image. Each point in the image is processed with its neighbors. The general idea is shown below
as a "sliding filter" that moves throughout the image to calculate the value at the center location.

In spatial filtering, we perform convolution of data with filter coefficients. In image processing,
we perform convolution of 3x3 filter coefficients with 2-D image data. In signal processing, we
perform convolution of 1-D data with set of filter coefficients.

Program for 1D convolution (Useful for 1-D Signal Processing):


clear;
clc;
x=input("Enter value of x: ")
y=input("Enter value of y: ")
n=length(x)

k=length(y)
for z=n+1:n+k-1
x(z)=0;

end
for u=k+1:n+k-1
y(u)=0;

end
for i=1:n+k-1

Gandhinagar Institute of Technology CV


s(i)=0
for j=1:i

s(i)=(x(j)*y(i-j+1))+s(i)
end
end
subplot(3,1,1)
plot2d3(x)

subplot(3,1,2)
plot2d3(y)
subplot(3,1,3)
plot2d3(s)
Take value of x: [ 1 2 3 4 5 6 7 8 9 0 10 11 12 13 14 15]
Y: [-1 1]
Observe result of convolution and write your comments:
Program for 2D convolution:
clear;
clc;

x=input("Enter value of x in matrix form: ")


y=input("Enter value of y in matrix form: ")
[xrows,xcols]=size(x); [yrows,ycols]=size(y); result=zeros(xrows+yrows,xcols+ycols)
for r = 1:xrows-1

for c = 1:xcols-1
sum=0;
for a=0:yrows
for b=0:ycols
sum=sum+x(r+a,c+b)*y(a+1,b+1);
end

Gandhinagar Institute of Technology CV


end
result(r,c)=sum;

end
end
Enter following 2D matrix for x:

10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10

Enter following 2D matrix for y:

1 1 1
0 0 0
1 1 1

Exercises:

1. Write a program to remove noise using any spatial filters (Use 3x3 Mask for low pass filter or
high pass filter).

Review Questions:
1. Explain sharpening filters in detail.
2. Write down the outputs after observation of above convolution methods.

Gandhinagar Institute of Technology CV

You might also like