% Demo code for the paper
% Foreground Detection in Video Sequences with Probabilistic
% Self-Organising Maps
% International Journal of Neural Systems. ISSN: 0129-0657. DOI: 10.1142/S012906571100281X  
% Coded by R.M.Luque and Ezequiel Lopez-Rubio -- June 2011 

% Load the video to analyse
disp('Loading the input sequence...');
sName='video.avi';
vidObj = VideoReader(sName);
NumFrames=vidObj.NumberOfFrames;
vidObj = VideoReader(sName);

% Create the structures of the stochastic approximation model
disp('Creating the structures of the probabilistic self organising network model...');
vidFrame = readFrame(vidObj);
model = createSOMModel(vidFrame);
model.LastFrame = NumFrames;
    
% Allocate scape for the set of images to initialise the model 
images = zeros(size(vidFrame,1),size(vidFrame,2),size(vidFrame,3),model.NumPatterns);
images(:,:,:,1) = vidFrame;

% Store the frames
for NdxFrame=2:model.NumPatterns
    vidFrame = readFrame(vidObj);
    images(:,:,:,NdxFrame) = vidFrame;
end
images = uint8(images);

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

%d=aviread(sName);
figure(1)
disp('Analysing the model...');
while hasFrame(vidObj)
    vidFrame = readFrame(vidObj);
    tic;
    Coef=CoefSOM(NdxFrame,model);
    model=TurboSOMMEX(model,double(vidFrame),Coef);
    toc;
    imMask = double(model.imMask >= 0.5);
    
    % Fill holes (size 1) y remove objects with minimum area
    imMask = bwmorph(imMask,'majority');
    imMask = removeSpuriousObjects(imMask, model.MaximumArea);
    
    subplot(1,2,1),imshow(vidFrame);
    title(['Frame nš ' num2str(NdxFrame)]);
    subplot(1,2,2),imshow(imMask);
    pause(0.01);
    NdxFrame=NdxFrame+1;
end
disp('End of the process');

