%% Motion History in Matlab

close all
clear all

%vr = VideoReader('backgammon.m4v');
vr = VideoReader('small.m4v');
vr.CurrentTime = 0.0;

mhist = uint8(zeros(vr.Height, vr.Width)); % motion history image

if hasFrame(vr)
    pFrame = readFrame(vr);
    pFrameGray = im2gray(pFrame);  % previous frame
end
   
while hasFrame(vr)
    cFrame = readFrame(vr);       % current frame
    cFrameGray = im2gray(cFrame);
    diff = uint8(abs( double(cFrameGray) - double(pFrameGray)));
    change=find(diff > 20); 
    mhist(change) = 255;
    imshow(mhist)
    
    % The next line relies on the properties of uint8 arithmetic.
    % For example, 5-10=0. So, no check for negative is needed.
    mhist = mhist - 10; % decay the motion history

    pause(1/vr.FrameRate);
    pFrameGray=cFrameGray;
end

