sumimg = zeros(240, 320);
%Create a matrix to store the sum of the images.
for a=1:56
sumimg = plus(sumimg, ag(:, :, a));
%Populate the matrix of the sum of images.
end
BG1 = sumimg ./ 56;
%Calculate the background image.
BGstd = std(ag, 0, 3);
%Calculate the standard deviation.
vector_v = zeros(1, 56);
%Create a vector to find the number of foreground pixels.
frgimg = zeros(240, 320, 56);
for i=1:56
    d = abs(ag(:, :, i) - BG1);
    e = BGstd*2;
    diffimg = d - e;
    %Calculate the difference image.
    for j=1:240
        for k=1:320
            if diffimg(j, k)<0
                diffimg(j, k)=0;
            else
                diffimg(j, k)=1;
            end
        end
        frgimg(:, :, i) = diffimg;
        %Fill the difference image matrix for each image.
        ones_vec = sum(sum(diffimg));
        %Find the number of ones in each difference image.
    end
            vector_v(i) = ones_vec;
            %Find the vector that contains the number of foreground pixels
            %in each frame.
end
avgv = sum(vector_v) ./ 56;
%Calculate the average number of foreground pixels.
newvec_v = vector_v - avgv;
%Find the vector that shows the deviation from the average foreground pixel
%value.
newsample = zeros(240, 320, 56);
%Create the new sample space for background detection.
for b=1:56
    if newvec_v(b)<0
        newsample(:, :, b)=ag(:, :, b);
    else
        newsample(:, :, b)=zeros(240, 320);
    end
end
sumimg1 = zeros(240, 320);
%Create a matrix to store the sum of the images.
for c=1:56
sumimg1 = plus(sumimg1, newsample(:, :, c));
%Populate the matrix of the sum of images.
end
BG2 = sumimg1 ./ 56;
%Calculate the background image.
BGstd1 = std(newsample, 0, 3);
%Calculate the standard deviation.
sumimg2 = zeros(240, 320);
%Create a matrix to store the sum of the images.
for d=1:56
sumimg2 = plus(sumimg2, newsample(:, :, d));
%Populate the matrix of the sum of images.
end
newvec = zeros(1, 56);
for e=1:56
    newvec(e) = 0;
    if newvec_v(e)<0;
    else
        newvec(e) = 1;
    end
end
lngthsmpl = 56 - sum(newvec);
%Finding the number of images with lower foreground activity than average.
BG3 = sumimg1 ./ lngthsmpl;
%Calculate the background image.
BGstd1 = std(newsample, 0, 3);
frgimg1 = zeros(240, 320, lngthsmpl);
for f=1:size(frgimg1, 3)
    d1 = abs(newsample(:, :, f) - BG3);
    e1 = BGstd1*2;
    diffimg1 = d1 - e1;
    %Calculate the difference image.
    for g=1:240
        for h=1:320
            if diffimg1(g, h)<0
                diffimg1(g, h)=0;
            else
                diffimg1(g, h)=1;
            end
        end
        frgimg1(:, :, f) = diffimg1;
        %Fill the difference image matrix for each image.
        %ones_vec = sum(sum(diffimg));
        %Find the number of ones in each difference image.
    end
end
bkgrnddiff = abs(BG2 - BG1); 
%Difference with image sample taken to fifty six.
bkgrnddiff1 = abs(BG3 - BG1);
%Difference image with the sample size taken to be smaller.

        