% Dima Damen
% Created Aug 2007

% This is same as findBestTransformationMatch, but it does not loop through
% Tx and Ty. It on the contrary uses the correlation to find the best match
% and the best TA for each RA and SA.

% updated version of findBestTransformationMatchConv [this version was
% added to try different metrics like weighting with something]

function [TA, RA, SA, diffImg] = findBestTransformationMatchConv_f (beginningFileName, direction, personWeight, params)

   % parameters
   minR = params.Results.minR;
   maxR = params.Results.maxR;
   minS = params.Results.minS;
   maxS = params.Results.maxS;
   RJump = params.Results.RJump;
   SJump = params.Results.SJump;
   writeIntermediateResults = params.Results.writeIntermediateResults;
   personHeight = params.Results.personHeight;
   
   % Scale the person according to size.
      
   minAccumm = Inf;
   sAccumm = 1;
   rAccumm = 0;
   tXAccumm = 0;
   tYAccumm = 0;
   
   for i = 1:personHeight
      heightWeighting(i,1) = 2*personHeight - i;
   end;
   
   %get through
   for S=minS:SJump:maxS
       for R=minR:RJump:maxR
           if (R < 0)
               templateRotated = imread (strcat ('TemplateModels/d', num2str(direction), 'RotM', num2str (abs(R)), 'scale', num2str(S*100), '.jpg'));
           else
               templateRotated = imread (strcat ('TemplateModels/d', num2str(direction), 'Rot', num2str (R), 'scale', num2str(S*100), '.jpg'));
           end;
           templateRotated = double(templateRotated)/255;
           for tX = -10:1:10
               for tY = -10:1:10
                   cImg = circshift (templateRotated, [-tX, -tY]);
                   diffImg = abs (cImg - personWeight);
                   diffImgHeight = sum (diffImg,2);
                   accumm = sum (diffImgHeight .* heightWeighting);
                   if (accumm < minAccumm)
                     minAccumm = accumm;
                     sAccumm = S;
                     rAccumm = R;
                     tXAccumm = -tX;
                     tYAccumm = -tY;
                     tempAcc = cImg;
                   end;
               end;
           end;
       end;
   end;

   if (writeIntermediateResults == true)
       imwrite (tempAcc, strcat (beginningFileName, 'templateBestMatched.jpg'));
       b1 = getBoundaryOnly (im2bw (tempAcc, 0.1));
       b2 = getBoundaryOnly (im2bw (personWeight, 0.1));
       imwrite (b1 | b2, strcat (beginningFileName, 'boundaryMatch.jpg'));
   end;
   %notice that it only generates the pixels that are in the person but not
   %the template (not the other way round.
   % maybe a measure of the other way round could be used to evaluate the
   % method.
   diffImg = personWeight - tempAcc;
   TA = [tXAccumm; tYAccumm];
   RA = rAccumm;
   SA = sAccumm;
end