close all;
clear all;
warning('off','all')
display(sprintf('\n .... Image Defencing Demo ..... '));
tic;
%% SETUP
exp = 'exp303'; % Available set of experiments includes exp1, exp2, exp3, exp4, exp7, exp8, exp16, exp17, exp19
applyDetection = 01; % Set to 1 if fence detection is required
loadSavedPoints = 01; % Set to 1 to detect the fence based on already saved points. This works only when applyDetection is set
saveFenceParameters = 0;  % Set to 1 to save the detection results and parameters
applyRecovery = 01; % Set to 1 for recovery procedure
proposed = 1; % Set to 1 to get results through proposed method and 0 to uses Crimisi method. It is effective when applyRecovery is set

outFolder = 'Results_Demo5'; % Name of the output folder
mkdir(outFolder);
%% Fence detection parameters
if applyDetection 
    
    NOP = 20; % Number of points
    d = 4; % Mahalanobis distance in fence detection
    windSize = 5; % Window size for each point
    mode = 8; % 4-neighbor or 8-neighbor
    th = 1; % thrash hold for connected components
    dilSize = 5; % dilation element size
    
    
    %% Load the saved points or select the new points
    if loadSavedPoints
        load(exp);
        fName = strcat(exp, '.jpg');
        
        im = imread(fName);
        showFigure(im);
    else
        fName = strcat(exp, '.jpg');
        im = imread(fName);
        [ R, G, B, NOP, x, y ] = gtPoints(im , NOP, windSize);
    end
    
    d = 13; % Mahalanobis distance in fence detection
    th = 18; % thrash hold for connected components
    dilSize = 7; % dilation element size
    windSize = 5; % Window size for each point
    
    %% Fence Detection
    display('Detecting Fence...');
    display(sprintf(' Number of user marked points: %d \n Selection Mode: 8-neighbor \n Window Size: %d \n Mahalanobis distance: %2.2f', NOP, windSize, d));
    display(sprintf(' Dilation Structuring Element Size: %d', dilSize));
    [mask] = fenceDetCC(im, R, G, B , NOP, windSize, d );
    figure; imshow(mask), title('Original Mask after fence detetction');
    sName1 = strcat(outFolder,'/',exp,'_fence.bmp');
    imwrite(mask , sName1);
    
    % % Bayes classification is not used in most of the experiment to
    % % limit the execution time. The optimal results are achieved with by
    % % carefully marking the points on the fence and by tuning the dilation
    % % and window size variables.
    % [mask] = BayesClassification( mask, im );
    % figure; imshow(mask), title('Original Mask after Bayes Classification');
    % sName1 = strcat(outFolder,'/',exp,'_fence_B.bmp');
    % imwrite(mask , sName1);
    display(' Bayes Classification is disabled.');
    
    %% Fence refinment
    % Removing FNs through CONNECTED COMPONENETS
    [mask] = cComponent(mask, mode, th);
    figure; imshow(mask), title('Fence after thresholding Connected Components');
    sName2 = strcat(outFolder,'/',exp,'_cc.bmp');
    imwrite(mask , sName2);
    
    % Including FPs through DILATION
    [mask, imMasked] = dilation(im, mask, dilSize);
    figure; imshow(mask), title('Fence after dilation');
    sName3 = strcat(outFolder,'/',exp,'_mask.bmp');
    imwrite(mask , sName3);
     
    area = sum(sum(mask))/(size(mask,1)*size(mask,2))*100;
    display(sprintf('Area occluded by the fence: %2.2f%%.', area));
    
    sName4 = strcat(outFolder,'/',exp,'_masked.bmp');
    imwrite(imMasked , sName4);
    figure; imshow(imMasked), title('Masked Image');
    
    % Save the parameters for future use
    if saveFenceParameters  
        %         save(exp, 'R', 'G', 'B', 'exp', 'th', 'NOP', 'dilSize', 'mode', 'd', 'windSize', 'x', 'y');
        save(exp, 'R', 'G', 'B', 'exp', 'th', 'NOP', 'dilSize', 'mode', 'd', 'windSize');
    end
end 

%% Apply the recovery procedure
if applyRecovery
    mask = imread(strcat(outFolder,'/',exp, '_mask.bmp'));
    mask = im2bw(mask, 0.5);
    imMasked = imread(strcat(outFolder,'/',exp, '_masked.bmp'));
    im = imread(strcat(exp, '.jpg'));    
   if ~proposed
        %%  --------   Crimisi Inpainting    ----------
        [recoveredImage,~,~,~,~,~] = inpaint7(im, imMasked, [0 0 0]);
        recoveredImage = uint8(recoveredImage);
        figure; imshow(recoveredImage);
        sNameR = strcat(outFolder,'/',exp,'_restored_Ciminisi.bmp');
        imwrite(recoveredImage , sNameR);
    else
        %%  --------   Proposed Recovery    ----------
        recoveredImage = recoverFence(im, mask, imMasked, mask, exp, outFolder );
        figure; imshow(recoveredImage);
        sNameR = strcat(outFolder,'/',exp,'_restored.bmp'); title('De-fenced Image.');
        imwrite(recoveredImage , sNameR);
    end
end
display(' Image is de-fenced. See "..._restored.bmp" file.');
display(sprintf('\n .... Image Defencing Demo ..... '));
toc;
