%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This function 'pixelBasedMotionDetector' detects motion in an input .avi movie file using the concept of vector distance between
% two consecutive frames of the movie based on pixel differences.
%
% Programmer : Nilesh Ghubade (nileshg@temple.edu)
% Date : March 2003
% Advisor : Dr.Longin Jan Latecki (latecki@temple.edu )
% Course : CIS 750 (Spring 2003) --> Video Analysis and Video Mining.
% Assignment : Pixel based Motion detector.
% Department : Computer and Information Science Department, Temple University, Philadelphia, PA-19122, USA
%
% Input arguments:-
% aviFileName = Input .avi movie file from whom motion is to be detected.
%
% Output : -
% A plot of vector distance between consecutive frames in the form of 'indexed' images.
% A plot of vector distance between consecutive frames in the form of 'rgb' images.
% 
% Example : -
% 1) pixelBasedMotionDetector('security1.avi');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function pixelBasedMotionDetector(aviFileName)
movieObj = aviread(aviFileName);
noOfFrameImages = size(movieObj,2);


for count = 1:1:noOfFrameImages
    fileName = strcat('frame',num2str(count),'.bmp');
    imwrite(movieObj(count).cdata,fileName,'bmp');
end

for count = 1:1:(noOfFrameImages-1)
    fileName = strcat('frame',num2str(count),'.bmp');
    firstImg = imread(fileName);
    fileName = strcat('frame',num2str(count + 1),'.bmp');    
    secondImg = imread(fileName);
    
    indexedFirstImg = rgb2ind(firstImg,colormap(gray(256)));
    indexedSecondImg = rgb2ind(secondImg,colormap(gray(256)));
    
    vectorOfImgDist(count) = norm(double(indexedSecondImg) - double(indexedFirstImg));
    
    r = norm(double(secondImg(:,:,1)) - double(firstImg(:,:,1)));
    g = norm(double(secondImg(:,:,2)) - double(firstImg(:,:,2)));    
    b = norm(double(secondImg(:,:,3)) - double(firstImg(:,:,3)));    
    
    vectorOfRGBImgDist(count) = r + g + b;
    
    
end

figure;plot(vectorOfImgDist);xlabel('Frame Number');title('PixelBasedMotionDetector: Plot of vector distance between consecutive images in INDEXED format');
figure;plot(vectorOfRGBImgDist);xlabel('Frame Number');title('PixelBasedMotionDetector: Plot of vector distance between consecutive images in RGB format');

for count = 1:1:noOfFrameImages
    fileName = strcat('frame',num2str(count),'.bmp');
    delete(fileName);
end

return;