% demo saliency maps for bicycle, car and person
% using pre-trained saliency models from graz02 and voc2007 datasets.
% You can set test = 'graz' or 'voc' to select the database 
% and set category = 'car', 'bike' or 'person' to select the model
% The test image for voc models is named by 'image.jpg'
% while the test images for graz models are named by their categories, 
% such as 'car.bmp'
clear all; clc;
addpath(genpath('BP'));
addpath('sparse-coding');
addpath('SIFT');

test = 'graz'; % or 'voc'
category = 'car'; % 'bike' or 'person'

switch test
    case 'graz' % test three saliency maps with graz02 model
        % parameters for sift feature extraction
        pars.gridSpacing = 16;
        pars.patchSize = 64;
        pars.numOBins = 16;
        pars.numSBins = 4;
        pars.maxImSize = 640;
        I = imread(sprintf('%s.bmp',category));
        load(sprintf('model_%s_graz.mat',category));
    case 'voc' % test three saliency maps with voc2007 model
        % parameters for sift feature extraction
        pars.gridSpacing = 16;
        pars.patchSize = 64;
        pars.numOBins = 8;
        pars.numSBins = 4;
        pars.maxImSize = 500;
        I = imread('image.jpg');
        load(sprintf('model_%s_voc.mat',category));
    otherwise
        error('Unknown.');
end

% parameters for saliency model
pars.numBases = size(model.D,2);
pars.gamma = 1e-3;
pars.lambda = 0.15;

% extract sift features
fprintf('Extract sift features...'); tic;
feaSet = extract_sift(I,pars);
fprintf('%f seconds.\n',toc);

% build the graph
fprintf('Build the graph on sift grid...'); tic;
rows = length(unique(feaSet.y));
cols = length(unique(feaSet.x));
graph = StarEdge_MakeEdgeNums_Lattice2(rows, cols);
[aff, dist] = BuildGraph(feaSet.feaArr, rows, cols);
graph.A = aff; graph.D = dist; graph.rows = rows; graph.cols = cols;
fprintf('%f seconds.\n',toc);

% sparse coding
fprintf('Sparse coding...'); tic;
S = L1QP_FeatureSign_Set(feaSet.feaArr, model.D, pars.gamma, pars.lambda);
fprintf('%f seconds.\n',toc);

% saliency maps
fprintf('Infer the saliency map...'); tic;
[label_hat, belief] = crf_infer_lbp(model, S, graph, []);
fprintf('%f seconds.\n',toc);

% display the results
saliency = reshape(belief(:,1),rows,cols);
saliency = imresize(saliency,[feaSet.height,feaSet.width]);
saliency(saliency < 0) = 0;
S = heatmap_overlay(I, saliency);
imshow(S,[]); title(sprintf('%s saliency map',category));
% imwrite(uint8(255*S),sprintf('%s_saliency.png',category), 'png');



