%
%
% [B, sorted_edge] = SegmentPetalFromBackground(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.
function [B, sorted_edge] = SegPetalFromBackgound(I)
I = double(I);
I = I./max(I(:));
B = calcPetalBinim(I);
E = edge(double(B));
[x, y] = find(E == 1);
if length(x)>0
    sorted_edge = image_sort(x,y); 
else
    sorted_edge = E;
end
return;


function [binim] = calcPetalBinim(I);
y =rgb2ycbcr(I);
y2 = y(:,:,2);
y2 = imadjust(y2, stretchlim(y2),[]);
y2 = adapthisteq(y2);
cform = makecform('srgb2lab');
labI = applycform(I,cform);
binim = (y2<.1) + (labI(:,:,2)>1);
binim = bwfill(binim, 'holes');
binim = bwareaopen(binim, 10000);
binim = imclearborder(binim);
binim = imdilate(binim, strel('disk', 5));