## I've created my own Otsu thresholding function, but is isn't working properly

### Niels Hop (view profile)

on 1 Aug 2019
Latest activity Answered by Image Analyst

### Image Analyst (view profile)

on 2 Aug 2019
I'm trying to implement my own otsu thresholding algorithm.
The input of this function is an grayscale map of an image and the output is the thresholded image and the 'within class variance' to check the result.
I've been stuck on this for several days and can't find the problem with the algorithm. This function gives a very different result from the built-in otsu threshold function.
function [wcv,thresholdedImage] = otsuthreshold(im,varargin)
if(nargin == 1)
[hist,values] = imhist(im);
histLength = length(hist);
histTotal = sum(hist);
wcv = zeros(1,histLength-1); %within class variance
for i = 1:histLength-1
%Weight
wb = sum(hist(1:i))/histTotal;
wf = sum(hist(i+1:end))/histTotal;
%Mean
ub = sum(hist(1:i).*values(1:i))/sum(hist(1:i));
uf = sum(hist(i+1:end).*values(i+1:end))/sum(hist(i+1:end));
%Variance
vb = sum(power(hist(1:i)-ub,2).*values(1:i))/sum(hist(1:i));
vf = sum(power(hist(i+1:end)-uf,2).*values(i+1:end))/sum(hist(i+1:end));
wcv(i) = wb*vb^2+wf*vf^2;
end
[~,index] = min(wcv);
else
index = varargin{1};
wcv = [];
end
im(im <= index) = 0;
im(im > index) = 255;
thresholdedImage = im;
end

dpb

on 1 Aug 2019

R2019a