% Demo code for the paper
% Stochastic approximation for background modelling
% Computer Vision and Image Understanding, DOI: 10.1016/j.cviu.2011.01.007
% Coded by R.M.Luque and Ezequiel Lopez-Rubio -- February 2011 

clear all

% Load the video to analyse
disp('Loading the input sequence...');
sName='video.avi';
fInfo=aviinfo(sName);
d=aviread(sName,1);

% Create the structures of the stochastic approximation model
disp('Creating the structures of the stochastic approximation model...');
model = createAEModel(d.cdata);
model.LastFrame = fInfo.NumFrames;

% Allocate scape for the set of images to initialise the model 
images = zeros(size(d.cdata,1),size(d.cdata,2),size(d.cdata,3),model.NumPatterns);
images(:,:,:,1) = uint8(d.cdata);

% Store the frames
for i=2:model.NumPatterns
    d=aviread(sName,i);
    images(:,:,:,i) = uint8(d.cdata);
end
images = uint8(images);

disp('Initialising the model...');
% Initialize the model using a set of frames
model = initializeAE_MEX(model,images); 

% Estimate the noise of the sequence
model.Noise = estimateNoise(model);

d=aviread(sName);
figure(1)
disp('Analysing the model...');
for i=model.NumPatterns+1:fInfo.NumFrames
    [model,imMask,resp]=updateAE_MEX(model,d(i).cdata);
    imshow(1 - imMask);
    pause(0.01);
end
disp('End of the process');

