# Matlab Motion Detection Help



## badkitty (Mar 27, 2011)

Hey Guys
I am working on a very simple algo for motion detection. I want to detect only one moving object and its centroid. I am pasting my code. The problem is that this is very slow. Can any one suggest how I can speed this up.


```
%%% MAIN CODE %%%
% Create video input object. 
vid = videoinput('winvideo',1,'YUY2_640x480');


src = getselectedsource(vid);
set(vid,'TriggerRepeat',0);
Triggerconfig(vid,'immediate');
set(vid,'ReturnedColorSpace','gray');
set(vid,'FramesPerTrigger',1000)
set(vid,'FramesAcquiredFcn',@difference);
set(vid,'FramesAcquiredFcnCount',2);
set(src,'Framerate','10');
vid.FrameGrabInterval = 1;

vid_src = getselectedsource(vid);
set(vid_src,'Tag','motion detection setup');

start(vid);


%%%% CALLBACK  FUNCTION DIFFERENCE %%%
function difference(obj,event)
data = getdata(obj,2);
diff_im = imabsdiff(data(:,:,1),data(:,:,2));
diff_imbw = im2bw(diff_im,0.07);
bwarea = bwareaopen(diff_imbw,60);
[y x ] = find(bwarea);
imshow(bwarea)
hold on
y = mean(y);
x = mean(x);
g = [x y]
plot(x,y,'*r');
hold off
flushdata(obj);
```
P.S I am a noob


----------

