function [bin, p, t, s2b] = otsu(I) % OTSU - Otsu's method for image thresholding % % [bin, p, t, s2b] = OTSU(I) takes an RGB image, I, and maximizes the % between-class variance in the binary image, bin, with respect to the % class-threshold, t. % % Outputs: % % bin = binary image version of I % % p = normalized intensity histogram of I % % t = threshold intensity for maximizing between-class variance % % s2b = between-class variance for 0 to maximum intensity % % Important note: Based on inverse of blue channel, for analyzing leaves. % determine image dimensions r = size(I, 1); % number of rows in image I c = size(I, 2); % number of cols in image I % extract inverse of blue channel of image I I = double(255 - I(:, :, 3)); % compute number of intensity levels in I L = max(max(I)) + 1; % "+ 1" is because 0 is the minimum level % compute normalized intensity histogram p = zeros(1, L); for i = 0:(L - 1) p(i + 1) = sum(sum(I == i))/(r*c); end % compute between-class variance, s2b, for every potential threshold, t s2b = zeros(1, L); for t = 1:(L - 1) % start at 1, the minimum possible threshold w0 = sum(p(1:t)); % class 0 probability w1 = sum(p((t + 1):L)); % class 1 probability mu0 = sum((0:(t - 1)).*p(1:t))/w0; % class 0 mean mu1 = sum((t:(L - 1)).*p((t + 1):L))/w1; % class 1 mean s2b(t + 1) = w0*w1*(mu0 - mu1)^2; % between-class variance end % determine the optimal threshold, t, which maximizes between-class variance t = find(s2b == max(s2b), 1) - 1; % output binary image bin = (I >= t);