bg1 = mean(ag,3);
bgstd = std(ag,1,3);
for i=1:size(ag,3)
    subplot(8,7,i), imshow(ag(:,:,i)), axis off;
end
figure;
for i=1:size(ag,3)
    img = abs(ag(:,:,i) - bg1) > 2*bgstd;
    subplot(8,7,i), imshow(img), axis off;
    v(i) = sum(img(:));
end
figure;
bar(v);

idx = find(v<mean(v));
bg2 = mean(ag(:,:,idx),3);
bgstd2 = std(ag(:,:,idx),1,3);
figure;
for i=1:size(ag,3)
    img = abs(ag(:,:,i) - bg2) > 2*bgstd2;
    subplot(8,7,i), imshow(img), axis off;
    v(i) = sum(img(:));
end

figure;
subplot(2,2,1), imshow(bg1);
subplot(2,2,2), imshow(bg2);
subplot(2,2,3), imshow(abs(bg2-bg1));
subplot(2,2,4), imshow(histeq(abs(bg2-bg1)));
