% GNF demo for segmentation with the 'Video2' video sequence and the 'RGB'
% color space
clear
MaxNeurons = 50; % Maximum number of neurons in each graph
NumBackgroundFrames = 100;
MyVideo = 'Video2';
MyColorSpace = 'RGB';
SubPathFrames = '/frames/f%07d.bmp';
SubPathGT = '/GT/GT%07d.bmp';
NumFrames = 749;
NumGTFrames = 444;
FirstGTFrame = 253;
Mu = 2;

% The following values of the parameters are those considered in the
% original GNG paper by Fritzke (1995)
Lambda=100;
Epochs=2;
EpsilonB=0.2;
EpsilonN=0.006;
Alpha=0.5;
AMax=50;
D=0.995;

% Store the first frames belonging to the background
NdxInitFrame = FirstGTFrame - NumBackgroundFrames;
MyFrame = imread(sprintf([MyVideo SubPathFrames],NdxInitFrame));
FirstFrames = zeros(size(MyFrame,1),size(MyFrame,2),size(MyFrame,3),NumBackgroundFrames);
FirstFrames(:,:,:,1) = MyFrame;
for NdxFrame=2:NumBackgroundFrames,
    NdxInitFrame = NdxInitFrame + 1;
    MyFrame = imread(sprintf([MyVideo SubPathFrames],NdxInitFrame));    
    FirstFrames(:,:,:,NdxFrame) = MyFrame;
end

% Obtain the samples as the median of the first NumBackgroundFrames frames
MyFrame = median(FirstFrames,4);
MyFrame = NormalizarEspColor(double(MyFrame), MyColorSpace);
MyMatrixFrame = reshape(shiftdim(MyFrame,2),3,[]);           
[i,j] = ind2sub([size(MyFrame,1) size(MyFrame,2)],[1:length(MyMatrixFrame)]);
Samples = [MyMatrixFrame;Mu*NormalizeData(i);Mu*NormalizeData(j)];                  
NumSamples = size(Samples,2);
NumSteps = Epochs*NumSamples;

% GNF Training
[Model] = TrainGNF(Samples,MaxNeurons,Lambda,EpsilonB,EpsilonN,Alpha,AMax,D,NumSteps);

% GNF Test
[Winners,Errors] = TestGNG(Model,Model.Samples);
PerformanceMeasures = TestGNFSegmentation(Model,Errors,...
                MyColorSpace,NumFrames,NumGTFrames,0,[MyVideo SubPathFrames],[MyVideo SubPathGT],Mu); 

% Plot the segmented image
figure, imshow(SegmentedImage);
