function [bim, sorted_edge] = ulises_vein(I)
% function [w, orig, im, bim, S2] = segment_arabidopsis_green_on_white_sandra(I, w)
% 
% A function that takes an image and a handle to a waitbar and returns the
% waitbar handle, the original image, the image with the sectors overlayed,
% the binary image of the organ, and the binary image of the sectors.
%
% This script has been written for Sandra Bensmihen (JIC) for use with the 
% expression of a cell autonomous marker (anthocyanin) in Antirrhinum
% majus leaves.
%
% Dr. A. I. Hanna (2006)

if nargin<1
    error('Must at least give an image');
end

% Make sure that the image is in a descend format.
I = double(I);
I = I./max(I(:));

% Calculate the binary image
bim = calcBinIm(I);

sorted_edge = bwboundaries(bim);
if isempty(sorted_edge)
    sorted_edge = [];
else
    sorted_edge = sorted_edge{1};
end
return;
%%%%%
%
%
%%%%%
function bim = calcBinIm(orig)
r = orig(:,:,1);
[counts, X] = imhist(r);
ind = intersect(find(X>0.05), find(X<.6));
X = X(ind);
counts = counts(ind);
[val, ind] = min(counts);
if isempty(ind)
    thr = 0.1;
else
    thr = X(ind(1));
end
bim = r>thr;
bim = imclearborder(bim);
bim = bwareaopen(bim, 1000);
bim = imclose(bim, strel('disk', 2));
bim = bwfill(logical(bim), 'holes');