% EMP8_ex7         script: EM Potts model 8-neighbors, test segmentation of Lena
%                  EM is Energy Minimization.
% 
% Use:   clear all; EMP8_ex7;        

disp('Load Lena image, 512x512 uint8');
A = imread('lena.bmp');

disp('Set cost matrix R, 512x512x3, double');
R = zeros(512,512,3);
R(:,:,1) = double(A)/500;             % low cost for dark pixels
R(:,:,2) = abs(double(A)-128)/128;    % low cost for gray pixels
R(:,:,3) = abs(double(A)-256)/500;    % low cost for white pixels

disp('make EMP8 structure s, Gaussian low-pass filtering for initial labeling.');
sigma = 1;  % parameter in Gaussian LP filtering
s = EMP8_argin(R,sigma,'lambda',1.5,'v',2);   

disp(['Number of pixels for segment 1 is ',int2str( nnz(s.Li == 1) ),'.']);
disp(['Number of pixels for segment 2 is ',int2str( nnz(s.Li == 2) ),'.']);
disp(['Number of pixels for segment 3 is ',int2str( nnz(s.Li == 3) ),'.']);
disp('And show initial labeling');
figure(1);
imagesc(reshape(s.Li,s.I,s.J));
colormap(gray); axis equal;
title(['Resulting labeling after Gaussian LP filtering. \sigma = ',num2str(sigma)]);
xlabel(s.ti);

disp('Use ICM.');
[Licm, cicm] = EMP8_icm(s);
figure(2);
imagesc(reshape(Licm, s.I,s.J));
colormap(gray); axis equal;
title('Resulting labeling after ICM.');
xlabel(cicm.icmCost);

disp('Use erode.');
[Le, ce] = EMP8_erode(s);
figure(3);
imagesc(reshape(Le, s.I,s.J));
colormap(gray); axis equal;
title('Resulting labeling after erode.');
xlabel(ce.erodeCost);
bw = input('To ''smooth'' borders it is possible to give borderWidth > 0 [0 for skip, or 1,2,3,4) : ');
if bw > 0
    s.borderWidth = bw;
    [Le, ce] = EMP8_erode(s);
    figure(3);
    imagesc(reshape(Le, s.I,s.J));
    colormap(gray); axis equal;
    title('Resulting labeling after erode.');
    xlabel(ce.erode255Cost);
end

disp('Use swap.');
[Lswap,cswap] = EMP8_swap(s);
figure(4);
imagesc(reshape(Lswap, s.I,s.J));
colormap(gray); axis equal;
title('Resulting labeling after swap.');
xlabel(cswap.swapCost);

% display figures on top
figure(1);
figure(2);
figure(3);
figure(4);


