0% found this document useful (0 votes)
59 views57 pages

Lab No. 1: Introduction To Matlab Lab Task 01: Multiply The Following Two Matrices. A (1 2 3 4) B (5 6)

This document contains solutions to various image processing tasks in MATLAB. It discusses: 1. Resizing, interpolating, and downsampling an image using nearest neighbor, bilinear, and bicubic interpolation methods. 2. Applying distance transforms to images using Euclidean, city-block, and chessboard distance measures. 3. Performing arithmetic operations like addition, subtraction, multiplication, and division on images and interpreting the results. 4. Detecting differences between images using subtraction and absolute difference and applying thresholding and division techniques. The document demonstrates various image processing functions in MATLAB like imresize, bwdist, imadd, imsubtract, imdivide, and graythresh on sample images

Uploaded by

Kiw Veeraphab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views57 pages

Lab No. 1: Introduction To Matlab Lab Task 01: Multiply The Following Two Matrices. A (1 2 3 4) B (5 6)

This document contains solutions to various image processing tasks in MATLAB. It discusses: 1. Resizing, interpolating, and downsampling an image using nearest neighbor, bilinear, and bicubic interpolation methods. 2. Applying distance transforms to images using Euclidean, city-block, and chessboard distance measures. 3. Performing arithmetic operations like addition, subtraction, multiplication, and division on images and interpreting the results. 4. Detecting differences between images using subtraction and absolute difference and applying thresholding and division techniques. The document demonstrates various image processing functions in MATLAB like imresize, bwdist, imadd, imsubtract, imdivide, and graythresh on sample images

Uploaded by

Kiw Veeraphab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Lab no.

1: Introduction To Matlab
Lab Task 01
Multiply the following two matrices.
a=[1 2;3 4]
b=[5 6].
Solution:
clear all
clc
a=[1 2;3 4];
b=[5 6];
p=a*b

Lab Task 02Solve the following


system of linear equations.
x1 + 2x2=1
2x1+3x2=1
You have to find the value of x1 and x2.
Solution:
A=[1 2; 2 3]
C=[1 ; 1]
B=inv(A)
X=B*C

Lab Task 03:


Run the following code and explain the
output.
x = 3;
while (x < 8)
disp('Am I done yet?')
x = x + 2.5;
end
Solution:
x = 3;
while (x< 8)
disp('Am I done yet?')
x = x + 2.5;
end

Lab Task 04:


Write a MATLAB script that convert the length given in feet and inches into
centimeters using the formula 1 inch=2.54 cm. Display the result on the screen.
Solution:
clear all;
clc;
f=input('Enter length in feet :');
f=['required result ; ',num2str(f*30.48)];
disp(f)
i=input('Enter length in inches :');
i=['required result ; ',num2str(i*2.54)];
disp(i)

Lab Task 05
Write a MATLAB script to input two integer values and find out whether the first or
the second number is greater.
Solution:
clear all;
clc;
a=input('Enter first number\n');
b=input('Enter second number\n');
if a>b
disp('First num is greater');
else
disp('Second num is greater');
end

Lab Task 06
Write a MATLAB script to calculate the sum of first 10 prime numbers.
Solution:
n=input('Enter the Number Till Where You Want to Find the Prime Number :')
total=0;
for k=1:n
if(isprime(k)==1)
total=total+k;
end end disp(total)
Lab no. 2: Image Processing Basics
Class Task 01:
Solution:
[X,map] = imread('trees.tif');
I=imread('cameraman.tif');
X_rgb = ind2rgb(X,map);
X_gray = ind2gray(X,map);
max(X_gray(:))
min(X_gray(:))
X_gray_dbl = im2double(X_gray);
imshow(I), impixelinfo
imshow(X,map), impixelinfo
Class Task 02:
Solution :
A = imread('pout.tif');
B = imread('cameraman.tif');
figure
subplot(1,2,1), imshow(A)
subplot(1,2,2), imshow(B)
figure
subplot(1,2,1), subimage(I), axis off
subplot(1,2,2), subimage(X,map), axis off
[I_ind,I_map] = gray2ind(I,256);
I_rgb = ind2rgb(I_ind,I_map);
figure
subplot(1,2,1), imshow(I_rgb)
subplot(1,2,2), imshow(X_rgb)

Lab Task 01:


Create a 2×2 array of type double
A = [1.5 -2; 0.5 0]
and use it to perform the following operations:
(a) Convert to uint8 using typecasting and
interpret the results.
(b) Convert to a normalized ([0, 255]) grayscale
image of data class uint8 using im2uint8 and
interpret the results.
(c) Convert to a normalized ([0.0, 1.0])
grayscale image of data class double using mat2gray and interpret the results.
(d) Convert the result from the previous step to a binary image using im2bw (with a
threshold level of 0.5) and interpret the results.
Solution:
a=[1.5 -2,0.5 0]; b=uint8(a); c=im2uint8(a); d=mat2gray(a) ;e=im2bw(d,0.5)

Lab Task 02
Take any five images from MATLAB and collect the following information about each of
them:
File name, File format (extension) ,Type (binary, grayscale, truecolor, or indexed color),
Size (bytes), Width (pixels) ,Height (pixels)Select five images available in MATLAB (they
may be the same as from the previous problem, or not, you choose). Open each of them
using imread, save it (using imwrite) to (at least three) different file formats, and compare
the resulting file size (in bytes) for each output format
Solution:
a=imread('coins.png'); b=imread('pout.tif');
c=imread('cameraman.tif');
d=imread('peppers.png');
e=imread('trees.tif');
imfinfo('coins.png')
imfinfo('pout.tif')
imfinfo('cameraman.tif')
imfinfo('peppers.png')
imfinfo('trees.tif')
imwrite(c,'D:\coins.png')
imwrite(c,'D:\coins.tif')
imwrite(c,'D:\coins.jpeg')

Questions:
what type of image is coins.png?
coins.png is a gray scale image
Why do we use the semicolon (;) operator
after the imread statement?
What happens if we omit it?
if semicolon is omit matrix whould not show. otherwise whole matrix of pic is shown.
How many dimensions does the variable X_rgb have and what are their
sizes?
having 258 rows and 350 columns.
What class type is X_gray?
unsigned int.
Why are we required to use the colon operator (:) when specifying the X_gray
variable? What happens if we omit it?
max=255, min=0, if we omit : it gives value of every pixel.
What is the range of values for the new variable X_gray_dbl?
if we convert it in double then range is 0 to 1.
What is the meaning of the values stored in variables r, c, and p?
c tells about column r about rows and p tells about rgb color;
What is the range of values for image A and image B?
max_camera=253 min_camera=7
What happened to the coins image just after the trees image was
displayed? Explain your answer.
Map function of tree also effect the coins img. if we use subimage command istead of
imshow then it does not effect the images
What do the variables I_ind and I_map contain?
We indexed the image.It tells that at certain location what is the vale of map.

Lab Manual No. 3


