%% Esercitazione 2
close all;

img = imread('pixels_wb.tiff');

figure;
imshow(img)
img = img > 100;

s = [0,1,0;1,1,1;0,1,0]

img_erode = my_erode(img,s);

figure('Name','Erosion');
subplot(1,3,1)
imshow(img);
title('original')
subplot(1,3,2)
imshow(img_erode);
title('erosion')
subplot(1,3,3)
imshow(img-img_erode);
title('difference')

%CREA LA TUA FUNZIONE my_dilate e provala!

help strel
s = strel('diamond',1);
img_erode2 = imerode(img,s);

isequal(img_erode, img_erode2)


%% PROVA DILATAZIONE

img_dilate = imdilate(img,s);

figure('Name','Dilatation');
subplot(1,3,1)
imshow(img);
title('original')
subplot(1,3,2)
imshow(img_dilate);
title('dilate')
subplot(1,3,3)
imshow(img_dilate-img);
title('difference')


%% Prova  apertura 
img_erode= imerode(img,s);
img_open = imdilate(img_erode,s);

figure('Name','Apertura');
subplot(1,3,1)
imshow(img);
title('original')
subplot(1,3,2)
imshow(img_open);
title('open')
subplot(1,3,3)
imshow(img-img_open);
title('difference')

%% Prova  chiusura
img_dilate = imdilate(img,s);
img_close= imclose(img_dilate,s);


figure('Name','Chiusura');
subplot(1,3,1)
imshow(img);
title('original')
subplot(1,3,2)
imshow(img_close);
title('close')
subplot(1,3,3)
imshow(img_close-img);
title('difference')


%% Application Noise reduction 
img = zeros(256,256);
img(128-50:128+50,128-50:128+50) =200;
img = uint8(img);
figure;
subplot(2,2,1)
imshow(img)
subplot(2,2,2)
imhist(img)
img_noise = double(img);
img_noise = img_noise + randn(256,256)*40;
img_noise(img_noise<0)=0;
img_noise = uint8(img_noise);
subplot(2,2,3)
imshow(img_noise)
subplot(2,2,4)
imhist(img_noise)
img_bw = img_noise>100;
figure;
subplot(1,3,1)
imshow(img_bw)
title('original')


s =strel('square',3)
img_close = imclose(img_bw,s);
subplot(1,3,2)
imshow(img_close)
title('close')

img_open = imopen(img_close,s);
subplot(1,3,3)
imshow(img_open)
title('open')


%% application to grayscale
img = rgb2gray(imread('lena.jpg'));
s =strel('square',11)
img_erode = imerode(img,s);
img_dilate = imdilate(img,s);
img_close= imclose(img,s);
img_open= imopen(img,s);
figure;
subplot(2,2,1)
imshow(img_erode)
title('erosion')
subplot(2,2,2)
imshow(img_dilate)
title('dilatation')
subplot(2,2,3)
imshow(img_open)
title('opening')
subplot(2,2,4)
imshow(img_close)
title('closing')

%% application background removal
img = imread('rice.png');
figure
subplot(2,2,1)
imshow(img)
title('originale')
subplot(2,2,2)
imhist(img)
title('istogramma')
img_bw = img > 150;
subplot(2,2,3)
imshow(img_bw)
title('immagine sogliata')
s = strel('disk',15);
background = imopen(img,s);
figure
subplot(2,2,1)
imshow(img)
title('originale')
subplot(2,2,2)
imshow(background,[])
title('apertura')
subplot(2,2,3)
img_rem = img-background;
imshow(img_rem)
subplot(2,2,4)
imhist(img_rem)
title('background rimosso')
figure;
subplot(1,2,1)
imshow(img_bw)
title('prima')

subplot(1,2,2)
imshow(img_rem>50)
title('dopo')