function [brightFraction particleImageOut] = ...
    computeBrightFraction(image, cartX, cartY, sizeFraction, threshold)
% compute brightness fraction for particle
%
%  Syntax: brightFraction = computeBrightFraction(image, cartX, cartY)
%
% This function takes the original image together with a boundary curve
%   structure (bnd) to do the following. First, extract the sub image of
%   the particle. Secondly compute a circular filter that selects about 70%
%   of the center area. Thirdly, apply a threshold to this part and
%   calculate the fraction of bright pixels by total pixels of the cneter
%   area.
%
% If required a modified image is returned in a second output argument.
%   This image leaves the center area as it was provided and inverts the
%   outer area.
%
% The brightnes fraction is used to identify bubbles. Therefore, the
%   roundness value is also required.
%
% See also: obtainBnd

% The elk-library: convex geometry applied to crystallization modeling.
%   Copyright (C) 2012 Alexander Reinhold
%
% This program is free software: you can redistribute it and/or modify it 
%   under the terms of the GNU General Public License as published by the 
%   Free Software Foundation, either version 3 of the License, or (at your 
%   option) any later version.
%
% This program is distributed in the hope that it will be useful, but 
%   WITHOUT ANY WARRANTY; without even the implied warranty of 
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
%   General Public License for more details.
%
% You should have received a copy of the GNU General Public License along 
%   with this program.  If not, see <http://www.gnu.org/licenses/>

% get particle image
particleImage = image(max(cartY):-1:min(cartY), ...
                      min(cartX):max(cartX));

% size and coordinates
xSize = size(particleImage, 1);
ySize = size(particleImage, 2);
xCenter = round(xSize/2);
yCenter = round(ySize/2);

% construct filter
[Y X] = meshgrid(1:ySize, 1:xSize);
filterImage = sqrt((X-xCenter).^2 + (Y-yCenter).^2) < ...
              0.5*sizeFraction*min([xSize ySize]);
imageFiltered = (particleImage > threshold) & filterImage;

% apply filter to brightness fraction
brightFraction  = sum(imageFiltered(:)) / sum(filterImage(:));

% return image if required
if nargout == 2
    particleImageOut = ...
    uint8(particleImage) .* uint8(filterImage) + ...
    uint8(255 - particleImage) .* uint8(~filterImage);
end


