user2071595
user2071595

Reputation: 9

Real time motion detection and alarm generation using MATLAB

I am doing a project on real time motion detection for security purpose using MATLAB with alarm generation. I had created code for live video capturing and saved it into an AVI file, but I am unable to read the live video in the code while it is running. Motion detection is not working properly. I have done this using two scripts. Two scripts are independently working, but when combined it is not reading live input. The scripts I used are posted below.

Enter code here 1. %code for reading and saving AVI file

function realtime_test()
    global movie name vid;
    % Define frame rate
    NumberFrameDisplayPerSecond=10;

    % Open figure
    hFigure=figure(1);

    % Set-up webcam video input

    vid = videoinput('winvideo', 1);

    % Set parameters for video
    % Acquire only one frame each time
    set(vid,'FramesPerTrigger',1);
    % Go on forever until stopped
    set(vid,'TriggerRepeat',Inf);
    % Get a grayscale image
    set(vid,'ReturnedColorSpace','rgb')
    vidRes = get(vid, 'VideoResolution');
    nBands = get(vid, 'NumberOfBands');
    hImage = imshow( zeros(vidRes(2), vidRes(1), nBands));
    preview(vid,hImage);
    triggerconfig(vid, 'Manual');

    % Set up timer object
    TimerData=timer('TimerFcn', {@FrameRateDisplay,vid},'Period',1/NumberFrameDisplayPerSecond,'ExecutionMode','fixedRate','BusyMode','drop');
    name = 'Realtime';
    movie=avifile(name,'compression','none');

    % Start video and timer object
    start(vid);
    start(TimerData);

    % We go on until the figure is closed
    uiwait(hFigure);

    % Clean up everything
    stop(TimerData);
    delete(TimerData);
    stop(vid);
    delete(vid);
    movie = close(movie);
    % Clear persistent variables
    clear functions;


% This function is called by the timer to display one frame of the figure

function FrameRateDisplay(obj, event,vid)
    global movie frame;

    frame=uint8(getsnapshot(vid));
    movie=addframe(movie,frame);
    persistent IM;
    persistent handlesRaw;
    persistent handlesPlot;
    trigger(vid);
    IM=getdata(vid,1,'uint8');

    if isempty(handlesRaw)
       % if first execution, we create the figure objects
       subplot(2,1,1);
       handlesRaw=imagesc(IM);
       title('CurrentImage');

       % Plot first value
       Values=mean(IM(:));
       subplot(2,1,2);
       handlesPlot=plot(Values);
       title('Average of Frame');
       xlabel('Frame number');
       ylabel('Average value (au)');
    else
       % We only update what is needed
       set(handlesRaw,'CData',IM);
       Value=mean(IM(:));
       OldValues=get(handlesPlot,'YData');
       set(handlesPlot,'YData',[OldValues Value]);
    end

2.% code for motion detection

% This m-file implements the frame difference algorithm for background
% subtraction.

clear all;
close all;

% source = aviread('live.avi');
%source = aviread('test.avi');
%--------------------------------------------------------------------------
[filename, pathname] = uigetfile( ...
   {'*.avi;*.mpg;*.mpeg;.*flv','Video Files (*.avi,*.mpg,*.mpeg,.*flv)';
   '*.*',  'All Files (*.*)'}, ...
  'Select a video file');

mov = mmreader(fullfile(pathname,filename));
implay(filename);
source = aviread(filename);
%--------------------------------------------------------------------------

thresh = 50;

bg = source(1).cdata;           % Read in 1st frame as background frame
bg_bw = rgb2gray(bg);           % Convert background to greyscale

% ----------------------- Set frame size variables -----------------------
fr_size = size(bg);
width = fr_size(2);
height = fr_size(1);
fg = zeros(height, width);

% --------------------- Process frames -----------------------------------

for i = 2:45
    fr = source(i).cdata;       % Read in frame
    fr_bw = rgb2gray(fr);       % Convert frame to grayscale

    fr_diff = abs(double(fr_bw) - double(bg_bw));  % Cast operands as double to avoid negative overflow

    for j=1:width                 % If fr_diff > thresh pixel in foreground
        for k=1:height
            if ((fr_diff(k,j) > thresh))
                fg(k,j) = fr_bw(k,j);

                disp('motion detected');

                %------------------------- Executes alarm ---------------------------------

                  t = 15;
                  Fs = 50;
                  [t,Fs] = wavread('Blip.wav');
                  player = audioplayer(t,Fs);
                  play(player);

                %--------------------------------------------------------------------------
            else
                fg(k,j) = 0;
            end
        end
        disp('motion not detected');
    end

    bg_bw = fr_bw;

    %figure(1), subplot(3,1,1), imshow(fr)
    subplot(3,1,2),imshow(fr_bw)
    subplot(3,1,3),imshow(uint8(fg))
    figure,imshow(uint8(fr_diff))

    %M(i-1)  = im2frame(uint8(fg),gray);        % Put frames into movie
end
fps = 15;
%movie2avi(M,'frame_difference_output', 'fps', 30);           % Save movie as AVI

Upvotes: 0

Views: 8735

Answers (2)

user1419
user1419

Reputation: 11

Instead of reading source in your second code you can directly read your live webcam using vid = videoinput('winvideo', 1). I think it will satisfy your requirements.Try out.

Upvotes: 1

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21561

As you are doing this for security purposes, I guess that near-realtime should be good enough. Here is a process flow that should work. Note that the entities that I mention can be threads, cpu's or even computers, whatever suits you.

  • Entity 1: Record a short fragment and save it (every 5 secs for example)
  • Entity 2: Frequently check the latest fragment and analyse it, including the sending of a signal if required. (every second for example)

With the times I proposed, you won't get realtime results but the delay should be limited to a max of 6 seconds.

Upvotes: 0

Related Questions