function [Ppost_final, trials, alpha] = classify_single (image)
% Start EM algorithm
[x, y, z] = size(image);
for chan=1:3
% Initialization
alpha = 1/8 * ones(3, 3);
alpha(2, 2) = 0;
sigma = 0.0075;
%P0 = 1/ 256;
P0 = 1/((sigma *(2*pi)^0.5));
img = double(image(:,:,chan)) ./ 255 ;
N = 1; % want 3x3 square where middle square is 0
error = 5;
trials = 0;
epsilon = sigma / 100;
while (error > .01) & (trials < 100)
% Expectation
est = conv2(img, alpha, 'valid');
res = img(2:end-1, 2:end-1) - est;
%epsilon = sigma / (100);
%Pcond = 1/(sigma *(2*pi)^0.5) * (exp(-(res).^2/(2*sigma^2))) * 2 * epsilon;
Pcond = 1/(sigma *(2*pi)^0.5) * (exp(-(res).^2/(2*sigma^2)));
%P0 = 1/(sigma *(2*pi)^0.5) /255;
Ppost = Pcond ./ (Pcond + P0);
% Generate f(x+u, y+v) matrices first
for v=-N:N
for u=-N:N
eval(['img' num2str(u+N) num2str(v+N) '=img(2+' ...
num2str(u) ':end-1+' num2str(u) ', 2+' num2str(v) ':end-1+' num2str(v) ');']);
end
end
count = 1;
% A and B matrices
Afinal = zeros(1, ((2*N)+1)^2-1);
for t=-N:N
for s=-N:N
BaseMatrix = Ppost .* img(2+s:end-1+s, 2+t:end-1+t);
Bmatrix = Ppost .* img(2+s:end-1+s, 2+t:end-1+t) .* img(2:end-1, 2:end-1);
B(count) = sum(sum(Bmatrix));
count = count+1;
Anew = [sum(sum(BaseMatrix .* img00)), ...
sum(sum(BaseMatrix .* img10)), ...
sum(sum(BaseMatrix .* img20)), ...
sum(sum(BaseMatrix .* img01)), ...
sum(sum(BaseMatrix .* img21)), ...
sum(sum(BaseMatrix .* img02)), ...
sum(sum(BaseMatrix .* img12)), ...
sum(sum(BaseMatrix .* img22))];
Afinal = [Afinal ; Anew];
end
end
Afinal = Afinal (2: end, :);
alphaold = alpha;
B = [B(1:4), B(6:end)];
Afinal = [Afinal(1:4, :) ; Afinal(6:end,:)];
alpha = linsolve (Afinal, B');
alpha = [alpha(1:4); 0; alpha(5:end)];
alpha = [alpha(1:3), alpha(4:6), alpha(7:9)];
sigma = ((sum(sum(Ppost .* res.^2)))/(sum(sum(Ppost)))).^.5;
error = sum(sum(abs(alphaold-alpha)));
trials = trials + 1;
end % End entire algorithm
alpha_final( :,:, chan) = alpha;
Ppost_final(:,:,chan) = Ppost;
end
%}
error;
alpha;
trials;
end