Class Task 01
Solution:
I=imread('cameraman.tif');
I_big1 = imresize(I,3);
figure, imshow(I), title('Original Image');
figure, imshow(I_big1), title('Enlarged
Image using bicubic interpolation');
I_big2 = imresize(I,3,'nearest');
I_big3 = imresize(I,3,'bilinear' );
figure, imshow(I_big2),title('Resized using
nearest-neighbor interpolation');
figure, imshow(I_big3), title('Resized using
bilinear interpolation');
I_rows = size(I,1);
I_cols = size(I,2);
I_sm1 = I(1:2:I_rows, 1:2:I_cols);
figure, imshow(I_sm1);
I_sm2 = imresize(I,0.5,'nearest');
I_sm3 = imresize(I,0.5,'bilinear');
I_sm4 = imresize(I,0.5,'bicubic');
figure,
subplot(1,3,1),imshow(I_sm2),title('Neares
t-neighbor Interpolation');
subplot(1,3,2), imshow(I_sm3), title('Bilinear Interpolation');
subplot(1,3,3), imshow(I_sm4), title('Bicubic Interpolation');

Lab Task 01
Write a MATLAB code to interpolate an image using Nearest Neighbor Interpolation
Algorithm.

Solution:
inputImage=I;
scale = [3 3];
oldSize = size(inputImage); %# Get the size of
your image
newSize = max(floor(scale.*oldSize(1:2)),1); %# Compute
the new image size
rowIndex = min(round(((1:newSize(1))-
1)./scale(1)+1),oldSize(1));
colIndex = min(round(((1:newSize(2))-
1)./scale(2)+1),oldSize(2));
outputImage = inputImage(rowIndex,colIndex,:)
figure, imshow(outputImage);

Lab Task 02
Consider the two image subsets, S1 and S2, shown in the
following figure. For V={1}, determine whether these two subsets are (a) 4-adjacent, (b) 8-
adjacent

If the set V= {1, 2} then check whether the following is 4 adjacent or 8 adjacent.
Solution:

Lab Task 03:


Read at-least 3 built-in images of MATLAB and apply the distance transform function on
the images using Euclidean, city-block and chess board distance measures. Comment
on
the output.

Solution:
bw = zeros(200,200); bw(50,50) = 1; bw(50,150)
= 1;
bw(150,100) = 1;
D1 = bwdist(bw,'euclidean');
D2 = bwdist(bw,'cityblock');
D3 = bwdist(bw,'chessboard');
D4 = bwdist(bw,'quasi-euclidean');
figure
subplot(2,2,1), subimage(mat2gray(D1)),
title('Euclidean')
hold on, imcontour(D1)
subplot(2,2,2), subimage(mat2gray(D2)),
title('City block')
hold on, imcontour(D2)
subplot(2,2,3), subimage(mat2gray(D3)),
title('Chessboard')
hold on, imcontour(D3)
subplot(2,2,4), subimage(mat2gray(D4)),
title('Quasi-Euclidean') Figure 1 LT 3
hold on, imcontour(D4)
Lab Manual No 04: Arithmetic and Logical Operation on Images
Class Task 01 (Addition)
Solution:
X = uint8([200 100 100; 0 10 50; 50 250 120]);
Y = uint8([100 220 230; 45 95 120; 205 100 0]);
W = uint16(X) + uint16(Y)
fmax = max(W(:));
fmin = min(W(:));
Za = uint8(255.0*double((W-fmin))/double((fmax-fmin)))
Zb = imadd(X,Y)
Class Task 02 (Subtraction)
Solution:
X = uint8([200 100 100; 0 10 50; 50 250 120])
Y = uint8([100 220 230; 45 95 120; 205 100 0])
Za = imsubtract(X,Y)
Zb = imsubtract(Y,X)
Zc = imabsdiff(Y,X)
Class Task 03 (Mul and Div)
Solution:
X = uint8([200 100 100; 0 10 50; 50 250 120]);
Y = uint8([100 220 230; 45 95 120; 205 100 0]);
Z = uint8([200 160 130; 145 195 120; 105 240 150]);
Sa = imdivide(imadd(X,imadd(Y,Z)),3)
a = uint16(X) + uint16(Y)
b=a+uint16(Z)
Sb = uint8(b/3)
Sc=imlincomb(1/3,X,1/3,Y,1/3,Z,'uint8')
Class Task 04
Solution:
I = imread('cameraman.tif');
J = imread('cameraman2.tif');
figure
subplot(1,2,1), imshow(I), title('Original Image');
subplot(1,2,2), imshow(J), title('Altered Image');
diffim = imsubtract(I,J);
figure
subplot(2,2,1), imshow(diffim), title('Subtracted Image');
diffim2 = imabsdiff(I,J);
subplot(2,2,2), imshow(diffim2), title('Abs Diff Image');
subplot(2,2,3), imshow(diffim,[]), title('Subtracted Image Scaled');
subplot(2,2,4), imshow(diffim2,[]), title('Abs Diff Image Scaled');
Class Task 05
Solution:
I = imread('moon.tif');
I2 = imadd(I,50);
I3 = immultiply(I,1.2);
figure
subplot(1,3,1), imshow(I), title('Original Image');
subplot(1,3,2), imshow(I2), title('Normal Brightening');
subplot(1,3,3), imshow(I3), title('Dynamic Scaling');

Class Taask 06
Solution:
I = im2double(imread('earth1.tif'));
J = im2double(imread('earth2.tif'));
K = immultiply(I,J);
figure
subplot(1,3,1), imshow(I), title('Planet Image');
subplot(1,3,2), imshow(J), title('Gradient');
subplot(1,3,3), imshow(K,[]), title('3D Planet');

Class Task 07
Solution:
I = imread('moon.tif');
I2 = imdivide(I,2);
figure
subplot(1,3,1), imshow(I), title('Original Image');
subplot(1,3,2), imshow(I2), title('Darker Image w/ Division')
I3 = immultiply(I,0.5);
subplot(1,3,3), imshow(I3), title('Darker Image w/ Multiplication');

Class Task 08
Solution:
notext = imread('gradient.tif');
text = imread('gradient_with_text.tif');
figure, imshow(text), title('Original Image');
level = graythresh(text);
BW = im2bw(text,level);
figure, imshow(BW)
fixed = imdivide(text,notext);
figure
subplot(1,3,1), imshow(text), title('Original Image');
subplot(1,3,2), imshow(notext), title('Background Only');
subplot(1,3,3), imshow(fixed,[]), title('Divided Image')
Questions:
Q1) What would be the result of adding a positive constant (scalar) to a
monochrome image?
By Adding a positive constant to monochrome image, image will be brighter.
Q2) What would be the result of subtracting a positive constant (scalar) from a
monochrome image?
By subtracting a positive constant from a monochrome image it will get dark. Brightness
of the image will be reduced.
Q3 What would be the result of multiplying a monochrome image by a positive
constant greater than 1.0?
By multiplying a monochrome image by a positive constant greater than 1 brightness of
the image increases.
Q4 What would be the result of multiplying a monochrome image by a positive constant
less than 1.0?

By multiplying a monochrome image by a positive constant less than 1 brightness of the


image decreases.
Q5 What happens when you add a uint8 [0, 255] monochrome image to itself?
By adding two monochrome images the brighter part of image will get brighter.
Q6.What happens when you multiply a uint8 [0, 255]
monochrome image by itself?
If value of multiplying factor is greater than 1 the image will
be brighter.so by multiplying the image with value close or
equal to 1 image is brightened to this extend that it distorts.

Q7. What happens when you multiply a double [0, 1.0] monochrome image by itself?
Since Values exist between 0 and 1 so when we multiply a monochrome image by itself if
multiplier is 0 multiplicand will be either 0 or 1 we wil get 0.so dark image is obtained on
output.
Q8.What happens when you divide a double [0, 1.0] monochrome image by itself?
As we divide the image by itself all pixel values will get cancelled so image will be
fully brighter because it get one.

Figure 2 Question no.7


Lab Manual No 05: Geometric Operation on Images
Class Task 01
Solution:
I = imread('cameraman.tif');imtool(I)
I2 = imread('cropped_building.png');imshow(I2)
x1 = 186; x2 = 211; y1 = 105; y2 = 159;
xmin = x1;ymin = y1;
width = x2-x1;height = y2-y1;
I3 = imcrop(I, [xmin ymin width height]);imshow(I3)
I_big1 = imresize(I,3);
figure,
imshow(I), title('Original Image');
figure,
imshow(I_big1),title('Enlarged Image w/ bicubic interpolation');
imtool(I_big1)
I_big2 = imresize(I,3,'nearest');I_big3 = imresize(I,3,'bilinear');
figure
imshow(I_big2), title('Resized w/ nearest-neighbor interpolation');
figure
imshow(I_big3),title('Resized w/ bilinear interpolation');
I_rows = size(I,1);
I_cols = size(I,2);
I_sm1 = I(1:2:I_rows, 1:2:I_cols);figure
imshow(I_sm1);
I_sm2 = imresize(I,0.5,'nearest') ;
I_sm3 = imresize(I,0.5,'bilinear');
I_sm4 = imresize(I,0.5,'bicubic');
figure
subplot(1,3,1),imshow(I_sm2),title('Nearest-neighbor Interpolation');
subplot(1,3,2), imshow(I_sm3), title('Bilinear Interpolation');
subplot(1,3,3), imshow(I_sm4), title(' Bicubic Interpolation');
Class Task 02
Solution:
I = imread('cameraman.tif');J = flipud(I); K = fliplr(I);
subplot(1,3,1), imshow(I), title('Original image')
subplot(1,3,2), imshow(J), title('Flipped upside-down')
subplot(1,3,3), imshow(K), title('Flipped left-right')
I_rot = imrotate(I,35);
imshow(I_rot);I_rot2 = imrotate(I,35,'bilinear');
figure, imshow(I_rot2)

Class Task 03
Solution:
filename = 'cameraman.tif'
I = imread(filename);
% Rotation
Ta = maketform('affine', [cosd(30) -sind(30) 0; sind(30) cosd(30) 0; 0 0 1]);
Ia = imtransform(I,Ta);
%Scaling
Tb = maketform('affine',[3.5 0 0; 0 3.5 0; 0 0 1]);
Ib = imtransform(I,Tb);
% Translation
xform = [1 0 25; 0 1 15; 0 0 1];
Tc = maketform('affine',xform);
Ic = imwarp(I,Tc, 'XData',[1 (size(I,2)+xform(3,1))],'YData', [1 (size(I,1)+xform(3,2))],'FillValues', 128 );
% Shearing
Td = maketform('affine2d',[1 3 0; 2 1 0; 0 0 1]);Id = imwarp(I,Td);

Class Task 04
Solution:
I1 = imread('cameraman.tif');
sx = 2;sy = 2;
T = maketform('affine',[sx 0 0; 0 sy 0; 0 0 1]);
I2 = imtransform(I1,T);
imshow(I2), title('Using affine transformation')
I3 = imresize(I1, 2);figure
imshow(I3), title('Using image resizing')

Class Task 04
Solution:
I1 = imread('cameraman.tif');theta = 35*pi/180
xform = [cos(theta) sin(theta) 0; -sin(theta) cos(theta) 0; 0 0 1]
T = maketform('affine',xform);I4 = imtransform(I1, T);
imshow(I4), title('Using affine transformation')
I5 = imrotate(I1, 35);figure
imshow(I5), title('Using image rotating')
Class Task 05
Solution:
I1 = imread('cameraman.tif');
delta_x = 50;
delta_y = 100;
xform = [1 0 delta_x; 0 1 delta_y; 0 0 1]
tform_translate = maketform('affine',xform);
I6 = imtransform(I1, tform_translate, 'XData', [1 (size(I1,2)+xform(3,1) )], 'YData', [1
(size(I1,1)+xform(3,2))], 'FillValues', 128 );
figure, imshow(I6)

Lab Task 01
Use imrotate to rotate an image by an arbitrary angle (not
multiple of 90◦) using the three interpolation methods discussed
in the tutorial. Compare the visual quality of the results obtained
with each method and their computational cost (e.g., using
MATLAB functions tic and toc).

Solution:
tic
I=imread('cameraman.tif');
bilinear=toc
bi=imrotate(I,60,'bilinear');
subplot(3,1,1),imshow(bi),title('Rotate by bilinear');
nearest=toc
near=imrotate(I,60,'nearest');
subplot(3,1,2),imshow(near),title('Rotate by nearest');
bicubic=toc
bicubic=imrotate(I,60,'bicubic');
subplot(3,1,3),imshow(bicubic),title('Rotate by bicubic');

Lab Task 02
Consider the MATLAB snippet below (assume X is a gray-level image) and answer this
question: Will X and Z be identical? Explain.
Y = imresize(X,0.5,’nearest’);
Z = imresize(Y,2.0,’nearest’);

Solution:
X=imread('cameraman.tif');
Y=imresize(X,0.5,'nearest');
Z=imresize(Y,2,'nearest');
subplot(1,2,1),imshow(X),title('Image X')
subplot(1,2,2),imshow(Z),title('Image Z')
% size will remain same but quality will be low

Lab Task 03
Create an affine transformation that maps the triangle with
vertices (0,0), (6,3), (-2 5) to the triangle with vertices(-1, -1) (0, -10),
(4,4).

Solution:
clear all;
a=[0 6 -2]';
b=[0 3 5]';
c=[-1 0 4]';
d=[ 1 -10 4]';
tform=maketform('affine',[a b],[c d]);
[am, bm] = tforminv(tform, c, d)

Lab Task 04
Read an image ‘statue.png’ and perform the following
operation.
1. Rotation
2. Scaling
3. Shear Horizontal
4. Shear Vertical
The required matrices are given below.

Solution:
%rotate
I=imread('statue.png');
ro=maketform('affine',[cos(45) sin(45) 0;-sin(45)
cos(45) 0;0 0 1]);
rotate=imtransform(I,ro);figure

subplot(1,2,1),imshow(I);subplot(1,2,2),imshow(rotate);
%Scaling
sa=maketform('affine',[.2 0 0;0 .2 0;0 0 1]);scale=imtransform(I,sa);
figure
% subplot(1,2,1),imshow(I);
imshow(scale);
%Shear Horizontal
sh=maketform('affine',[1 0 0;2 1 0;0 0 1]);shear=imtransform(I,sh);
figure
% subplot(1,2,1),imshow(I);
imshow(shear);
%Shear Vertical
shv=maketform('affine',[1 2 0;0 1 0;0 0 1]);
shear_v=imtransform(I,shv);
figure
% subplot(1,2,1),imshow(I);
imshow(shear_v);

Lab Task 05
Read two images provided to you named ‘Orignal_image.png’ and ‘Distorted_image.png’ and
register the image ‘Distorted_image.png’ with reference to ‘Original_image.png’. Show the three
images at the output.

Solution:
clear all;
base=imread('Original_image.png');
unregistered= imread('Distorted_image.png');
cpselect(unregistered,base);
% ist comment the below code and run then comment the above code
[input_points,base_points]=cpstruct2pairs(cpstruct);
mytform1 = cp2tform(input_points, base_points, 'nonreflective similarity');
info = imfinfo('Original_image.png');
registered = imtransform(unregistered,mytform1,'XData',[1 info.Width], 'YData',[1 info.Height]); figure,
imshow(registered);
hold on
figure
imshow(base),title('Base Image'); figure
imshow(unregistered),title('Unregistered Image');
figure
h = imshow(base),title('Registered Image');
% set(h, 'AlphaData', 0.6)
Lab Manual No 06: Gray Level Transformation on Images
Class Task 01
Solution:
LUT = uint8(zeros([1 256]));
LUT(1:65) = 2*(0:64);
LUT(66:129) = 128;
LUT(130:256) = (130:256) -1;
A = uint8([20 40 0; 178 198 64; 77 128 1])
B = intlut(A, LUT)

Class Task 02
Solution:
I = imread('klcc_a.png');
O = intlut(I,LUT);
figure, subplot(1,2,1), imshow(I),
subplot(1,2,2), imshow(O

Class Task 03:


Solution:
I = imread('klcc_a.png');
LUT = double(zeros([1 256]));
LUT(1:256)=5*sqrt(0:255);
LUT_int8 = uint8(LUT);
tic
O = intlut(I, LUT_int8);
toc
figure, subplot(1,2,1), imshow(I),
subplot(1,2,2), imshow(O)

Class Task 04
Solution:
I = imread('moon.tif');
x = uint8(0:255);
plot(x);
xlim([0 255]);
ylim([0 255]);
I_adj = x(I + 1);
figure,
subplot(1,2,1), imshow(I), title('Original Image');
subplot(1,2,2), imshow(I_adj), title('Adjusted Image');

Class Task 05
Solution:
y = uint8(255: -1:0);
I_neg = y(I + 1);
figure, subplot(1,3,1), plot(y),
title('Transformation Function'),
xlim([0 255]), ylim([0 255]);
subplot(1,3,2), imshow(I), title('Original Image');
subplot(1,3,3), imshow(I_neg), title('Negative Image');
I_cmp = imcomplement(I);
I_dif = imabsdiff(I_cmp,I_neg);
figure, imshow(I_cmp)
figure, imshow(I_dif,[])

Class Task 06
Solution:
I = imread('radio.tif');
I_log = uint8(y(I + 1));
subplot(2,2,2), imshow(I), title('Original Image');
subplot(2,2,3), imshow(I_log), title('Adjusted Image');
I_br = imadd(I,100);
subplot(2,2,4), imshow(I_br), title('Original Image
Scaled');
z = exp(x/c) - 1;
I_invlog = uint8(z(I_log + 1));
figure,
subplot(2,1,1), plot(z), title('Inverse-log Mapping
Function');
subplot(2,1,2), imshow(I_invlog), title('Adjusted
Image');
x = 0:255; n = 2;
c = 255 / (255^ n);
root = nthroot((x/c), n);
figure,subplot(2,2,1), plot(root),
title('2nd-root transformation'), axis tight, axis square

Class Task 07
Solution:
I = imread('drill.tif');
I_root = uint8(root(I + 1));
subplot(2,2,2), imshow(I), title('Original Image');
subplot(2,2,[3 4]), imshow(I_root), title('Nth Root
Image');
power=c*(x.^n);
figure, subplot(1,2,1), plot(power),
title('2nd-power transformation'); axis tight, axis
square
I_power = uint8(power(I_root + 1));
subplot(1,2,2), imshow(I_power), title('Adjusted
Image');

Class Task 08 Figure 3 CT 8

Solution:
I = imread('micro.tif');
figure, subplot(1,3,1), imshow(I), title('Original Image');
I2 = uint8(y(I + 1));
subplot(1,3,3), imshow(I2), title('Adjusted Image');
z(1:175) = 50;
z(176:200) = 250;
z(201:256) = 50;
I3 = uint8(z(I + 1));
figure, subplot(1,2,1), plot(z), xlim([0 255]), ylim([0 255]),
axis square
subplot(1,2,2), imshow(I3)

Lab Task 01
Write a MATLAB function to perform a piecewise linear
brightness and contrast adjustment on monochrome
images using the generic method described earlier by
using equation given below. It should take as arguments a
monochrome image, the c coefficient (slope), and the b
coefficient (offset).

Solution:
function [ ]=l61(I,c,b)
x = 0:255;
y=c*x+b;
figure, subplot(2,2,1), plot(y),
title('Log Mapping Function'), axis tight, axis square
I_log = uint8(y(I + 1));
subplot(2,2,2), imshow(I), title('Original Image');
subplot(2,2,3), imshow(I_log), title('Adjusted Image');
I_br = imadd(I,100);
subplot(2,2,4), imshow(I_br), title('Original Image Scaled'); Figure 4 LT 1
Lab Task 02
Write a MATLAB function to perform a simple version of
image solarization technique(also known as Sabatier
effect),a point transformation that processes an image by
leaving all pixels brighter than a certain value (T)
untouched, while extracting the negative of all pixels
darker than T.

Solution:
I = imread('cameraman.tif');
figure, subplot(1,3,1), imshow(I), title('Original Image');
y(1:128) = 255:-1:128;
y(129:256) = 128:255;
subplot(1,3,2), plot(y), axis tight, axis square
I2 = uint8(y(I + 1));
subplot(1,3,3), imshow(I2), title('Adjusted Image');

Lab Task 03
The sigmoid function used to generate a point transformation can be described by the equation

where r is the original pixel value, s is the resulting pixel value, m is a user-specified threshold,
and S is a parameter that controls the slope of the curve.
Apply the transformation function developed for above
equation to different images and experiment with different
values of m and S. Report a summary of
your findings.

Solution:
function [ ]=l63(I,m,S)
x = 0:255;
y=(1./(1+(m./x).^S));
figure, subplot(2,2,1), plot(y),
title('Log Mapping Function'), axis tight, axis square
I_log = uint8(y(I + 1));
subplot(2,2,2), imshow(I), title('Original Image');
subplot(2,2,3), imshow(I_log), title('Adjusted Image');
I_br = imadd(I,100);
Lab Manual No 07: Histogram Processing on Images
Lab Task 01
Write a MATLAB function that takes an image as input to calculate and plot the histogram of the
image without using built-in function. Plot the histogram using imhist function. Compare the
result of your code with the built-in function result.

Solution:
function [b]= histogram(a)
a=imread(a);
[r,c]=size(a);
b=0;count=0;temp=0;
for l=1:1:256
for i=1:1:r
for j=1:1:c
if(a(i,j)==count)
temp=temp+1;
end
end
end
b(l)=temp;count=count+1;
temp=0;
end
b;stem(b)
ylim([0 1000]) xlim([0 256])
figure
imhist(a)
end

Lab Task 02
Write a MATLAB function that takes an image as input and perform histogram equalization on
the image without using built-in function. Plot the equalized histogram using histeq function.
Compare the result of your code with the built-in function result.

Solution:
a=task1('cameraman.tif')
cdf=0;h=0;temp=0;
max_a= 255;min_a= 1;for i=1:1:256
temp=temp+a(i);cdf(i)=temp;
end max_cdf= max(cdf);min_cdf= min(cdf);
for i=1:1:256
temp=round(((cdf(i)-min_cdf)/65536)*255)
h(i)=temp;
end h
figure
stem(h)end
Lab Manual No 08: Image Enhancement in Spatial Domain-
Filtering
Class Task 01
Solution:
x = [140 108 94;89 99 125;121 134 221]
y = [-1 0 1; -2 0 2; -1 0 1]
z = imfilter(x,y,'corr')
g = imfilter(x,y,'full','conv')
Class Task 02
Solution
I = imread('cameraman.tif');
figure, subplot(1,2,1), imshow(I), title('Original Image');
fn = fspecial('average');
I_new = imfilter(I,fn);
subplot(1,2,2), imshow(I_new), title('Filtered Image');

Class Task 03
Solution
fn2 = [1 2 1; 2 4 2; 1 2 1]
fn2 = fn2 * (1/16)
I_new2 = imfilter(I,fn2);
figure,
subplot(1,2,1), imshow(I_new), title('Uniform Average');
subplot(1,2,2), imshow(I_new2), title('Non-uniform
Average');
fn_gau = fspecial('gaussian',9,1.5);
figure, bar3(fn_gau,'b'), title('Gaussian filter as a 3D graph')
I_new3 = imfilter(I,fn_gau);
subplot(1,3,1), imshow(I), title('Original Image');
subplot(1,3,2), imshow(I_new), title('Average Filter');
subplot(1,3,3), imshow(I_new3), title('Gaussian Filter')

Class Task 04
Solution
I = imread('moon.tif');
Id = im2double(I);
figure, subplot(2,2,1), imshow(Id), title('Original Image');
f = fspecial('laplacian',0);
I_filt = imfilter(Id,f);
subplot(2,2,2), imshow(I_filt), title('Laplacian of Original');
subplot(2,2,3), imshow(I_filt,[]),
title('Scaled Laplacian');
I_sharp = imsubtract(Id,I_filt);
subplot(2,2,4), imshow(I_sharp), title('Sharpened Image');
Class Task 05
Solution
f2 = [0 -1 0; -1 5 -1; 0 -1 0]
I_sharp2 = imfilter(Id,f2);
figure,
subplot(1,2,1), imshow(Id), title('Original Image');
subplot(1,2,2), imshow(I_sharp2), title('Composite
Laplacian');

Class Task 06
Solution
I = imread('moon.tif');
f_blur = fspecial('average',5);
I_blur = imfilter(I,f_blur); Figure 5 CT 5
figure,
subplot(1,3,1), imshow(I), title('Original Image');
subplot(1,3,2), imshow(I_blur), title('Blurred
Image');I_blur_adj = imadjust(I_blur,stretchlim(I_blur),[0 0.4]);
I_sharp = imsubtract(I,I_blur_adj);
I_sharp_adj = imadjust(I_sharp);
subplot(1,3,3), imshow(I_sharp_adj), title('Sharp Image');
I_sharpening = imsubtract(I,I_blur);
I_sharp2 = imadd(I,I_sharpening);
figure,
subplot(1,2,1), imshow(I), title('Original Image');
subplot(1,2,2), imshow(I_sharp2), title('Sharp Image');
f_unsharp = fspecial('unsharp');
I_sharp3 = imfilter(I,f_unsharp);
figure,
subplot(1,2,1), imshow(I), title('Original Image');
subplot(1,2,2), imshow(I_sharp3), title('Sharp Image');

Class Task 07
Solution
f_hb2 = [0 -1 0; -1 7 -1; 0 -1 0];
I_sharp5 = imfilter(I,f_hb2);
I_mult = immultiply(I,3);
figure,
subplot(1,3,1), imshow(I), title('Original Image');
subplot(1,3,2), imshow(I_sharp5), title('High Boost, A =3');
subplot(1,3,3), imshow(I_mult), title('Multiplied by 3');

Questions
Question 1:-
What is the relationship between the size of the
output matrix, the size of the original matrix, and the length of the filter?
The output array is the full filtered result, and so is larger than the input array.

Question 2:-How does changing the third parameter from ’full’ to ’same’ affect the
output?
The output array is the same size as the input array.
Question 3:-In the resulting matrix (z), we are interested only in the center value. How
does this value compare with our calculation illustrated above?
It is the sum of products of all elements with the filter
(140)(−1)+(108)(0)+(94)(1)+(89)(−2)+(99)(0)+(125)(2)+(121)(−1)
+(134)(0)+(221)(1) = 126

Question 4:-What are the other values in the resulting matrix?


They are calculated by using the same method that is applied on the origin using sum of
products.

Question 5:-Note in the last step we did not specify if the output should be ’full’ or ’same’.
What is the default for this setting if it is not specified?
Same

Question 6:- How does the center value of the resulting matrix compare with our
calculation above?
It is the negative of the above value.

Question 1:- Explain what the value of the variable fn represents.


fn is an averaging filter of size 3x3.

Question 2:- What other commonly used masks is the fspecial function capable of
generating?
Help fspecial

Question 3:- What was the effect of the averaging filter?


Blurred image

Question 1:- When specifying the Laplacian filter in the fspecial function,
what is the second parameter (in the case above, 0) used for?
H = fspecial('laplacian',ALPHA) returns a 3-by-3 filter approximating the shape of the two-
dimensional Laplacian operator. The parameter ALPHA controls the shape of the
Laplacian and must be in the range 0.0 to 1.0.The default ALPHA is 0.2.

Question 2:-What is the minimum value of the filtered image?


-0.6588
Question 3:-Verify that a uint8 filtered image would not reflect negative
numbers. You can use the image I that was previously loaded.
Min(I1_new(:))=0
Imshow: If you use an empty matrix ([]) for
[LOW HIGH], imshow uses [min(I(:)) max(I(:))]; that is, the minimum value in I is displayed
as black, and the maximum value is displayed as white.
Question 4:-You may have noticed that we created the mask without using the fspecial
function. Is the fspecial function capable of
generating the simplified Laplacian mask?
I don’t think so
Question 6:-What does the second parameter of the fspecial function call
mean?
H = fspecial('average',HSIZE) returns an averaging filter H of size HSIZE. HSIZE can be
a vector specifying the number of rows and columns in H or a scalar, in which case H is
a square matrix. The default HSIZE is [3 3].

Question 8:-How can we adjust the amount of sharpening when using this
implementation?
By using a different filter for blurring
Lab # 9: Image Enhancement in Frequency Domain- Filtering
Class Tasks
Task no. 1
To generate the FT of an image (a 2D function), To view the spectrum of the image,
Shift the FT array of results. Display the FT results, remapped to a grayscale range.
Display the log of the shifted FT image.
Code
I = imread(’cameraman.tif’);Id = im2double(I); ft = fft2(Id); ft_shift = fftshift(ft);
figure, subplot(1,2,1),imshow(abs(ft_shift),[]),title(’Direct remap’);
subplot(1,2,2), imshow(log(1 + abs(ft_shift)), []), title(’Log remap’);
Result

Questions
What are the minimum and maximum values of the resulting discrete Fourier
transform coefficients for the cameraman image?
min(min(ft)) ans =0.0154 - 0.0445i max(max(ft)) ans =3.0513e+04
Why are we required to use the abs function when displaying the ft_shift image?
Because ft_shift is a 256x256 complex double variable ,we need to convert it into
256x256 double to show as a plot so that is why we use abs function while displaying it.
How did we remap the image to a different (narrower) grayscale range?
We remapped the adjusted values to the grayscale range by specifying ’[]’ in the second
parameter.
subplot(1,2,2), imshow(log(1 + abs(ft_shift)), []), title(’Log remap’);
Task no. 2
Low-Pass Filters in frequency Domain
Code
I = imread(’eight.tif’); Id = im2double(I); I_dft = fft2(Id);figure, imshow(Id), title(’Original
Image’); figure, imshow(log(1 + abs(fftshift(I_dft))),[]),title(’FT of original image’);
Result

Task no. 3
Ideal Low Pass Filters
Code
I = imread(’eight.tif’); Id = im2double(I); I_dft = fft2(Id);H = zeros(M, N); radius = 35;
ind = dist <= radius; H(ind) = 1;
Hd = double(H);figure, imshow(fftshift(H)), title(’Ideal low-pass filter’); DFT_filt = Hd .*
I_dft;
I2 = real(ifft2(DFT_filt)); figure,imshow(log(1+abs(fftshift(DFT_filt))),[]),title(’Filtered FT’);
figure, imshow(I2), title(’Filtered Image’);
Result

Questions
Verify that the size of the distance matrix is in fact equal to the size of the image.

What happens if we display the distance matrix without shifting?


We get an error because X,Y, Z and C can’t be complex.

Explain how the previous code sets all values within a given radius to 1.
Ind gets all the values from dist <= radius in the form of 1s and 0s and then H(ind) is set =1;

How does the filtered image compare to the original image? Can you see any
noticeable artifacts?
Yes noticeable artifacts can be seen and the image is more blur as compared to the
original
Task no. 4
Gaussian LPF
Code
sigma = 30;H_gau = exp(-(dist .ˆ 2) / (2 * (sigma ˆ 2)));
figure, imshow(Id), title(’Original Image’);figure, imshow(log(1 + abs(fftshift(I_dft))),
[]),title(’DFT of original image’); figure, mesh(fftshift(dist)), title(’Distance Matrix’);
figure, imshow(fftshift(H_gau)), title(’Gaussian low-pass’);DFT_filt_gau = H_gau .* I_dft;
I3 = real(ifft2(DFT_filt_gau)); figure, imshow(log(1 + abs(fftshift(DFT_filt_gau))),[]),
title(’Filtered FT’); figure, imshow(I3), title(’Filtered Image’);
Result

Questions
Compare the output images between the ideal filter and the Gaussian filter. What
are their similarities? What are their differences?
Filtering with a Gaussian tends to look "natural" compared to ideal low pass filters,
which can generate ringing artifacts.
Task no. 5
Butterworth LPF
Code
D0 = 35; n = 3; H_but=1./(1+(dist./D0).ˆ(2*n));
figure, imshow(Id), title(’Original Image’);
figure, imshow(log(1 + abs(fftshift(I_dft))),[]), title(’FT of original image’); figure,
mesh(fftshift(dist)), title(’Distance Matrix’);
figure, imshow(fftshift(H_but)), title(’Butterworth low-pass’);
DFT_filt_but = H_but .* I_dft; I4 = real(ifft2(DFT_filt_but));
figure, imshow(log(1 + abs(fftshift(DFT_filt_but))),[]), title(’Filtered FT’); figure, imshow(I4),
title(’Filtered Image’);

Questions
Compare the ideal-filtered FT image and the Butterworth-filtered FT image.
Butterworth-filtered image has less ringing than the ideal-filtered image.
Implement the Butterworth filter again, but this time using a much higher order,
such as 20. How does this output compare to the ideal filter?
Image got more blur and the ringing artifacts became more visible.
Task no. 6
Ideal High Pass Filter
Code
H = ones(M, N);radius = 30; ind = dist <= radius;
H(ind) = 0;a = 1;b = 1; Hd = double(a + (b .* H));
DFT_filt = Hd .* I_dft; I2 = real(ifft2(DFT_filt));
figure,imshow(log(1+abs(fftshift(DFT_filt))),[]),title(’Filtered FT’); figure, imshow(I2),
title(’Filtered Image’);
Result

Questions
Explain how the previous code generates an ideal high-pass filter.
Just like ideal low pass filter ind takes values less than equal to the radius and all the
values of H(ind) are set 0 while others remain 1
When displaying the filter as an image, why must we scale the output for display
purposes?
We need to scale the image to get the whole image otherwise we just get a white
screen with few dots in it.
How does the new image compare to the original image?
It is a bit sharper but there are ringing artifacts present in it.
How does the output compare between using a cutoff value of 30 and 10?
At cutoff value 10 the sharpness is increased considerably as compared to cutoff value
30.The ringing effect is more visible at cutoff value 10.
What happens to the filtered image as we increase the cutoff value (beyond 30)
with respect to the original image?
The sharpness starts to decrease, it looks more like the original image.
Task no. 7
Gaussian HPF
Code
sigma = 30; H_gau=1-exp(-(dist.ˆ2)/(2*(sigmaˆ2))); H_gau_hfe=a+(b.*H_gau);
figure,mesh(fftshift(H_gau_hfe)), zlim([0 2]), title(’Gaussian
high-pass filter’);DFT_filt_gau = H_gau_hfe .* I_dft; I3 = real(ifft2(DFT_filt_gau));
figure, imshow(I), title(’Original Image’); figure, imshow(log(1 + abs(fftshift(I_dft))),[]), title(’FT of
original image’); figure, imshow(log(1 + abs(fftshift(DFT_filt_gau))),[]),
title(’Filtered FT’); figure, imshow(I3), title(’Filtered Image’);

Result

How does the Gaussian-filtered image compare to the ideal-filtered image?


It sharpens the image but doesn’t produce ringing effect.
In general, how does the filter change when the standard deviation of the filter is
increased or decreased?
If we increase sigma the sharpness decreases and when we decrease the value of
sigma the sharpness increases.
Task no. 8
Butterworth HPF
Code
cutoff = 30; order = 2;
H_but=1./(1+(cutoff./dist).ˆ(2*order)); H_but_hfe=a+(b.*H_but);
figure,mesh(fftshift(H_but_hfe)),zlim([0 2]),title(’Butterworth high-pass filter’);
DFT_filt_but = H_but_hfe .* I_dft;
I4 = real(ifft2(DFT_filt_but)); figure, imshow(I), title(’Original Image’);
figure, imshow(log(1 + abs(fftshift(I_dft))),[]), title(’FT of original image’); figure,
imshow(log(1 + abs(fftshift(DFT_filt_but))),[]), title(’Filtered FT’); figure, imshow(I4),
title(’Filtered Image’);
Result
Lab No. 10: Edge Detection
Task no. 1
Prewitt Operator

Code
I = imread(’cameraman.tif’);
figure, subplot(2,2,1), imshow(I), title(’Original Image’);
[I_prw1,t1] = edge(I,’prewitt’);
subplot(2,2,2), imshow(I_prw1), title(’Prewitt, default thresh’);

Result

Questions
What does the t1 variable represent?
Represents the threshold value
How did the Prewitt edge detector perform in the presence of noise (compared to no
noise)?
In the presence of noise it was very sensitive to the noise it detected edges where noise
was present.
Did MATLAB use a different threshold value for the noisy image?
Yes t1 was 0.1399 while t2 was 0.1756.Threshold used for noisy image was greater than t1.

Task no. 2
Edge Detection Using the Sobel Operator

Code
[I_sob1,t1] = edge(I,’sobel’);
figure, subplot(2,2,1), imshow(I), title(’Original Image’);
subplot(2,2,2), imshow(I_sob1), title(’Sobel, default thresh’); [I_sob2,t2] =
edge(I_noise,’sobel’);
subplot(2,2,3), imshow(I_noise), title(’Image w/ noise’);
subplot(2,2,4), imshow(I_sob2), title(’Sobel on noise’);

Result

Questions
How does the Sobel operator compare with the Prewitt operator with and without
noise?
Without noise they are almost same
Why do we display the absolute value of the vertical and horizontal images?
Because we have negative and positive values in horizontal and vertical values of image so
we use absolute values.

Task no. 3
Edge Detection with the Roberts Operator

Code
I_rob1 = edge(I,’roberts’); figure subplot(2,2,1), imshow(I), title(’Original Image’);
subplot(2,2,2), imshow(I_rob1), title(’Roberts, default thresh’);
[I_rob2,t] = edge(I_noise,’roberts’); subplot(2,2,3), imshow(I_noise), title(’Image w/ noise’);
subplot(2,2,4), imshow(I_rob2), title(’Roberts on noise’);

Questions
Compare the Roberts operator with the Sobel and Prewitt operators. How does it hold
up to noise?
Roberts operator doesn’t hold up good to noise. It treats noise like edges just like prewitt
operator. Sobel shows a good result as compared to them.
If we were to adjust the threshold, would we get better results when filtering the
noisy image?
Yes by controlling threshold we can set a threshold such that maximum noise is left out due
to thresholding before applying the operator.
Suggest a method to reduce the noise in the image before performing edge
detection.
We can use preprocessing techniques like smoothing filters to reduce the noise.

Result

Task no. 4
Edge Detection with the Laplacian of a Gaussian Operator

Code
I_log1 = edge(I,’log’); figure subplot(2,2,1), imshow(I), title(’Original Image’);
subplot(2,2,2),imshow(I_log1),title(’LoG,default parameters’);[I_log2,t] = edge(I_noise,’log’);
subplot(2,2,3), imshow(I_noise), title(’Image w/ noise’);
subplot(2,2,4), imshow(I_log2), title(’LoG on noise’);
By default, the LoG edge detector uses a value of 2 for σ (the standard deviation of
the filter). What happens when we increase this value?
The edges start to become less visible. For example using sigma =10 we get,
Result

Task no. 5
Edge Detection with the Canny Operator

Code
I_can1 = edge(I,’canny’); figure subplot(2,2,1), imshow(I), title(’Original Image’);
subplot(2,2,2), imshow(I_log1), title(’Canny, default parameters’); [I_can2,t] =
edge(I_noise,’canny’, [], 2.5); subplot(2,2,3), imshow(I_noise), title(’Image w/ noise’);
subplot(2,2,4), imshow(I_can2), title(’Canny on noise’);[I_can3,t] = edge(I_noise,’canny’, [],
2);
figure subplot(1,2,1), imshow(I_can2), title(’Canny, default parameters’);subplot(1,2,2),
imshow(I_can3), title(’Canny, sigma = 2’);
Result

Questions
Does increasing the value of sigma give us better results when using the Canny
detector on a noisy image?
Increasing sigma makes edge detection noise free but if we keep increasing it our required
edges are not detected.

Task no. 6
Edge Detection with the Kirsch Operator

Code
I = imread(’cameraman.tif’); I = im2double(I);
k = zeros(3,3,8); k(:,:,1) = [-3 -3 5; -3 0 5; -3 -3 5];
k(:,:,2) = [-3 5 5; -3 0 5; -3 -3 -3];
k(:,:,3) = [5 5 5; -3 0 -3; -3 -3 -3];
k(:,:,4) = [5 5 -3; 5 0 -3; -3 -3 -3];
k(:,:,5) = [5 -3 -3; 5 0 -3; 5 -3 -3];
k(:,:,6) = [-3 -3 -3; 5 0 -3; 5 5 -3];
k(:,:,7) = [-3 -3 -3; -3 0 -3; 5 5 5];
k(:,:,8) = [-3 -3 -3; -3 0 5; -3 5 5]; I_k = zeros(size(I,1), size(I,2), 8);
for i = 1:8
I_k(:,:,i) = imfilter(I,k(:,:,i));
end
figure
for j = 1:8
subplot(2,4,j),imshow(abs(I_k(:,:,j)),[]), title([’Kirsch mask ’, num2str(j)]); end
Result

Questions
Why are we required to display the absolute value of each mask?
Because it contains negative values so we need to take their absolute.
How did we dynamically display the mask number when displaying all eight images?
All the masks are stored in the same array so by the help of loops we displayed the value of
j for each iteration.
Why are we required to scale the image when displaying it?
If we don’t scale it we get a distorted image. The edges need to be scaled to get a good
view.

Task no. 7
Edge Detection with the Robinson Operator
Code
r = zeros(3,3,8);r(:,:,1) = [-1 0 1; -2 0 2; -1 0 1];r(:,:,2) = [0 1 2; -1 0 1; -2 -1 0];r(:,:,3) = [1 2 1; 0 0
0; -1 -2 -1];r(:,:,4) = [2 1 0; 1 0 -1; 0 -1 -2];r(:,:,5) = [1 0 -1; 2 0 -2; 1 0 -1];r(:,:,6) = [0 -1 -2; 1 0 -1;
2 1 0];r(:,:,7) = [-1 -2 -1; 0 0 0; 1 2 1];r(:,:,8) = [-2 -1 0; -1 0 1; 0 1 2];
I_r = zeros(size(I,1), size(I,2), 8); for i = 1:8
I_r(:,:,i) = imfilter(I,r(:,:,i));
End figure
for j = 1:8
subplot(2,4,j), imshow(abs(I_r(:,:,j)),[]),title([’Robinson mask ’, num2str(j)]);end

I_rob = max(I_r,[],3);
figure, imshow(I_kir,[]);

Result

Questions
How does the Robinson edge detector compare with the Kirsch detector?
Robinson edge detector is a bit mo

re
refine than Kirsch detector.
Lab No. 11: Image Segmentation
Task no. 1
Global Thresholding

Code
I = imread(’coins.png’); figure, imshow(I), title(’Original Image’);figure, imhist(I),
title(’Histogram of Image’); T = 85; I_thresh = im2bw(I,( T / 255)); figure, imshow(I_thresh),
title(’Threshold Image (heuristic)’); T2 = graythresh(I);
I_thresh2 = im2bw(I,T2);figure, imshow(I_thresh2), title(’Threshold Image (graythresh)’);
Result

Question
Which peak of the histogram represents the background pixels and which peak
represents the pixels associated with the coins?
The peak values at the left are the background pixels.
What is the purpose of the im2bw function?
Im2bw is used for thresholding. The threshold value must be between 0 and 1.
Why do we divide the threshold value by 255 in the im2bw function call?
Because threshold value can be only between 0 and 1.
How did the graythresh function compare with the heuristic approach?
Graythresh approach gives a threshold value using Otsu’s algorithm which is far better than
the user defined value in heuristic approach.

Task no. 2
Adaptive Thresholding

Code
I = imread(’gradient_with_text.tif’); figure, imshow(I), title(’Original Image’); I_gthresh =
im2bw(I,graythresh(I)); figure, imshow(I_gthresh), title(’Global Thresholding’);
figure, imhist(I), title(’Histogram of Original’); I_thresh = blkproc(I,[10 10],@adapt_thresh);
figure subplot(1,2,1), imshow(I), title('Original Image');
subplot(1,2,2),imshow(I_thresh),title('Adaptive Thresholding');
Result

Questions
What is the difference between the standard deviation of the two blocks of pixels?
Explain.
std_with_text is greater than std_without_text because there are more changes in the area
where text is present.Variance is more over that area while area without text has less
amount of changes.
How does our function label a block of pixels as background?
the standard deviation of the block of pixels is low, then simply label it as background;
otherwise, perform thresholding on it. This change should cause the function to only
perform thresholding where text exists. Everything else will be labeled as background.
How does the output of the new function compare with the old?
The new function is quite accurate.
Task 3
Modify the code

Code
Id = im2double(I); % I is a uint8 grayscale image
T = 0.5*(min(Id(:)) + max(Id(:)));
% deltaT = 0.01; % convergence criterion
deltaT=0.000001
done = false;
count=1;
Tsave=zeros(1,20);
% Tsave=0;
while ~done
g = Id >= T;
Tnext = 0.5*(mean(Id(g)) + mean(Id(~g)));
done = abs(T - Tnext) < deltaT;
Tsave(1,count)=T
T = Tnext;
count=count+1;
end
Result
Lab No. 12: Morphological Image Processes
Task no. 1
Dilation

Code
I = imread(’blobs.png’);
figure, imshow(I), title(’Original Image’); SE_1 = strel(’square’,3); I_dil_1 = imdilate(I,SE_1);
figure, imshow(I_dil_1), title(’Dilated with 3x3’);SE_2 = strel(’rectangle’, [1 7]);
I_dil_2 = imdilate(I, SE_2); figure, imshow(I_dil_2), title(’Dilated with 1x7’);
Result

Questions
What happened when we dilated the image with a square 3×3 SE?
The image expanded equally in both the directions.
What is the difference in results between the dilation using the 3×3 SE and the 1×7
SE?
The image expanded equally in both the directions using 3x3 while using 1x7 the image
dilated more horizontally.
How would the results change if we use a 7×1 SE? Verify your prediction.
The image will dilate more vertically.

What other SE shapes does the strel function support?


Rectangle, octagon, line, disk, diamond, ball and square.

Task no. 2
Erosion

Code
I_ero_1 = imerode(I, SE_1); figure, imshow(I), title(’Original Image’);
figure, imshow(I_ero_1), title(’Eroded with 3x3’); I_ero_2 = imerode(I, SE_2);
figure, imshow(I_ero_2), title(’Eroded with 1x7’);

Questions
What is the effect of eroding the image?
The image shrinks.

Task no. 3
Opening

Code
I_open_1 = imopen(I, SE_1); figure, imshow(I), title(’Original Image’);
figure, imshow(I_open_1), title(’Opening the image’); figure,
subplot(2,2,1), imshow(I), title(’Original Image’);
subplot(2,2,2), imshow(I_ero_1), title(’Result of Erosion’);
subplot(2,2,3), imshow(I_open_1), title(’Result of Opening (3x3)’); I_open_2 = imopen(I,
SE_2);
subplot(2,2,4), imshow(I_open_2), title(’Result of Opening (1x7)’);

Questions
What is the overall effect of opening a binary image?
Erosion operation removes objects that are smaller than structuring element B and dilation
operation restores the shape of remaining objects
How do the results of opening and erosion compare?
Image is shrunk in opening and erosion but in opening the image is restored after dilation
with the removal of noise.

Task no. 4
Dilation

Code
SE_3 = strel(’square’,5); I_clo_1 = imclose(I, SE_3); figure, imshow(I), title(’Original Image’);
figure, imshow(I_clo_1), title(’Closing the image’);
Result

Questions
What was the overall effect of closing this image?
The few components in the image are connected to each other due to closing.
How does closing differ from dilation?
In dilation the image is expanded while in closing the image is first dilated then eroded in
order to retain the original shape.

Task no. 5
Hit or Miss Transform

Code
SE1 = [ 0 0 0 0 0 ;0 0 0 0 0 ;0 1 1 0 0 ;0 0 1 0 0 ;0 0 0 0 0]
SE2 = [ 0 0 0 0 0 ;1 1 1 1 0 ;0 0 0 1 0 ;0 0 0 1 0 ;0 0 0 1 0]
I_hm = bwhitmiss(I,SE1,SE2); figure, imshow(I), title(’Original Image’);
figure, imshow(I_hm), title(’Hit-or-miss operation’);
Result
What was the result of applying the HoM operation to the image with the given
structuring elements?
Only a few dots are visible.
Task no. 6
Basic Morphological Operations

Code
I = imread('morph.bmp');figure, imshow(I), title('Original image');
se = strel('square',3); I_ero = imerode(I,se); I_bou = imsubtract(I,I_ero);
figure, imshow(I_bou), title('Boundary Extraction'); I_perim = bwperim(I,8);
figure, imshow(I_perim), title(’Boundary using bwperim’);

Questions
Show that the I_perim image is exactly the same as I_bou.

If we specify 4-connectivity in the bwperim function call, how will this affect the
output image?
It doesn’t affect much.
In the last step, we did not save the output image into a workspace variable. Does
this function allow us to do this? If so, what is the syntax?
Yes we can do this like y= bwselect(I); and we will get the new matrix in variable y.
What do the different shades of gray represent when the image is displayed?
By using bwlabel each shape is represented by a different gray level.
What happens if we specify 10, 15, or Inf(infinitely many) iterations instead in
thinning?
The image keeps getting thin until the final point is reached after that no thinning takes
place.
What happens when we specify a higher number of iterations?
How does MATLAB know when to stop thickening an object? (Hint: Check to see
what happens if we use Inf (infinitely many) iterations?
If we specify higher iterations the image keeps on becoming thick but a point comes when
only black lines of background can be seen and rest of the image becomes white at that
point the thickening stops.
How does skeletonization compare with thinning? Explain.
Unlike the thinning operation, skeleton retains the size of the input object. The end points of
the skeleton extend all the way to the edges of the input object.

You might also like