function pruned_img = prune(bin_img, coeff)
%PRUNE Removes connected components components that do not intersect a curve.
%   PRUNED_IMG = PRUNE(BIN_IMG,PRIOR_COEFFS) where BIN_IMG is a binary image
%   and PRIOR_COEFFS is the coefficients [c b a] of a curve using the
%   quadratic model ax^2 + bx + c. It returns a binary image, PRUNED_IMG,
%   containing only the connected components from BIN_IMG that intersect a
%   curve specified by PRIOR_COEFFS. 
%
%   This regression assumes that the data provided is part of a collinear set
%   of rectangles. Contrary to previos versions, it will prune all points in
%   in the image regardless of the information provided in RECTS.
%
%   Example Usage:
%   
%   bin_img = grayImage>128;
%   coeff = initregress(bin_img);
%   pruned_img = (bin_img,coeff);
%
%   See also PRUNEREGRESS, INITREGRESS.

% Copyright (c) 2011
% Jerod Weinman
% jerod@acm.org

% $Id: prune.m 595 2014-10-24 18:15:54Z weinman $
 
% Jerod Weinman, Zach Butler, Dugan Knoll, Alexander Turner, Yirong Jing
% jerod@acm.org
% Copyright 2011, 2012, 2013, 2014
 
%    This file is part of PIONEER WordNorm.
%
%    PIONEER WordNorm 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.
%
%    PIONEER WordNorm 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 PIONEER WordNorm.  If not, see <http://www.gnu.org/licenses/>.

% Run a connected components analysis
CC = bwconncomp(bin_img);

sz = size(bin_img);

curve = false(sz);
xcurve = 1:sz(2);
ycurve = round(xcurve.^2*coeff(3) + xcurve*coeff(2) + coeff(1));
ycurve = max(min(ycurve,sz(1)),1);
curve(sub2ind(sz,ycurve,xcurve)) = 1; % An image with the curve = 1

pruned_img = false(sz);
largestComp = max(cellfun(@length,CC.PixelIdxList));
currentComp = logical(sparse([],[],[],sz(1),sz(2),largestComp));

for i=1:CC.NumObjects
    currentComp(CC.PixelIdxList{i}) = 1; % Set component to one
    if(anyv(currentComp & curve))% If it intersects the curve
        pruned_img(CC.PixelIdxList{i}) = 1; % add it to the pruned image
    end
    currentComp(:) = 0; % Erase Component
end
