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

for i=1:size(ag,3)
    FG = BGthres(Wag(:,:,i), BG1, BGstd);
    v(i) = size(find(FG),1);
    FGag(:,:,i) = FG;
    se=strel('square',3);
%    FGclag(:,:,i) = imclose(imclose(imopen(imopen(FG,se),se),se),se);
    FGclag(:,:,i) = imclose(imopen(FG,se),se);
end

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

for i=1:size(ag,3)
    FG = BGthres(Wag(:,:,i), BG2, BG2std);
    FG2ag(:,:,i) = FG;
    se=strel('square',3);
    FG3ag(:,:,i) = imclose(imclose(imopen(imopen(FG,se),se),se),se);
%    FG3ag(:,:,i) = imclose(imopen(FG,se),se);
    v2(i) = size(find(FG3ag(:,:,i)),1);
    ED(:,:,i) = imdilate(FG3ag(:,:,i),se);
end
FG4 = ED - FG3ag;
FG4 = (FG4 == 1);

