Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Name : Ganni Akash

Roll No: BT21ECE019

Experiment-1
Aim:

To write a generalized function to calculate the mean and


standard deviation of an image (grayscale or coloured with
custom dimensions) and verify it with the in-built
functions.

Software: MATLAB

Code:

clc;
clear all;
close all;

str = 'cameraman.tif';

mean_n = cus_mean(str);
std_n = cus_std(str);

s1 = sprintf("Custom mean: %d, Inbuilt mean: %f", round(mean_n*255),


mean2(imread(str)));
s2 = sprintf("Custom std dev: %d, Inbuilt std dev: %f", round(std_n*255),
std2(imread(str)));

disp(s1);
disp(s2);

function std_n = cus_std(str)


A = imread(str);
A= im2double(A);

t = 0;
su = 0;
mean_n = cus_mean(str);
s = size(A);
if length(s) == 2
s = [s,1];
end
for z=1:s(3)
for y=1:s(1)
for x=1:s(2)
su = su + (A(y, x, z) - mean_n)^2;
t = t + 1;
end
end
end
std_n = (su/t)^0.5;
end

function mean_n = cus_mean(str)


A = imread(str);

A= im2double(A);
t = 0;
su = 0.0;

s = size(A);

if length(s) == 2
s = [s, 1];
end
for z=1:s(3)
for y=1:s(1)
for x=1:s(2)
su = su + A(y, x, z);
t = t + 1;
end
end
end
mean_n = su/t;
end
Results:

With grayscale image:

With colored image:

Conclusion:

1. In this we have written the functions to calculate


cus_mean and cus_std to calculate the mean and standard
deviation of the image given as input to these
functions.
2. These functions can handle both grayscale and color
images and also they can dynamically calculate the mean
irrespective of the size and dimensions of the image.
3. The functions return a normalized value.
4. We had to convert the array to double precision (or
alternatively we could typecast the ‘su’ variable to
double) to avoid the overflow that would occur when ‘su’
goes over 255 when in uint8 type.
5. We have verified the output with the in-built function
and the results are matching.

You might also like