function result=extract_object(image,threshold)
%function result=extract_object(image,threshold)
%
%   COPYRIGHT:  George D. Tsibidis(1) and Nektarios Tavernarakis(2)
%               (1) Institute of Electronic Structure and Laser 
%               (2) Institute of Molecular Biology and Biotechnology 
%               Foundation for Research and Technology-Hellas (FORTH)
%               January 2007
%
%
%Use: this algoirthm is sed to ext by the user. 
% Inpute :   image: image number
%           threshold: it is passed in the extra_all_objects.m algorithm by
%           the user

A=imread([int2str(image) '.jpg']);

%cd 'DATA'

%figure;imshow(A);

GRAY=rgb2gray(A);

%figure;imshow(GRAY)


cw=im2bw(GRAY,threshold);


BW2=1-cw;

%figure;imshow(BW2)




%figure;imshow(BW2);

perim=bwperim(BW2,8);
%figure;imshow(perim);

label=bwlabel(perim,8);

%figure;imshow(label);
%cfv

bw2=imfill(label,'holes');
label_perim=bwperim(bw2,8);
label_perim=bwlabel(label_perim,8);
bw2=label_perim;
bw2=bwfill(bw2,1,1,8);
bw2=1-bw2;
bw2=imdilate(bw2,ones(6,6)); 
label=bwlabel(bw2,8);

%figure;imshow(label)

A=label;


%figure;imshow(GRAY);


%plot(c,r,'r.')


%%%%%%%%

A=label;
%figure;imshow(A)



label=bwlabel(BW2,8);
KA=[];
for y=1:max(label(:))
    t=find(label==y);
    KA=[KA;[y,length(t)]];
end

p=find(KA(:,2)==max(KA(:,2)));
w=find(label==KA(p,1));%w1=find(~(BW2==KA(p,1)));
BW2=zeros(size(BW2,1),size(BW2,2));
BW2(w)=1;%BW2(w1)=0;


A=BW2;



BW2 = bwmorph(A,'thin',Inf);

%figure;imshow(A);

%%%%  remove small objects for mask and skeleton

  
%figure;imshow(BW2)
%save A:  object mask pixels
file1=['mask_' int2str(image)];


cd ('DATA_SAVED')
save(file1,'A', '-ascii');


%save perimeter


%save skeleton

file2=['skeleton_' int2str(image)];
BW2=im2double(BW2);

%figure;imshow(BW2)

%cbfgbf
save(file2,'BW2', '-ascii');

%plot(x,y,'b.');

cd ..


%toc