% SUM-MAX MAPS FOR TEMPLATE MATCHING INFERENCE -- piecewise version
%% load in learned template, set parameter values
clear; close all; 
load 'learnedTemplate'; % load in the learned template
mex Csigmoid.c; % sigmoid transformation
mex CgetMAX1.c;   % getting MAX1 maps without getting track maps
mex CgetSUM2.c;   % template matching inference
%% load in test image, generate multiple resolutions
numResolution = 10;  % total number of resolutions to search 
allSizex = zeros(1, numResolution); allSizey = zeros(1, numResolution); 
tmpIm = imread('test.jpg'); 
if size(tmpIm,3) == 3
     tmpIm = rgb2gray(tmpIm);
end
J0 = single(tmpIm); 
MAX1maps = cell(numResolution, 1); 
SUM2map = cell(1, numResolution); 
for(img=1:numResolution)
    J{img} = imresize(J0, .50+(img-1)*.03, 'nearest');  % scaled images
    [sizex, sizey] = size(J{img}); 
    allSizex(img) = sizex; allSizey(img) = sizey; % sizes of images at multiple resolutions
    sizexSubsample = floor(sizex/subsample); sizeySubsample = floor(sizey/subsample); 
    SUM2map{img} = single(zeros(sizexSubsample, sizeySubsample));  % log-likelihood score maps for testing images
    MAX1map{img} = single(zeros(sizexSubsample, sizeySubsample)); 
    translatedTemplate{img} = single(zeros(sizex, sizey));  % symbolic sketch on testing image
end
MAX2score = single(zeros(1, numResolution));  % maximum log-likelihood score at each resolution
%% compute SUM1 maps for all resolutions
disp(['start filtering']); tic
SUM1map = ApplyFilter1(J, dogFilter);  % filter testing image at all resolutions
disp(['filtering time: ' num2str(toc) ' seconds']);
Csigmoid(numResolution, allSizex, allSizey, saturation, SUM1map);
%% compute MAX1 maps for all resolutions
disp(['start maxing']); tic
CgetMAX1(numResolution, allSizex, allSizey, locationShiftLimit, subsample, ...
         SUM1map, MAX1map); 
disp(['maxing time: ' num2str(toc) ' seconds']);
%% detect the object and superpose template
disp(['start finding']); tic
CgetSUM2(numResolution, allSizex, allSizey, ...
      locationShiftLimit, subsample, ...
      halfFilterSize, SUM1map, MAX1map, dogSymbol, ...
      numElement, selectedx, selectedy, selectedlambda, selectedLogZ, ...
      SUM2map, translatedTemplate, MAX2score);
disp(['mex-C finding time: ' num2str(toc) ' seconds']);
%% display results
[maxOverResolution ind] = max(MAX2score);   % most likely resolution
Outepsgif(rgb2gray(imread('test.jpg')), 'ex2_1_original'); % original image
Outepsgif(J{ind}+translatedTemplate{ind}*100, 'ex2_1_sketch'); % overlaid sketch at optimal resolution  
figure('Position', [1 1 1024 768]); 
mesh(double(SUM2map{ind})); % log-likelihood score map at optimal resolution
saveas(gcf, 'ex2_1_S2','eps');
figure; plot(MAX2score); 
title('MAX2 score vs scale'); xlabel('scale'); ylabel('MAX2');
saveas(gcf, 'ex2_1_M2','eps');




