%% Quanli Wang, Mike West
% MCF example: customize MCF Size-Shape Transform

addpath dist

%% example 1: remove "salt & pepper" noise from a grayscale image
%load a matlab image and add 'salt and pepper" noise 
I = imread('eight.tif'); 
J = imnoise(I,'salt & pepper',0.02);
figure(1), imshow(J), title('Input iamge wit salt & pepper noise')


% use ISSO Size Shape Filter to find salt & pepper mask
[X2 A2] = ImmersionSimulation1(J, @ISSO_SizeShapeFilter, @ISSO_agr,[0 5], []);
[X3 A3] = ImmersionSimulation1(255-J, @ISSO_SizeShapeFilter, @ISSO_agr,[0 5], []);
d = (A2>20 | A3 >20);
d(A2>20 & A3>20) = 0;

% apply median filter only to the mask, to reduce blurness
L = medfilt2(J,[3 3]);
e = J;e(d>0) = L(d>0);
figure(2), imshow(e), title('final denoised image')



%% example 2: use a modified agr function to enhance input image
clear all
a = imread('pears.png');
b = rgb2gray(a);
figure(1),imshow(b), title('input image')

% ISSO transform to enhance input image
graylevels = sort(unique(b(b>0)));
X = b<0;A = uint8(X);
for h = min(graylevels): max(graylevels) %immersion simulation\
    % self-organizie
    T_h  = b >= h;                       % get threshold set
    X = imfill(T_h, 'holes');            % fill holes
    X = bwareaopen(X,1000);              % remove small objects
    
    %aggregate results
    A(X>0) = h;                          
    
end
figure(2),imshow(A,[]), title('smoothed image')
