


BG1 = mean(ag,3);
BGstd = std(ag,0,3);

for i=1:size(ag,3)
    FG = BGthres(ag(:,:,i), BG1, BGstd);
    v(i) = size(find(FG),1);
    FGag(:,:,i) = FG;
end

vm = mean(v);
vlow = find(v < vm);
BG2 = mean(ag(:,:,vlow),3);
BG2std = std(ag(:,:,vlow),0,3);
BGdiff = (abs(BG2-BG1));
BGhd = histeq(BGdiff);

for i=1:size(ag,3)
    FG = BGthres(ag(:,:,i), BG2, BG2std);
    v2(i) = size(find(FG),1);
    FG2ag(:,:,i) = FG;
end
