% CIS 601 Computer Graphics and Image Processing
% Homework 3                    Spring 2007
% Riu Baring
% ==============================================
% Main function
% ==============================================

% 
clear all

% Load a Matlab data file
load survtestframes.mat;

% Array pre-allocation
BG1 = zeros(240, 320);
BG2 = zeros(240, 320);
BG1std = zeros(240, 320);
BG2std = zeros(240, 320);
p = zeros(240, 320);
dimg = zeros(240, 320);
v = zeros(1, 56);

% Compute a background image BG1 from the frames as the mean of all
% frames
BG1 = mean(ag, 3);

% Compute the pixelwise standard deviation in each pixel using all frames
BG1std = std(ag, 0, 3);

for i = 1:size(ag,3)
    dimg = abs(ag(:, :, i) - BG1);
    p = (dimg > 2 * BG1std);
    %subplot(2,2,1); imshow(ag(:,:,i));
    %subplot(2,2,2); imshow(p);
    v(i) = sum(p(:));
    %[i v(i)]
    %pause(0.5);
end

%subplot(2,2,3); bar(v);

% Compute second background image BG2 from frames with a foreground
% activity that's less than the mean activity.
BG2 = mean(ag(:,:,v < mean(v)), 3);

% Compute the pixelwise standard deviation in each pixel using frame with a
% foreground activity that's less than the mean activity.
BG2std = std(ag(:,:,v < mean(v)), 0, 3);

for i = 1:size(ag,3)
    dimg = abs(ag(:, :, i) - BG2);
    p = (dimg > 2 * BG2std);
    subplot(2,2,1); imshow(ag(:,:,i));
    subplot(2,2,2); imshow(p);
    %v(i) = sum(p(:));
    i
    pause(0.5);
end