%
%
% [B, sorted_edge] = SegLeafFromBackground(I);
%
% Input params: 
%            I - the input image
% Output params:
%            B - the binary image
%            sorted_edge - the edge of the objects in B, ordered.
%
%  Dr. A. I. Hanna 2005. (and J.Andrew Bangham 2005)
function [B, sorted_edge] = Segment_Petals_BlackBackgound(I)
global fig1 % smuggled in from AutomaticPlacement
I = double(I);
I = I./max(I(:));
B = calcPetalBlackBackgroundBinim(I);
%E = edge(double(B));
E = bwperim(B); % this ensures a closed loop %edge(double(B));
[x, y] = find(E == 1);
if length(x)>0
    sorted_edge = image_sort(x,y); 
    %sorted_edge = sort_coord_pixel([x, y], 'clockwise', 'discontinuous');
else
    sorted_edge = E;
end
%fig=figure(1);
if ishandle(fig1)
    imshow(I);
    hold on
    plot(sorted_edge(:,2),sorted_edge(:,1),'-g');
    hold off
    %disp('press a key')
    drawnow
    pause(2)
end
%close(fig); 
return;

function [binim] = calcPetalBlackBackgroundBinim(im,verbose)
if nargin<2
    verbose=0;
end
p = im(:,:,1);
p = p./max(p(:));
area=prod(size(p));
ps=double(sieve2d(uint8(255*p),floor(area/20)))/255;
ps = imadjust(ps, stretchlim(ps), []);
N=20; % look for the most stable choice of threshold
% i.e. the perimeter should not change much with threshold
for i=1:N
    t(i)=i/N;
    tps=ps>t(i);
    e=bwperim(tps); %edge(tps);
    le(i)=sum(e(:));
end
med=median(le); % and find the index in the middle
ind=find(le>(med-med/10) & le<(med+med/10)); % within + - 10 %
med_ind=median(ind);
binim=ps>t(floor(med_ind));
if verbose
    plot(t,le);
    hold on
    plot(t(ind),le(ind),'*');
    plot(t(med_ind),le(med_ind),'Or');
    hold off
    %bwperim
end

% p = imadjust(p, stretchlim(p), []);
% binim = p > .3;
% binim = bwareaopen(binim, 2000);
% binim = imclearborder(binim);
% binim = bwfill(binim,'holes');
% binim = imdilate(binim, strel('disk',2));
% return;

