% clear all
% close all
% load survtestframes.mat
bg1 = mean(ag,3);

sd1  = std(ag,0,3);
sd1 (sd1 == 0) = 0.0001;

figure(1);

for i = 1:56
    x(:,:,i) = abs((ag(:,:,i) - bg1(:,:))) < sd1.*2;
end

y = ag.*not(x);

for i = 1:56
    subplot(2,2,1);
    imshow(x(:,:,i) );
    xlabel('pixels that changed');

    subplot(2,2,2);
    imshow(ag(:,:,i));
    xlabel('full frame');

    subplot(2,2,3);
    imshow(y(:,:,i));
    xlabel('new pixels');
    pause(0.07);

    subplot(2,2,4);
    count(i) = 240*320 - sum(sum(x(:,:,i)));

    bar(count);

    xlabel('frame');
    ylabel('pixels changed');

end


display('Press any key to continue');
pause;

mc = mean(count);
emptyframes = count<mc;
bg2 = mean(ag(:,:,emptyframes),3);
sd2 = std(ag(:,:,emptyframes),0,3);
sd2 (sd2 == 0) = 0.0001;


figure(2);

subplot(2,2,1);
imshow(bg1);
xlabel('bg1');

subplot(2,2,2);
imshow(bg2);
xlabel('bg2');

subplot(2,2,3);
imshow(sd1);
xlabel('sd1');

subplot(2,2,4);
imshow(sd2);
xlabel('sd2');

display('Press any key to continue');
pause;


figure(3);

for i = 1:56
    x(:,:,i) = abs((ag(:,:,i) - bg2(:,:))) < sd2.*2;
end

y = ag.*not(x);

for i = 1:56
    subplot(2,2,1);
    imshow(x(:,:,i) );
    xlabel('pixels that changed');

    subplot(2,2,2);
    imshow(ag(:,:,i));
    xlabel('full frame');

    subplot(2,2,3);
    imshow(y(:,:,i));
    xlabel('new pixels');
    pause(0.07);

    subplot(2,2,4);
    count2(i) = 240*320 - sum(sum(x(:,:,i)));

    bar(count2);

    xlabel('frame');
    ylabel('pixels changed');

end

bgcompare = histeq(abs(bg1-bg2));
figure
imshow(bgcompare);
xlabel('difference in background');

sdcompare = histeq(abs(sd1-sd2));
figure
imshow(sdcompare);
xlabel('difference in standard deviation');
