% Jingting Zeng  02/20/07
% detect cars

% midian filter, dilation, erosion
for i=1:size(ag,3)
    ag2(:,:,i) = im2double(ag(:,:,i));
    ag2(:,:,i) = histeq(ag2(:,:,i));
end

bgMean1 = mean(ag2,3);
bgStd1 = std(ag2,1,3);
M=[];
for i=1:size(ag,3)
    diff1(:,:,i)= abs(ag2(:,:,i)-bgMean1)>2*bgStd1;
    diff1(:,:,i) = medfilt2(diff1(:,:,i),[3 3]);
    se=strel('disk',2);
    diff1(:,:,i) = imdilate(diff1(:,:,i),se);
    diff1(:,:,i) = imerode(diff1(:,:,i),se);
%     diff1(:,:,i) = imdilate(diff1(:,:,i),se);
    imshow(diff1(:,:,i));
    M=[M getframe()];
end
movie2avi(M,'2_1.avi');

% blur, median
for i=1:size(ag,3)
    ag2(:,:,i) = im2double(ag(:,:,i));
    ag2(:,:,i) = histeq(ag2(:,:,i));
    ag2(:,:,i) = filter2(fspecial('motion'),ag2(:,:,i));
    ag2(:,:,i) = filter2(fspecial('unsharp'),ag2(:,:,i));
end

bgMean1 = mean(ag2,3);
bgStd1 = std(ag2,1,3);
M=[];
for i=1:size(ag,3)
    diff1(:,:,i)= abs(ag2(:,:,i)-bgMean1)>2*bgStd1;
    diff1(:,:,i) = medfilt2(diff1(:,:,i),[3 3]);
    imshow(diff1(:,:,i));
    M=[M getframe()];
end
movie2avi(M,'2_2.avi');

%laplacian, erosion, dilation
for i=1:size(ag,3)
    ag2(:,:,i) = im2double(ag(:,:,i));
    ag2(:,:,i) = histeq(ag2(:,:,i));
    ag1(:,:,i) = imfilter(ag2(:,:,i), fspecial('laplacian',0),'replicate');
    ag2(:,:,i)= ag2(:,:,i)-ag1(:,:,i);
end

bgMean1 = mean(ag2,3);
bgStd1 = std(ag2,1,3);
M=[];
for i=1:size(ag,3)
    diff1(:,:,i)= abs(ag2(:,:,i)-bgMean1)>2*bgStd1;
    se=strel('disk',1);
    diff1(:,:,i) = imdilate(diff1(:,:,i),se);
    se = strel('disk',1);
    diff1(:,:,i) = imerode(diff1(:,:,i),se);
    imshow(diff1(:,:,i));
    M=[M getframe()];
end
movie2avi(M,'2_3.avi');
