%% 
% If there are regions that you want to fill in, you can use imclose to 
% fill them in.  It does the opposit of imopen.  It takes the brighest
% value in the mask, and sets the whole mask to that value.  It's useful if
% you have pixels that are not enclosed.

imgCircle = imread('circles.png');
imgCircleDouble = im2double(imgCircle);

figure
imshow(imgCircleDouble)

% We can use imclose to fill in the spaces between.
filt2 = strel('disk',3);
imgClose = imclose(imgCircleDouble,filt2);

figure
imshow([imgCircleDouble imgClose])

% Just as a comparison, how does imopen look on the same image
filt3 = strel('disk',10);
imgOpen = imopen(imgCircleDouble,filt3);

figure
imshow([imgCircleDouble imgClose imgOpen])


%% Sequential opening and closing
clear
close all

img = im2double(imread('rice.png'));
filt1 = strel('disk',4);

imgO = imopen(img,filt1);
imgOC = imclose(imgO,filt1);

figure
imshow([img,imgO,imgOC])


%% Morphological reconstruction
clear
close all

img = im2double(imread('rice.png'));
mask = img - .15;

recon = imreconstruct(mask,img);

figure
imshow([img,mask,recon])%% Filling in holes
clear
close all

% First we can load in the image as per usual, and convert it to a logical
% image
img = im2double(rgb2gray(imread('Picture2.png')));
imgBW = im2bw(img,graythresh(img));

figure
imshow([img imgBW])

% You can see the paper clips and some of the coins have holes in them.  We
% can use the imfill command to correct for that.

imgBW2 = imfill(imgBW,'holes');
figure
imshow([imgBW imgBW2])


