clear all; close all; 
disp(['===============> Getting parameters, mex-c code, and training images']);
mkdir('working'); % working directory to store .mat files. 
mkdir('output'); % directory that contains output from the code. 
%% mex-C code
mex Chistogram.c;   % pool histogram from negative images
mex CsharedSketch.c; % learning by shared sketch algorithm
mex Csigmoid.c; % sigmoid transformation
mex CgetMAX1track.c; % get MAX1 maps and track maps
mex Caverage.c; % sigmoid transformation
mex CgetSUM2.c;   % template matching inference
mex CgetMAX2.c;   % template matching inference
mex CgetBack.c;   % template matching inference
mex CgetBackInhibit.c;   % template matching with inhibition 
mex ClocalNormalizeDouble.c; % local normalization of type double
mex ClocalNormalize.c; % local normalization
mex Ccopy.c; % copy around detect location with sigmoid transformation to prepare for learning
mex Ccopy0.c % simple copy without sigmoid transformation
%% parameters for Gabor filters
numScale = 1; 
scales = [1.]; % scales of Gabor wavelets 
numOrient = 15;  % number of orientations
saturation = 6.; % saturation level for sigmoid transformation
%% parameters for exponential model
binSize = .2;  % binsize for computing histogram of q()
numStoredPoint = 50; % number of stored lambda values
spacing = .1; % spacing between two adjacent points
%% parameters for normalization
localOrNot = 1; % if we use local normalization or not. If not, set it to -1 
localHalfx1 = 20; localHalfy1 = 20; % the half range for local normalization, has to be quite large
windowNormalizeOrNot = -1; % whether normalize within the scanning window in detection 
if (localOrNot>0)
    windowNormalizeOrNot = -1; 
end % if we use local normalization, we should not use window normalization in detection
thresholdFactor = .01;  % divide the response by max(average, maxAverage*thresholdFactor)
%% parameters for active basis
epsilon = .1; % allowed correlation between selected Gabors 
subsample = 1; % subsample in computing MAX1 maps   
locationShiftLimit = 3; % shift in normal direction = locationShiftLimit*subsample pixels
orientShiftLimit = 1; % shift in orientation
numElement1 = 40; % number of Gabors in active basis at the first scale
%% parameters for detection
resizeFactor = .6; % resize the input images 
inhibitFind = -1;  % whether to apply inhibition after detection for re-computing MAX2 score
resolutionGap = .1; % gap between consecutive resolutions in detection
numExtend = 5; % number of gaps extended both below and above zero
numResolution = numExtend*2 + 1;  % number of resolutions to search for in detection stage
originalResolution = numExtend + 1; % original resolution is the one at which the imresize factor = 1
allResolution = (-numExtend : numExtend)*resolutionGap + 1.; 
%% read in positive images
imageFolder = 'positiveImage'; % folder of training images  
imageName = dir([imageFolder '/*.jpg']);
numImage = size(imageName, 1); % number of training images 
Ioriginal = cell(1, numImage); 
for (img = 1 : numImage)
    tmpIm = imread([imageFolder '/' imageName(img).name]); 
    if size(tmpIm,3) == 3
        tmpIm = rgb2gray(tmpIm);
    end
    Ioriginal{img} = imresize(single(tmpIm), resizeFactor, 'nearest');
    J0 = Ioriginal{img}; 
    J = cell(1, numResolution); 
    for(r=1:numResolution)
       J{r} = imresize(J0, allResolution(r), 'nearest');  % scaled images
    end
    multipleResolutionImageName = ['working/multipleResolutionImage' num2str(img)]; 
    save(multipleResolutionImageName, 'J');  
end
%% parameters for initialization and iteration
useWholeImageOrNot = 1; % whether use the whole image of I{start} or use a portion of it to initialize learning
starting = 1; % initilize by single image learning from I{starting}
startx = 4; endx = 139; % initialize by learning from a given patch
starty = 42; endy = 181; 
numIt = 5; 
tmp = Ioriginal{starting}; 
if (useWholeImageOrNot>0)  % initialize from the whole image 
    startx = 1; starty = 1; 
    [endx endy] = size(tmp); 
end
I0 = tmp(startx:endx, starty:endy); % initialize the template from the starting image 
[sizeTemplatex sizeTemplatey] = size(I0); % size of template
halfTemplatex = floor(sizeTemplatex/2.); halfTemplatey = floor(sizeTemplatey/2.); % half size
sizeTemplatexSubsample = floor(sizeTemplatex/subsample); % subsample size
sizeTemplateySubsample = floor(sizeTemplatey/subsample); 
%% spaces for learning
for (s = 1:numScale)
SUM1mapLearn = cell(numImage, numOrient); % data structures for learning
MAX1mapLearn = cell(numImage, numOrient); 
trackMapLearn = cell(numImage, numOrient);
for (img = 1:numImage) 
    for (orient = 1:numOrient)
       SUM1mapLearn{img, orient} = single(zeros(sizeTemplatex, sizeTemplatey)); 
       MAX1mapLearn{img, orient} = single(zeros(sizeTemplatexSubsample, sizeTemplateySubsample)); 
       trackMapLearn{img, orient} = single(zeros(sizeTemplatexSubsample, sizeTemplateySubsample)); 
    end
end
%% variables for learning
numElement = floor(numElement1*scales(1)/scales(s)); 
selectedOrient = zeros(1, numElement);  % orientation and location of selected Gabors
selectedx = zeros(1, numElement); 
selectedy = zeros(1, numElement); 
selectedlambda = zeros(1, numElement); % weighting parameter for scoring template matching
selectedLogZ = zeros(1, numElement); % normalizing constant
commonTemplate = single(zeros(sizeTemplatex, sizeTemplatey)); % template of active basis 
deformedTemplate = cell(1, numImage); % templates for training images 
for (img = 1 : numImage)
    deformedTemplate{img} = single(zeros(sizeTemplatex, sizeTemplatey));  
end
allSizex0 = sizeTemplatex + zeros(1, numImage); allSizey0 = sizeTemplatey + zeros(1, numImage); 
learningSpaceName = ['working/learningSpace' num2str(s)]; 
save(learningSpaceName, 'SUM1mapLearn', 'MAX1mapLearn', 'trackMapLearn'); 
learningSpaceMoreName = ['working/learningSpaceMore' num2str(s)]; 
save(learningSpaceMoreName, 'commonTemplate', 'deformedTemplate'); 
learnedTemplateName = ['working/learnedTemplate' num2str(s)]; 
save(learnedTemplateName, 'numElement', 'selectedOrient', 'selectedx', 'selectedy', 'selectedlambda', 'selectedLogZ');             
end
%% Output options
showMAX2SUM2 = 1; 
showOriginal = 1; 


