% Assignment 1
% Author: Vladimir Ouzienko
% Date 02/02/2008


% get standard deviation
agStdev=std(ag,1,3);
% get back ground image as mean
backGround = mean(ag,3);
% show diffs images thresholded by standard deviation
% and save stuff into vector
vectorOfDiffs =zeros(56,1);
for i=1:size(ag,3)
    diffImage = abs(ag(:,:,i)-backGround);
    diffImage(diffImage<=agStdev*2)=0;
    diffImage(diffImage>agStdev*2)=1;
    foreGroundPixels = sum(diffImage(:));
    vectorOfDiffs(i,1)=foreGroundPixels;
    imshow(diffImage);
    pause(0.06);
end

bar(vectorOfDiffs);
% -------------------------------------------------------------------
% there is a clear correlation between this plot and the activity
% in the movie. The number of pixels peaks out when there is the most
% activity in the movie clip. I think this simple technique of detecting 
% frames with moving images is workable only for some types of environments,
% such as the one presented. The background in the movie is static, the
% lightning is the same, there is very little background noise.

pause(1);
% 7 points 

%mean of vectorValues
vectorsMean = mean(vectorOfDiffs);
counter=0;
secondBackground = zeros(size(ag,1),size(ag,2));
for i=1:size(vectorOfDiffs,1)
    if vectorOfDiffs(i,1) < vectorsMean
       counter=counter+1;
       secondBackground = secondBackground+ ag(:,:,i);
    end         
end    
% second background is composed of frames
% with zero activity
secondBackground = secondBackground/counter;

% show the movie using secondBackground
for i=1:size(ag,3)
    diffImage = abs(ag(:,:,i)-secondBackground);
    diffImage(diffImage<=agStdev*2)=0;
    diffImage(diffImage>agStdev*2)=1;
    imshow(diffImage);
    pause(0.06);
end

pause(1);
%show diff between original and learned backgrounds
%abs value
imshow(abs(backGround-secondBackground),[0,1]);
pause(0.5);
%  ..and contrasted
imshow(histeq(abs(backGround-secondBackground),[0,0.25,0.5,0.75,1]));
%-------------------------------------------------------------------
% The most obvious difference between 2 backgrounds is the professor's
% figure, which shows that the second version (learned) is supposed
% to better than original. The mean of second background is composed from 
% frames without activity. However, looking at the two clips I could not 
% discern a notable difference.

% 10 points