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

3 views (last 30 days)
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

Answers (1)

Image Analyst
Image Analyst on 2 Aug 2019
See how the Mathworks does it:
>> edit otsuthresh.m

Products


Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!