%Morphological Approach

% read image
I = imread('Fold.jpg');
imshow(I);
% grayscale image
G = rgb2gray(I);
%figure; imshow(G);

% smooth (median)
fSize = 52;
S = medfilt2(G, [fSize fSize]);
figure; imshow(S);
% make a strel for bottom-hat
bh_radius1 = 15;
SE1 = strel('disk', bh_radius1);
bh_radius2 = 25;
SE2 = strel('disk', bh_radius2);
% top hat
S1 = imtophat(S, SE2);
figure,imshow(imadjust(S1));
% bottom hat
S2 = imbothat(S, SE1);
figure,imshow(imadjust(S2));
% Subtract bottom-hat from smoothed image
BH2 = imadd(S,S1);
figure,imshow(BH2);
BH1 = imsubtract(BH2,S2);
figure,imshow(BH1);
% double threshold on combined bottom/top hat
BL1 = (BH2 < 60);
BL2 = (BH2 < 110);
figure;imshow(BL1)
figure;imshow(BL2)
[indI,indJ] = find(BL1 > 0);
[indI,indJ] = find(BL2 > 0);
B3 = bwselect(BL2, indI, indJ, 8);
figure;imshow(B3)
% %bridge
BR= bwmorph(B3, 'bridge',60);
figure; imshow(BR)
%skeleton
SK = bwmorph(BR,'skel',50);
figure;imshow(SK)

%dilate with disk
radius =10;
h = strel('disk', radius);
SKd = imdilate(SK, h);
figure; imshow(SKd);

%fill
F= bwmorph (SKd, 'fill', 60);
figure, imshow(F)

%invert image
Finv= 1-F;
figure, imshow(Finv)

