image thumbnail
from Detect Changes from a Video by Jussi Mattila
Detects changes (movements, colour changes) from a video through frame-to-frame comparison.

ChangeDetectionFromVideo.m

%%                         Detect changes in a video
%
%
% This script detects changes in a video by comparing each frame into a
% reference frame, here defined as the first frame of the video. If no
% changes occur, the resulting frame will only contain zero values, i.e.,
% the frame is black. If changes do occur, these are then shown with white colour in
% the resulting video. The results are showed in implay and, in addition, 
% written into an avi-file. 
%
% Note that prerequisite for using this script is the Image Processing Toolbox.
%
% Computation for large video files will be time consuming...
%
%
%                      Copyright (C) Jussi Mattila 2013
%
%
%
% This program is free software; you have the permission to use, copy, and
% distribute, either verbatim or with modifications, either without cost or for a
% fee, as long as the copyright notice above is distributed with the software
% and you clearly state modifications made to the original code.
% Improvements to the code are  welcomed!
%
% 
%                      Contact: jussi.mattila@posiva.fi

%% Input - read in the videofile and define the first frame

clear

MovieObj = VideoReader('Insert the name of the video file here'); %Read in the videofile
nframes = get(MovieObj, 'NumberOfFrames'); %Compute the number of frames in the video
FirstFrame=read(MovieObj,1); %Define the first frame in the video as the FirstFrame
FirstFrame=rgb2gray(FirstFrame); %Change the frame into grayscale

%% Create an array "Original" from the original movie


for k = 1 : nframes
    OriginalFrame = read(MovieObj, k); %Read in the k:th frame
    OriginalFrame=rgb2gray(OriginalFrame); %Change the frame into grayscale
    Original(:,:,:,k) = OriginalFrame; %Write the results into 
...the array "Original"
end

%% Compute the difference between the first and k:th frame and create an array "EnhancedChange"
...(the k:th frame defined as NextFrame)


for k = 1 : nframes
    NextFrame = read(MovieObj, k); %Read in the k:th frame
    NextFrame=rgb2gray(NextFrame); %Change the frame into grayscale
    NextFrame=FirstFrame-NextFrame; %Compute the difference between 
    ...the first and k:th frame
    EnhancedChange(:,:,:,k) = NextFrame*2; %Write the results into 
...the array "EnhancedChange"
end



%% Play the results with implay with the original video on top and changes below

Mov=vertcat(Original,EnhancedChange);
implay(Mov)

%% Write the resulting file into avi - uncomment if you want to take this in use 

% writerObj = VideoWriter('movie.avi');
% open(writerObj);
% writeVideo(writerObj,Mov);
% close(writerObj);


Contact us