
function [binim, EDGE] = drosophila_eye_segmentation_top(I)

% E = entropyfile(I);
% S = stdfilt(I, nhood);
% R = rangefilt(I, ones(5));
%Ic = imcrop(I);
Ic = I;
Ic = double(Ic);
Ic = Ic./max(Ic(:));

[r, g, b] = splitRGB(Ic);
nr = r./(r+g+b); nr = nr./max(nr(:));
ng = g./(r+g+b); ng = ng./max(ng(:));
nb = b./(r+g+b); nb = nb./max(nb(:));

d = nr-(ng.*nb);
se = strel('disk', 10);
Io = imopen(d, se);
Iro = imreconstruct(Io, d);
Ird = imdilate(Iro, se);
Ird = Ird./max(Ird(:));
Irda = imadjust(Ird, [.4 1],[0 1]);
[X, counts] = getRange(Irda, 0.4, 0.7);
[val, ind] = min(counts);
binim = Irda>X(ind);

[X, counts] = getRange(Ird, 0.6, 0.8);
[val, ind] = min(counts);
binim = binim | Ird>X(ind);

YIQ = rgb2ntsc(Ic);
YIQ = YIQ(:,:,2); YIQ = YIQ./max(YIQ(:));
[X, counts] = getRange(YIQ, 0.5, 0.8);
[val, ind] = min(counts);
binim = binim | YIQ>X(ind);

binim = bwareaopen(binim, 5000);
binim = imclose(binim, strel('disk', 10));
binim = bwfill(binim, 'holes');
binim = bwareaopen(binim, 5000);
L = bwlabel(binim);
levels = 1:max(L(:));
for i=levels
    b = (L==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
    EDGE{i} = sorted_edge;
end
return;
function [r, g, b] = splitRGB(I)
r = [];
g = [];
b = [];
if size(I,3)~=3
    return;
end
r = I(:,:,1);
g = I(:,:,2);
b = I(:,:,3);
return;

function [X, counts] = getRange(I, minr, maxr)
[counts, X] = imhist(I);
ind = intersect(find(X>minr), find(X<maxr));
X = X(ind);
counts = counts(ind);

