Experiment 4madsip Lab

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

EXPERIMENT 4

AIM: Write a program to detect the edges of a coloured image using Sobel and
Prewitt operators and verify the results using the inbuilt commands.

SOFTWARE USED: MATLAB R2019a

THEORY: The discontinuity in the image brightness is called an edge. Edge


detection is the technique used to identify the regions in the image where the
brightness of the image changes sharply. This sharp change in the intensity value
is observed at the local minima or local maxima in the image histogram, using
the first-order derivative.

The techniques used in this experiment are first-order derivative techniques


namely:
I .Prewitt Operator
2.Sobel Operator

MATLAB CODE:
This MATLAB code performs edge detection on an input image using both
manual implementation and built-in functions for Sobel and Prewitt operators.

CODE:
% Read the image
I = irnread('fishjpg');

% Convert the image to grayscale


!_gray= rgb2gray(I);
% Convert grayscale image to double I_gray =
im2double(l_gray);

% Initialize the output images for manual approach


BW _sobel_manual = zeros(size(l_gray));

1
BW_prewitt:....manual = zeros(size(I_gray));

% Define the Sobel and Prewitt operators h_sobel =


[L0-1 ; 20-2; L0-l]; h_prewitt=[l l l; 000; -1-
1 - I] ;

% Detect edges using the Sobel and Prewitt operators (manual approach) for row
=2:size(l_gray, 1)-1 for col =2:size(I_gray, 2)-l
% Calculate the gradient using the Sobel operator
Gx = sum(sum(h sobel * l_gray(row-l:row+ l,
col-l:col+ I)));
Gy = sum(sum(h_sobel * l _gray( row- I :row+ I ,
col-l:col+ 1)'));
gradient_sobel = sqrt(Gx"2 + Gy"2);

% Calculate the gradient using the Prewitt operator


Gx = sum(sum(h_prewitt * l_gray(row-1:row+ I,
col-l:col+ 1)));
Gy = sum(sum(h_prewitt * I_gray( row- I :row+ I ,
col-1 :col+ I)'));
gradient_prewitt = sqrt(Gx"2 + Gy"2);

% Store the edge strength as the pixel value


BW_sobel_manual(row, col)= gradient:....sobel;
BW_prewitt_manual(row, col)= gradient_prewitt; end
end

% Detect edges using Sobel operator (built-in function)


BW_sobel_auto = edge(I_gray, 'sobel');

% Detect edges using Prewitt operator (built-in function)


BW_prewitt_auto = edge(I_gray, 'prewitt');

% Display the results

2
figure ; subplot(3, 2, 1);
imshow(I); title('Original
lmaot;,.e')·
,

subplot(3, 2, 2); imshow(I_gray);


title('Grayscale Image');

subplot(3, 2, 3); imshow(BW_sobel_manual, []);


title('Sobel Operator (loop)');

subp1ot(3, 2, 4); imshow(BW_prewitt_manual, []);


title('Prewitt Operator (loop)');

subplot(3, 2, 5); imshow(BW_sobel_auto);


title('Sobel Operator (inbuilt)');

subplot(3, 2, 6); irnshow(BW_prewitt_auto);


title('Prewitt Operator ( inbuilt)');

3
EXPERIMENT 2
AIM: Write a program to perform 'zoom in' and 'zoom out' operation on an image by
200% and 50% respectively using (a) nearest neighbour (b) bi-linear interpolation (c) bi-
cubic interpolation.

SOFTWARE USED: MATLAB R2019a

THEORY: In the context of image processing, zooming refers to altering the scale of an
image, either by enlarging or reducing it Let's delve into the details:
1. Zoom In (Minimization):
• Purpose: To compress the size of an image.
• Effect: The image is enlarged, making details more visible and clearer.
• Techniques: Various algorithms manipulate pixels to zoom in on specific
portions of the image.
• Example Imagine focusing on a specific area of a photograph to see
intricate details.
2. Zoom Out (Maximization):
• Purpose: To expand or increase the size of an image.
• Effect: The image is reduced, showing a broader view with less detail.
• Techniques: Like zooming in but applied to a larger area.
• Example Viewing a wide landscape photo where distant objects appear
smaller.

MATLAB CODE:
1. using loop
(a). Nearest neighbour zoom in

% Load the image


originallmage = imread('fish.jpg');

% Define the scaling factor


scalingFactor = 2;
% for example, to resize to 50% of original size

4
% Detennine the new dimensions
newHeight= round(size( originall mage, I) * scalingfactor);
newWidth = round(size(originallmage, 2) * scalingfactor);
% Initialize the resized image
resizedimage = uint8(zeros(newHeight, newWidth, size(originallmage, 3)));
% Iterate over each pixel in the resized image for
i = I :newHeight
for j = I :newWidth
% Calculate the corresponding pixel in the original image
x = round(i I scalingfactor);
y = roundU / scalingfactor);
% Ensure the coordinates are within bounds x
= min(max(x, I), size(originallmage, I)); y=
min(max(y, I), size(originallmage, 2));

% Assign the pixel value from the original image to the resized image
resizedimage(i, j, :) = original image(x, y, ); end
end
% Display the original and resized images
figure; subplot( I, 2, I);
imshow(original Image); title('Original
Image');
subplot( ), 2, 2); imshow(resizedJmage);
title('zoomed in Image');

Nearest neighbour Zoom out:


% Load the image
originallmage = imread('fish.jpg');

% Define the scaling factor


scalingf actor = 0.5; % for example, to resize to 50% of original size

% Determine the new dim ensions newHeight =


round(size(originallmage, I)* scalingfactor); newWidth =
round(size(originallmage, 2) * scalingfactor);

5
% Initialize the resized image
resizedimage = uint8(zeros(newHeight, newWidth, size(originallmage, 3)));

% Iterate over each pixel in the resized image for


i = I :newHeight for j = I :newWidth
% Calculate the corresponding pixel in the original image
x = round(i / scalingfactor); y = round(i / scalingfactor);

% Ensure the coordinates are within bounds


x = min(max(x, I), size(originallmage, I)); y=
min(max(y, 1), size(originallmage, 2));

% Assign the pixel value from the original image to the resized image
resizedlmage(i, j , :) = originallmage(x, y, :); end
end

% Display the original and resized images


figure; subplot( I, 2, I);
imshow(original Image); title('Original
Image');

subplot( !, 2, 2); imshow(resizedimage);


title('zoomed out Image');

ZOOM In Using Matlab Function:

clc; clea r;
close all; z=2; %zooming
factor
A=imread('kobi. png');
subplot(2,2,1) imshow(A)
title('original image');

B=imresize(A,2,"nearest");
subplot(2,2,2) imshow(B)

6
title('zoomed in image with nearest neighbour' );

C=im resize(A,2," bilinear");


subplot(2,2,3) imshow(C)
title('zoomed in image with bilinear' );

D=imresize(A,2,"bicubic");
subplot(2,2,4) imshow(D)
title( 'zoomed in image with bicubic');

ZOOM Out Using Matlab function:


clc; clea r;
close all;
z=.5; %zooming factor

A= imread('peppers.png');
subplot(2,2,1) imshow(A)
title( 'original image');

B=i mresize(A,.5, "nearest");


subplot(2,2,2) imshow(B)
title( 'zoomed out image w ith nearest neighbour');

C=imresize(A, .5,"biIi near");


subplot(2,2,3) imshow(C)
title('zoomed out image w ith bilinear');

D=im resi ze(A,.5, "bicub ic");


subplot(2,2,4) imshow(D)
title('zoomed out image with bicub ic');

7
Experiment - 1
AIM : To write a program to read a RGB image and perform the following operations
on the image:

1. Extract red, green, and blue components of the image and then combine them to
get the original image.

2. Convert the RGB image into grayscale image using equation:


Y = (77/256) *R + (150/256) *G + (29/256) *B
3. Add and subtract another RGB image into the original image.

4. Calculate the sizes of all the images.

SOFTWARE USED: MATLAB R2019a

THEORY: An RGB image is a type of digital image that uses the


RGB color model to represent colours. The RGB color model is an additive color
model, which means that different colors are created by combining different
amounts of red, green, and blue light. Each pixel in an RGB image has three
values, one for each color component, that determines the color and brightness of
that pixel. The range of these values depends on the bit depth of the image, which
is the number of bits used to store each color component. For example, an 8-bit
RGB image can have values from Oto 255 for each color component, resulting in
I 6.7 million possible colours.

MATLAB CODE:

1.
clc;
clear;

close all;

A=imread('peppers.png');

subplot(2,3,1)

8
imshow(A)
title('original image');
R=A(,:, 1);
subplot(2,3,2)
imshow(R)
title('Highlighted Red colour') G=A(:, ,2);
subplot(2,3,3)
imshow(G)
title('Highlighted GREEN colour')
B=A(: ,:,3);
subplot(2,3,4)
imshow(B)
title('Highlighted BLUE colour')
combined=cat(3,R,G,B);
subplot(2,3,5)
imshow( combined)
title('combined ofRGB')
Y=rgb2gray(A);
subplot(2,3,6)
imshow(Y)
title('RGB to grayscale')

2.
clc; clear; close all;
image=zeros(400,300,3); %
Either use this (This is a
comment)

9
image(:,:,! )=77/255;
image(:, :,2)=150/255;
image(:,:,3)=29/255;
% or this can be used (this is a comment)
%R=77/255;
%G=l50/255;

%B=29/255;
%image=cat(3,R,G,B);

subplot(2, l,l) imshow(image)


title('combined of RGB')
Y=rgb2gray( image);
subplot(2, 1,2) imshow(Y)
title('RGB to grayscale')

3. clc; clear; close all;


B=zeros(384,512,3);
B(:,:, l )=77/255;
B(:,:,2)= 150/255;
B(:,:,3)=29/255;
subplot(2,3,2) imshow(B)
title('Second Image')
A=imread('peppers.png');
subplot(2,3, I) imshow(A)
title('First image');

R=A(:,:, l);

10
G=A(:,:,2);

B=A(:,:,3);

P=cat(3,R,G,B);
subplot(2,3,3) imshow(P)
title('First image after adding RGB of it'); [height_ I,
width_ 1, colour_ I]=size(A); disp(height_ I);
<lisp( width_ I); <lisp(colour_ I);
[height_2, width_2, colour_2]=size(B);
disp(height_ 2); disp(width_ 2); <lisp( colour_ 2);

C=P+B; subplot(2,3,4)
imshow(C)
title(' Addition');

D=P-B; subplot(2,3,5)
imshow(D)
title('Subtraction');

4.
etc; clear; close all;
B=zeros(400,300,3);
B(:,:, I)=77/255;

B(:,:,2)= 150/255;
B(:,:,3)=29/255;
subplot(2,3,2)
imshow(B)

11
title('Second image')
A=imread('peppers.png');
subplot(2,3, I) imshow(A)
title('First image');

[height_ !, width_ !, colour_ l]=size(A);


[height_ 2, width_ 2, colour_ 2]=size(B);
fprintf('the height of A is ¾d\n',height_ I);
fprintf('the width of A is ¾d\n',width_ I);
fprintf('the height ofB is %d\n',height_2);
fprintf('the width of B is %d\n',width_2);
fprintf('the size of A is %dX%d\n',height_ l ,width_ I);
fprintf('the size ofB is %dX%d\n',height_2,width_2);

Observation and Result:


All the parts of the question were performed, and the result is shown below

12
EXPERIMENT 3
AIM : Write a program to construct (i) 5 x5 Gaussian filter (ii) average filter (iii) median filter
and compare their results on an image corrupted by salt and pepper noise.

SOFTWARE USED: MATLAB R2019a

THEORY: noise refers to unwanted modifications that a signal may undergo during capture,
storage, transmission, processing, or conversion. Digital filter is a system that operates on a
sampled, discrete-time signal to reduce or enhance certain aspects of that signal. Unlike analog
filters, w hich work with continuous-time analog signals, digital filters perform mathematical
operations o n digitized signals or numerical data stored in a computer memory

MATLAB CODE:
Filters using loop:

(1). AVG filter:

% Read the input image

A= imread('fish.j pg');

B=rgb2gray(A);

input_ image=imnoise(B,"salt & pepper" ,.08);

% Define the fi lter size (e.g., 3x3 or 5x5)

filter_size = 3;

% Get the size of the input image

[rows, cols]= size(input_ image);

% Initialize the filtered output image

filtered_image = zeros(rows, cols, 'uint8');

% Apply the average filter using a for loop

for i = I :rows

for j = 1:cols

% Determ ine the range of pixels to average

13
row_indices = max(I, i • floor(filter_size/2)):min(rows, i + floor(filter_size/2));

col_ indices = max( I, j - floor( filter_ size/2)):min(cols, j + floor( filter_ size/2 ));

% Extract the region of interest

region= input_image(row_ indices, col_indices);

% Compute the average of the selected pixels

filtered_ image(i,j) = mean(region(:));

end

end

% Display the original and filtered images

figure; subplot(2, 2, 3);

imshow(input_i mage);

title('noisy image');

subplot(2, 2, 4);

imshow(filtered_ image);

title('Filtered Image using avg filter');

subplot(2, 2, I);

imshow(A);

title{'Original Image');

subplot(2, 2, 2);

imshow(B);

title{'gray image');

(2). Gaussian filter

I=imread(" fish.jpg");

subplot(2,2, I)

imshow(I)

14
title('original image')

i=rgb2gray(I);

subplot(2,2,2)

imshow(i)

title('gray image')

N=imnoise(i,'salt & pepper',0.05);

subplot(2,2,3) imshow(N)

title('noisy image') sigma= I;

A=createGaussianfilter(sigma);

F=imfilter(N,A); subplot(2,2,4)

imshow(F)

title('filter image')

function gaussianfilter = createGaussianfilter(sigma)

% Create a SxS Gaussian filter

filterSize = 5;

filterRadius = floor(filterSize / 2);

gaussianfilter = zeros(filterS ize, filterSize);

normalizationfactor = O;

% Compute Gaussian kernel values

for i = -filterRadius filterRadius

for j = -filterRadi us filterRadi us

15
gaussianfilter(i + filterRadius + I, j + filterRadius + I)= exp(-(iA2 + Y2) I (2 * sigmaA2));
normalizationfactor = normalizationfactor + gaussianfilter(i + filterRadius + I, j + filterRadius
+ I);

end

end

% Normalize the filter

gaussianfilter = gaussianfilter / normalizationfactor; end

Using Matlab Functions:

clc; clear

; close

all;

l=imread(" fish .jpg");

subplot(2,3, I)

imshow(I)

title('original image')

i=rgb2gray(I);

subplot(2,3,2)

imshow(i)

title{'gray image')

N=im noise(i,'salt & pepper',0.05);

subplot(2,3,3)

imshow(N)

title('noisy image')

G=imgaussfilt(N,5);

subplot(2,3,4) imshow(G)

16
title('image after gausian fi lter')

width=S;

filter-ones( width)/width"2;

A=imfilter(N, filter);

subplot(2,3,5) imshow(A)

title(' image after avg filter')

M=medfilt2(N);

subplot(2,3,6) imshow(M)

title('image after median filter')

17

You might also like