% ==================================================================================================
% Module:   skeleton.m
%
% Usage:    Free standing routine that performs morphological skeletonization.
%
% Purpose: 
%     Implement and verify morphological skeletonization.
%
%     
% Input Variables:
%     N/A
%     
% Returned Results:
%     The image read in on Line 41 is skeletonized and partially
%     reconstructed.  Results are shown in figures that open automatically.
%  
% Restrictions/Notes:
%     This function is geared for binary images. 
%     
% See Also:
%       dilation(), setdifference(), SK(), union()
%
% References:
%
% 
% Author:       Justin Ford
% Date:         2/14/04
% Revisions:    none
% ==================================================================================================

% Clear Workspace
close all; clear all; clc;

% Read in initial image
X = imread('../images/bear.gif');

% Define Structuring Element
% B = ones(3);
B = ones(5);
B(1,1) = 0; B(5,1) = 0; B(1,5) = 0; B(5,5) = 0;

[skel, Si] = SK(X,B);

% Show result
figure
imshow(logical(skel))

% Perform partial reconstruction
N = size(Si,2)/256 - 1;
S_N_dil = dilation(Si(1:256,(N*256+1):((N+1)*256)),B);
S_N_dil = S_N_dil((1+floor((size(B,1)/2))):(size(S_N_dil,1)-floor((size(B,1)/2))),(1+floor((size(B,1)/2))):(size(S_N_dil,2)-floor((size(B,1)/2))));     % Resize dilation result to 256x256

for i=N:-1:(N-3)
    S_N_1 = union(Si(1:256,((i-1)*256+1):(i*256)),S_N_dil);
    S_N_dil = dilation(S_N_1,B);
    S_N_dil = S_N_dil((1+floor((size(B,1)/2))):(size(S_N_dil,1)-floor((size(B,1)/2))),(1+floor((size(B,1)/2))):(size(S_N_dil,2)-floor((size(B,1)/2))));     % Resize dilation result to 256x256
end

% Show partial reconstruction
figure
imshow(logical(S_N_1))

% Show difference between original and partial reconstruction
diff = setdifference(X,S_N_1);
figure
imshow(logical(diff))