You are on page 1of 6

Assignment 2

Image Processing
ENG/13/017 S.L.D De Silva

MATLAB program to find implement the basic global thresholding algorithm to


detect objects.

Code to find global threshold value


function thresh = thresholdingglobal(I,T,dT)
%to avoid Threshold exceed maximum intensity
maxInt=max(I(:))
if(T>=maxInt)
T=maxInt-1;
end
%get the dimensions of matrix
[vSize hSize]=size(I);
totSize=hSize*vSize;
%convert 2D array to 1D row array
v=double(reshape(I,1,totSize));
Tnew=T;%new T value
%dT is the least distance between new T and the previous T
Tprev=dT;%previous T value
while(abs(Tnew-Tprev)>dT)
lowerPx=0;%pixels intensity sum of px less than or equal to threshold
lowerNum=0;%no of pixels less than or equal to threshold
upperPx=0;%pixels intensity sum of px greater than threshold
upperNum=0;%no. of pixels greater threshold
Tprev=Tnew%assign new T value to the previous value of T
i=1;%counter
%add lower sumand upper sum seperately
for i=1:totSize
if(v(i)<=Tprev)
lowerNum=lowerNum+1;
lowerPx=lowerPx+v(i);
else
upperNum=upperNum+1;
upperPx=upperPx+v(i);
end
end
m1=lowerPx/lowerNum;%mean of pixels having intensity less than Tprev
m2=upperPx/upperNum;%mean of pixels having intensity more than Tprev
Tnew=(m1+m2)/2;%new threshold value
end
thresh=Tnew;
end

Function to threshold
function y=threshFunc(I,T)
I=im2double(I);%convert to double
%thresholding
G=I>T;
Y=G.*255;
end

Testing the code


I=imread('img1.jpg');%load image
imshow(I) %display (Image 1)
%convert image to gray scale by rgb2gray(I) if image is RGB
imhist(I);%to get the histogram of the image (Image 2)

Image 1

Image 2

%set parameter values


T=60; %estimate threshold
dT=2; %least distance between new T and the previous T

%calling threshold value returning function


t=thresholdingglobal(I,T,dT)

Tprev =
60
Tprev =
68.1877
Tprev =
76.5002
Tprev =
82.7507
Tprev =
85.9530
t =
86.7824

Analysis
dT
2
2
2
1
0.1
0.001

T
10
80
120
80
80
80

% therefore 86.9843 was selected as threshold and thresholded


Th=threshFunc(I,t);
imshow(Th); %Image 3
%Image seems to have some white noise.
%This can be smoothened out by a median filter
J = imnoise(th,'salt & pepper',0.02);
K = medfilt2(J);
imshow(K) % Image 4

t
86.7824
86.7824
87.3131
86.9843
86.9843
86.9843

Image 3

Image 4

Repeat this for an image with different histogram


img=imread('crowd.jpg');
imshow(img) %Image 5
imhist(img) %Image 6

Image 5
%find threshold value
T=60; dt=2;
t1=thresholdingglobal(img,T,dT)

Tprev =

Image 6

60
Tprev =
56.4950
Tprev =
53.7533
t1 =
52.1780

Analysis
dt
T
t1
2
60
52.1780
1
60
51.4424
0.001
60
50.6445
0.001
100
50.6445
0.001
150
50.6445
0.001
10
50.6445
It seems that this function tends to give the mean value of the distribution of the
histogram which is 50.6445. The accuracy of the mean depends on the dt value
precision.
th1=threshFunc(img,t1);
L=imshow(th1); % Image 7

Image 7

You might also like