% By Ramón Morneo jiménez
% natafresa@gmail.com
% Computational Intelligence Group
% http://www.ehu.es/ccwintco


% this function find the bigger and more conected red region in a image

% I :           RGB input image
% sf2thr:       threshold for binarization of SF2 transform [.25 -.5]
% recTorelance: size of the window. is a multiplier [2-3]

% Perim:        Bi-dimensional vecor with perimatral pixels
% Centroid:     Mass centroid


function [Perim, Centroid] = Segmentation2(I, sf2thr, recTolerance); 

sf2 = SF2(I); % specularfree transform

R = sf2(:,:,1); % select the red channel

Rbw = im2bw(R,sf2thr); % binarize

[L,n] = bwlabel(Rbw);  % labeling

%% look for the bigger region
rg =0;
tmax = 0;
for i =1:n
    members = find(L == i);

    tm = size(members,1);
    if tm > tmax
        tmax = tm;
        rg = i;
    end
end

[f,c] = find(L == rg);

centroid = mean([f,c]); % of SF2, used for crop a region
h = max(f) - min(f);
w = max(c) - min(c);
l = max(h,w);
l = l* recTolerance; 
rec = [(centroid(2) - l)  (centroid(1) -l)   l*2  l*2];

% crop the ball region
I2 = imcrop(I,rec);

sf3 = SF3(I2); % other specular free transform


R3 = sf3(:,:,1); % select the red channel
thr = double(max(max(R3)))/255;
R3  = im2bw(R3,thr/2); % binarize

% remove  noise
R3 = imerode(R3, ones(5,5));

[L,n] = bwlabel(R3); 

% look for the bigger region
rg =0;
tmax = 0;
for i =1:n
    members = find(L == i);
    tm = size(members,1);
    if tm > tmax
        tmax = tm;
        rg = i;
    end
end

s = find(L == rg);
BW2 = zeros(size(L,1),size(L,2));
BW2(s) =1;

BW2 = imdilate(BW2,ones(5,5));

[f,c] = find(BW2 == 1);

% mass centroid
Centroid = mean([f,c]);
p = bwperim(BW2);

[fl,cl]= find(p == 1);

% scale to the original image size
fl = fl + rec(2); 
cl = cl + rec(1);

fl = round(fl);
cl = round(cl);

% perimeter
Perim = [fl cl];

% visual supervision
figure(1)
subplot(1,3,1);
imshow(Rbw);
title ('SF2 red band');
subplot(1,3,2);
imshow(sf3);
title ('SF3 transform');
subplot(1,3,3);
imshow(BW2);
title('Selected region');

pause(1);
