function PerformanceMeasures = TestGNFSegmentation(Model,TrainingErrors,ColorSpaceName,NumFrames,NumGTFrames,DeltaFrames,VideoPath,GTPath,Mu)
% Performs a video segmentation by using the trained GNF model
% E.J. Palomo 2015

MinArea = 10;
PerformanceMeasures = zeros(7,0);
Cputime = 0;
contGT = 0;

for NdxFrame=1:NumFrames,
    
    if (mod(NdxFrame,100)==0),
        fprintf('\tFrame %d\n',NdxFrame);
    end
    
    if exist(sprintf(GTPath,DeltaFrames+NdxFrame),'file')
        % Obtain the test samples
        MyFrameOrig = imread(sprintf(VideoPath,DeltaFrames+NdxFrame));             
        MyFrame = NormalizarEspColor(double(MyFrameOrig), ColorSpaceName);
        MyMatrixFrame = reshape(shiftdim(MyFrame,2),3,[]);            
        [i,j] = ind2sub([size(MyFrame,1) size(MyFrame,2)],[1:length(MyMatrixFrame)]);
        TestSamples = [MyMatrixFrame;Mu*NormalizeData(i);Mu*NormalizeData(j)];

        % DETECT THE FOREGROUND
        tic;
        [TestWinners,TestErrors] = TestGNG(Model,TestSamples);       
        ErrorDiff = abs(TrainingErrors - TestErrors);
        MyThreshold = nanmean(ErrorDiff)+nanstd(ErrorDiff);   
        ForegroundPixels = (ErrorDiff > MyThreshold);
        
        Cputime = Cputime + toc;
        imMask = reshape(ForegroundPixels,size(MyFrame,1),size(MyFrame,2));       
        imMask = double(imMask >= 0.5);

        % Fill holes (size 1) and remove objects with minimum area
        imMask = bwmorph(imMask,'majority');
        imMask = removeSpuriousObjects(imMask, MinArea);  
    
        % Measure performance    
        contGT = contGT+1;
        if contGT == round(NumGTFrames/2),
            SegmentedImage = imMask;
        end
        GroundTruthFrame = double(imread(sprintf(GTPath,DeltaFrames+NdxFrame)));       
        PerformanceMeasures(:,end+1) = EvaluatePerformance(imMask>40/255,GroundTruthFrame);
        
        % Plot frames
        fig = figure;
        set (fig, 'Units', 'normalized', 'Position', [0,0,1,1]);
        
        subplot(1,3,1)
        imshow(MyFrameOrig);
        title('Original Frame');
        
        subplot(1,3,2)
        imshow(GroundTruthFrame);
        title('Ground Truth');
        
        subplot(1,3,3)
        imshow(imMask);
        title('GNF Segmentation');                
        
        fprintf('\nPress any key to continue\n');
        pause
        close
    end
end
PerformanceMeasures(1,end+1) = Cputime/NumFrames;