function model = rgbdclassifier(model)

% train classifier 

% train linear svm on all images
disp('train binary classifier ... ...');
option = '-s 2 -c 10 -e 0.001 -B 1';
%option = '-s 2 -c 10';
hog = sparse([model.cropfea'; model.negfea']);
label = [ones(size(model.cropfea,2),1); -ones(size(model.negfea,2),1)];
tic
svmmodel = train(label,hog,option);
toc
[predictlabel, accuracy, decvalues] = predict(label, hog, svmmodel);
clear label;
model.classifier = svmmodel;

% get directories of background images
bgpath = getdatapath(model.datadir.bgdir,'_clean_depth.png');
objbg = getobjbg(model);
start = length(bgpath);
it = 0; cnt = -1;
for i = 1:length(objbg)
    objbgpath = getdatapath([model.datadir.objdir objbg{i} '/'], '_clean_depth.png');
    for j = 1:length(objbgpath)
        cnt=cnt+1;
        if mod(cnt,10) ~= 0
           continue;
        end
        parts = regexp(objbgpath{j},'\/','split');
        parts = regexp(parts{end},'_','split');
        cat = [];
        for p=1:(length(parts)-5)
           cat = [cat parts{p} '_'];
        end
        cat = cat(1:end-1);
        inst = str2num(parts{end-4});
        if ~strcmp(model.category,cat) || model.instance > 0 && model.instance ~= inst
           it = it + 1;
           bgpath{start+it} = objbgpath{j};
        end
    end
end

maxitnum = 5; % maximum iteration
numim = 500; % number of images per iteration
for i = 1:maxitnum

    % minning hard examples
    perm = randperm(length(bgpath));
    hardneg = zeros(size(hog,2),numim);
    for s = 1:numim
        im = imread([bgpath{perm(s)}(1:end-16) '.png']);
        depth = imread(bgpath{perm(s)});
        [imcrop, depthcrop, bbox] = rgbdhardneg(im, depth, model);
        negfea = cropfea(imcrop, depthcrop, bbox.scale, model);
        hardneg(:,s) = negfea(:);
        disp(['Score of hard negative is ' num2str(bbox.score)]);
        if mod(s, 50) == 0
           disp(['Number of images is ' num2str(s)])
        end
    end

    % retrain classifier
    model.negfea = [model.negfea hardneg];
    clear hog;
    hog = sparse([model.cropfea'; model.negfea']);
    label = [ones(size(model.cropfea,2),1); -ones(size(model.negfea,2),1)];
    disp('train binary classifier ... ...');
    svmmodel = train(label,hog,option);
    [predictlabel, accuracy, decvalues] = predict(label, hog, svmmodel);
    clear label;
    model.classifier = svmmodel;
    disp(['Current iteration is ' num2str(i)]);
end

function objbg = getobjbg(model)
% get names of background objects

objname = bodir(model.datadir.objdir);
it  = 0;
for i = 1:length(objname)
    it = it + 1;
    if false %strcmp(objname(i).name,model.category)
       it = it -1;
    else
       objbg{it} = objname(i).name;
    end
end


