MATLAB: Otsu Threshold algorithm function for blockproc

blockprockotsu threshold

Hello! I try to write an Otsu Threshold algorithm function to be used later along with the blockproc. Here is my code:
clc; clear; close all;
function out = graythresh(im)
if isstruct(im)
im = im.data;
end
if ~isempty(im)
I = im2uint8(im(:));
num_bins = 256;
counts = imhist(I,num_bins);
P = counts/sum(counts);
omega = cumsum(p);
mu = cusum(p.*(1:num_bins)');
mu_t = mu(end);
previous_state = warning('off','MATLAB:divideBYZero');
sigma_b_squared = (mu_t*omega-mu).^2./(omega.*(1-omega));
warning(previous_state);
maxval = max(sigma_b_squared);
isfinite_maxval = isfinite(maxval);
if isfinite_maxval
idx = mean(find(sigma_b_squared == maxval));
level = (idx-1)/(num_bins-1);
else
level = 0.0;
end
if nargout > 1
if isfinite_maxval
em = maxval/sum(p.*((1:num_bins).^2)')-mu_t^2);
else
em = 0;
end
end
out = (im>level*max(im(:)));
disp(['Threshold =',num2str(round(255*level))])
However, this code cannot be run successfully. The command window state that
Error: File: OTSUBLOCK.m Line: 3 Column: 1
Function definitions are not permitted in this context.
Please kindly give me advices
Thankyou!

Best Answer

You must delete the first line, the one that says
clc; clear; close all;
Also, you must either rename the file from OTSUBLOCK.m to graythresh.m or else you must change the "function out = graythresh(im)" to
function out = OUTSUBLOCK(im)