Balanced Histogram Thresholding with MATLAB. Basic Concept & programming
Balanced Histogram Thresholding in MATLAB
Basic Concept
The main idea is to find the point of the image histogram to balance, the unbalanced histogram of the image. In this method, the image is divided into two main parts, background, and foreground. The method finds the point in the histogram where both parts (background & foreground) are balanced.
The Algorithm
- we determine the start and endpoints in the Histogram of the image
- From these two points, we calculate the midpoint to divide the histogram into the left side & the right side
- we calculate the weights or sum of both parts ( left side & right side) of the histogram
- we compare the sums of both parts
- remove the farthest point (weight) from the heavier side or part
- adjust the midpoint
- recalculate the sums of the left & right side
- compare the weights
- we repeat this procedure until the sums or starting and endpoints become equal or the same on both sides.
The process as shown in a GIF from Wikipedia |
MATLAB Program
You can download the code from my GitHub repository.
Or just copy-paste the following code.
%Reading Image & converting data type to double
img=imread('LovelySpider.jpeg');
%img(:,:,[2:3])=[]; %uncomment this if image is rgb
figure
subplot(2,1,1)
imshow(img)
title('Original Image')
img=double(img);
I=img(:); % Calculating Histogram
hst=zeros(1,256);
for ii =0:255
hst(ii+1)=sum(I==ii);
end
for ii=1:256 % Calculating Start Point
if hst(ii)>0
stpt=ii;
break
end
end
for ii=256:-1:1 % Calculating End point
if hst(ii)>0
endpt=ii;
break
end
end
mdpnt=round((stpt+endpt)/2); %mid point
lsum=sum(hst(stpt:mdpnt)); % sum of left side
rsum=sum(hst(mdpnt:endpt)); % sum of right side
while lsum ~= rsum % iterative process of finding
if rsum>lsum % balanced mid point
endpt=endpt-1;
if round((stpt+endpt)/2)< mdpnt
mdpnt=mdpnt+1;
lsum=sum(hst(stpt:mdpnt));
rsum=sum(hst(mdpnt:endpt));
end
else
stpt=stpt+1;
if round((stpt+endpt)/2) > mdpnt
mdpnt=mdpnt-1;
lsum=sum(hst(stpt:mdpnt));
rsum=sum(hst(mdpnt:endpt));
end
end
end
% image processing
nimg=zeros(size(img));
rng=size(img);
for ii=1:rng(1)
for jj=1:rng(2)
if img(ii,jj)<=(mdpnt/2) % threshold point to separate the image background
nimg(ii,jj)=255;
else
nimg(ii,jj)=0;
end
end
end
subplot(2,1,2)
imshow(nimg)
title('Processed Image')
I=nimg(:); % Calculating Histogram
hst2=zeros(1,256);
for ii =0:255
hst2(ii+1)=sum(I==ii);
end
figure
subplot(2,1,1)
stem(hst)
grid on
title('original Image Histogram')
axis([1 256 0 65000])
subplot(2,1,2)
stem(hst2)
title('processed Image Histogram')
figure
stem(hst)
grid on
%axis([0 172 0 65000])
hold on
stem(mdpnt,hst(mdpnt),'red', 'linewidth',2)
disp('The balanced threshold value of Histogram is :')
disp(mdpnt)
Figure 2 |
Comments
Post a Comment