function [w, orig, im, bim, S2] = sandra_leaf_sectors(I, w)	
	I = double(I);
	I = I./max(I(:));
	orig = I;
	d = orig(:,:,1) -orig(:,:,3);
	bim = d> .15;
    waitbar(1/10, w);
	bim = bwfill(bim, 'holes');
	bim = imclearborder(bim);
	bim = bwareaopen(bim, 50000);
    bim = imclose(bim, strel('disk', 15));
    bim = imdilate(bim, strel('disk', 5));
    
	L = bwlabel(bim);
	stats = regionprops(L, 'BoundingBox');
	BB = round(stats.BoundingBox);
	% Extract the leaf from the full RGB image
	I2(:,:,1) = I(:,:,1).*bim;
	I2(:,:,2) = I(:,:,2).*bim;
	I2(:,:,3) = I(:,:,3).*bim;
	I3(:,:,1) = imcrop(I2(:,:,1), BB);
	I3(:,:,2) = imcrop(I2(:,:,2), BB);
	I3(:,:,3) = imcrop(I2(:,:,3), BB);
    waitbar(2/10, w);
	I2 = I3;
	H = fspecial('gaussian', 5, 5);
	A = normalise(I2(:,:,1) - I2(:,:,2).^5);
	A2 = normalise(I2(:,:,1) - I2(:,:,2));
	thehist = load('leafhist');
	thehist = thehist.h;
    waitbar(3/10, w);
	A2 = histeq(A2, thehist);
	A = conv2(A, H, 'same');
	A2 = conv2(A2, H, 'same');
    waitbar(4/10, w);
	h = imhist(A);
	for i=length(h):-1:1
		if (h(i) >= 300)
			thr = i/256;
			break
		end
	end
    waitbar(5/10, w);
	if(i==1)
		thr = 0.8;
	end
	S = A>thr;
	p = S.*A;
	q = imadjust(p, [.5 1], [], 1);
	S = (q> .4) + (A> .8) + (A2>.6);
    waitbar(6/10, w);
	v = normalise(A.*A2);
	h = imhist(v);
	lh = log(h)./max(log(h));
	for i=length(lh):-1:1
		if(lh(i) >= 0.46)
			thr = i/256;
			break
		end
	end
    waitbar(7/10, w);
	v = A2.^3;
	h = imhist(v);
	h = h./max(h);
	dh = diff(h);
	for i=length(dh):-1:1
		if(dh(i) < -1.403e-3)
			thr = i/256;
			break;
		end
	end
	
	%S = (S>0).* (normalise(A.*A2)>thr);
	S = (normalise(A.*A2)>thr);
    waitbar(8/10, w);
	S = normalise((histeq(A2).*histeq(A)))>.9;
	v = normalise(A.*A2);
	S = A2.^3 > thr;
	S = (A2.^3>.5) & (imextendedmax(v, .2));
	S = (A2>.7) & (I2(:,:,2) < .7);
	S = imclose(S, strel('disk', 5));
    waitbar(9/10, w);
	S = bwfill(S, 'holes');
	S2 = zeros(size(orig(:,:,1)));	
	S2(BB(2):BB(2) + BB(4), BB(1):BB(1)+BB(3)) = S;
    
	waitbar(10/10, w);
    im = I;
return;

% NORMALISE - Rescale image values to 0-1.
%
% Function to rescale elements of a matrix
% so that the minimum value is 0 and the 
% maximum value is 1.
%
% Usage: rescaled = normalise(im)
%

% Peter Kovesi
function n = normalise(a)

    if ndims(a)==3           % Assume colour image 
	hsv = rgb2hsv(a);
        v = hsv(:,:,3);
        v = v - min(min(v)); % Just normalise value component
        v = v/max(max(v));
        hsv(:,:,3) = v;
        n = hsv2rgb(hsv);
    else                     % Assume 1D or 2D greyscale values
	if ~isa(a,'double'), a = double(a); end
	n = a - min(min(a));
	n = n/max(max(n));
    end
    