% Segmentation

% The function graythresh implements the Otsu algorithm for finding
% the optimal threshold.


I  = imread('cube.jpg');

I2 = rgb2hsv(I);

H = I2(:,:,1); % hue
S = I2(:,:,2); % saturation
V = I2(:,:,3); % intensity

figure;
subplot(2,2,1);
imshow(I);
subplot(2,2,2);
imshow(H);
subplot(2,2,3);
imshow(S);
subplot(2,2,4);
imshow(V);

% segmentation of the green faces
M = (S > .4 & abs(H-.4)<.05);
figure;
imshow(M);
title('green faces');
figure;
imshow(imopen(M, strel('disk',2)));
title('green faces after opening');

% segmentation of the red faces
H2 = H+.5;
ind = find(H2>1);
H2(ind) = H2(ind)-1;
M = (S > .4 & abs(H2-.5)<.033);
figure;
imshow(M);
title('red faces');
figure;
imshow(imopen(M, strel('disk',2)));
title('red faces after opening');



t = H;
%t = imfilter(t, fspecial('disk', 18));
%t = imfilter(t, fspecial('gaussian', 20, 3));
max(t(:)), min(t(:)),
t = 1-t;
t(find(S<=.4))=-Inf;
figure; imshow(t);
L = watershed(t);
rgb = label2rgb(L,'jet',[.5 .5 .5]);
figure, imshow(rgb,'InitialMagnification','fit')
title('Watershed transform of H')
