%
%
% [B, sorted_edge] = SegPetalFromBackground(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); 
    %sorted_edge = sort_coord_pixel([x, y], 'clockwise', 'discontinuous');
else
    sorted_edge = E;
end
return;
function [binim] = calcPetalBinim(im);
I2 = im(:,:,3) - im(:,:,2);
I2 = I2 + abs(min(I2(:)));
I2 = I2./max(I2(:));
J = imadjust(I2, stretchlim(I2), []);
k = imadjust(im(:,:,1), stretchlim(im(:,:,1)), []);
binim = (k>.5) + (J<.7);
binim = binim > 0;
binim = bwareaopen(binim, 2000);
binim = imclearborder(binim);
binim = imclose(binim, strel('disk', 40));
binim = bwfill(binim,'holes');
binim = imdilate(binim, strel('disk', 2));
return;

