function coeff = initregress(bin_img,deg,rects)
%INITREGRESS Least squares regression on a binary image.
%
%   COEFF = INITREGRESS(BIN_IMG,DEG) returns a vector,
%   COEFF, of length DEG containing the coefficients, [c b] or [c b
%   a], of the baseline of the binarized text contained in BIN_IMG. In
%   the case when DEG=2, the baseline coefficients, COEFF, are from
%   the quadratic model y = ax^2 + bx + c. When DEG=1, the
%   coefficients COEFF are from a linear model y=b*x+c. 
%   The data points for the regression are derived from each of the pixels of
%   value 1 from the binary image, BIN_IMG. This function is designed for
%   BIN_IMG to be binary text. The coefficients in COEFF are with respect to
%   the image coordinate system. 
%
%   See also PARABOLICREGRESS, REGRESS. 


%   This regression is essentially a wrapper function for the function
%   parabolicregress().  parabolicregress() takes the data points from within
%   the image, moves the origin of the data points to the center of the data,
%   calls regress(), then shifts the origin back to the top left corner of the
%   image.

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

% $Id$
 
% 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/>.
    
[row,col] = find(bin_img);% Extract the data points from the image.

if isempty(row) % Nothing in image. Use the rectangle bottoms
  col = [rects(:,1) ; rects(:,1) + rects(:,3)];
  row = [rects(:,2) + rects(:,4) ; ...
         rects(:,2) + rects(:,4)];
end

if deg==2 && length(col)>2
  coeff = parabolicregress(col, row);
else
  coeff = linearregress(col,row);
end

if deg==2 && length(coeff)==2
  coeff(3) = 0;
end
