MATLAB Answers


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

Asked by Niels Hop on 1 Aug 2019
Latest activity Answered by Image Analyst
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
wb = sum(hist(1:i))/histTotal;
wf = sum(hist(i+1:end))/histTotal;
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));
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;
[~,index] = min(wcv);
index = varargin{1};
wcv = [];
im(im <= index) = 0;
im(im > index) = 255;
thresholdedImage = im;

1 Answer

Answer by Image Analyst
on 2 Aug 2019

See how the Mathworks does it:
>> edit otsuthresh.m


Sign in to comment.