%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% AdaDGS for video background substraction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%  J. Huang, et al., ”Learning with Dynamic Group Sparsity”, ICCV 2009. 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clc;clear; close all;
load VideoData;
[H, W, D, T]=size(VideoData);


m=H*W; Tau=120; 
% load FgDGS;
FgDGS=zeros(H, 4*W, D, T-Tau);

A=VideoData(:,:,:,1:Tau);
A=reshape(A, [m, D, Tau]);
A_mask=logical(zeros(H*W, Tau));

bg=zeros(H, W, D);
bg(:,:,:)=105*ones(H, W, 3);


%%%% These two sparsity numbers are tuning parameters for the balance
%%%% between the accuracy and the speed
option.kxmax=4;  %%%% The max sparsity number for background images
option.kemax=1000; %%%% The max sparsity number for forground images
in=1;
% figure;
for i=Tau+1:T,
    in=i-Tau;
    fprintf('i=%d\n', i);
    img(:,:,:)=VideoData(:,:,:,i);
    %%%%%%%%%%
    option.method='AdaDGS';
    [imout1, fg1, mask]=SparseBG_Option(A, A_mask, img, H, W, option);
    fprintf('end of method \n');
    ma=repmat(mask, [1 1 D]);
    FgDGS(:,:,:,in)=[img, fg1,imout1, mask] ;
     
    
    
    imshow(uint8([img, fg1+bg]), []);
    title(num2str(i));
    pause(0.05);
%     in=in+1;
end
save FgDGS FgDGS;
