Showing posts with label Motion Detection and Tracking. Show all posts
Showing posts with label Motion Detection and Tracking. Show all posts

Monday, 4 March 2013

Kalman filter full code(zipped)

Friday, 25 January 2013

Motion Detection using Camshift algorithm Matlab code


There are two files included.

1.convert video frames using this .m file


clc;
cd frames;

for i = 2:107,
    filename1 = sprintf('%3.3i.png', i);
    filename2 = sprintf('%3.3i.png', i-1);
    A = imread(filename1, 'png');
    A = RGB2GRAY(A);
 
    B = imread(filename2, 'png');
    B = RGB2GRAY(B);
 
    C = imabsdiff(A,B);
    C = medfilt2(C, [5 5]);
    imwrite(C, sprintf('Frame %4.4d.png', i), 'png');
end

cd ..

disp('Done.');


2. Camshift.m



clc;
disp('Running...');
close all;
clear;
cd frames;

    WHITE = 255;

    % Threshold of convergence (in pixels for each deg. of freedom)
T = 1;
 
    % Number of pixels to expand search window by.
    P = 5;

avi = avifile('output1.avi');

% Initial search window size.
%W = [10 10];
W = [99 99];

% Initial location of search window.
%L = [95 193];
L = [71 141];

% For plotting motion
Xpoints=[];
Ypoints=[];

disp('Frame: Coordinates');

for frame = 1:44,
filename = sprintf('%3.3i.png', frame);
R = imread(filename, 'png');

% Convert image from RGB space to HSV space
I = rgb2hsv(R);

% Extract the hue information
I = I(:,:,1);
    I = roicolor(I, 0.83, 1.0);
 
    % Initialization
    oldCamL = [0 0];
    MeanConverging = 1;

    for i = L(1) : L(1)+W(1),
        x = i;
        y = L(2);
        if x > size(I,1) | y > size(I,2) | x < 1 | y < 1
            continue;
        else
            R(x, y,:) = 0;
        end
    end
 
    for i = L(1) : L(1)+W(1),
        x = i;
        y = L(2) + W(2);
        if x > size(I,1) | y > size(I,2) | x < 1 | y < 1
            continue;
        else
            R(x, y, :) = 0;
        end
    end  
 
    for i = L(2) : L(2)+W(2),
        x = L(1);
        y = i;
        if x > size(I,1) | y > size(I,2) | x < 1 | y < 1
            continue;
        else
            R(x, y, :) = 0;
        end
    end  

    for i = L(2) : L(2)+W(2),
        x = L(1)+W(1);
        y = i;
        if x > size(I,1) | y > size(I,2) | x < 1 | y < 1
            continue;
        else
            R(x, y, :) = 0;
        end
    end  

M00 = 0.0;
for i = L(1)-P : (L(1)+W(1)+P),
            for j = L(2)-P : (L(2)+W(2)+P),
                if i > size(I,1) | j > size(I,2) | i < 1 | j < 1
                    continue;
                end
                M00 = M00 + double(I(i,j));
            end
end

M10 = 0.0;
for i = L(1)-P : (L(1)+W(1)+P),
            for j = L(2)-P : (L(2)+W(2)+P),
                if i > size(I,1) | j > size(I,2) | i < 1 | j < 1
                    continue;
                end
                M10 = M10 + i * double(I(i,j));
            end
end

M01 = 0.0;
for i = L(1)-P : (L(1)+W(1)+P),
            for j = L(2)-P : (L(2)+W(2)+P),
                if i > size(I,1) | j > size(I,2)| i < 1 | j < 1
                    continue;
                end              
                M01 = M01 + j * double(I(i,j));
            end
end

xc = round(M10 / M00);
yc = round(M01 / M00);

oldL = L;
L = [floor(xc - (W(1)/2)) floor(yc - (W(2)/2))];
     
        % Check threshold
        if abs(oldL(1)-L(1)) < T | abs(oldL(2)-L(2)) < T
            MeanConverging = 0;
        end
    end
 
    s = round(1.1 * sqrt(M00));
    W = [ s      floor(1.2*s) ];
    L = [floor(xc - (W(1)/2)) floor(yc - (W(2)/2))];
 
    % Output the centroid's coordinates
    disp(sprintf('%3i:   %3i, %3i', frame, xc, yc));
    Xpoints = [Xpoints xc];
    Ypoints = [Ypoints yc];
 
    % Superimpose plus sign on to centroid of hand.
    plus_sign_mask = [0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     1 1 1 1 1 1 1 1 1 1 1 1 1;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0];
sizeM = size(plus_sign_mask);
for i = -floor(sizeM(1) / 2):floor(sizeM(1) / 2),
        for j = -floor(sizeM(2) / 2):floor(sizeM(2) / 2),
            if plus_sign_mask(i+1+floor(sizeM(1) / 2), j+1+floor(sizeM(2) / 2)) == 1
                R(i+xc, j+yc, :) = WHITE;
            end
        end
end
% ----------------------------------------------------------------------
    % Display the probability image.
    I = rgb2hsv(R);
    S = [];
    S(:,:,1) = I(:,:,1);
    S(:,:,2) = I(:,:,1);  
    S(:,:,3) = I(:,:,1);
% Extract the hue information
    avi = addframe(avi, S);
 
end
disp('AVI move parameters:');
avi = close(avi)
plot(Ypoints,Xpoints, 'go' , Ypoints, Xpoints);
axis([0 320 0 240]);
cd ..
disp('Done.');








Thursday, 24 January 2013

Motion Tracking using Kalman Filter Matlab Code



clear all; close all; clc

%% Read video into MATLAB using aviread
video = aviread('Roof1.AVI');
nframes = length(video);

% Calculate the background image by averaging the first 5 images
temp = zeros(size(video(1).cdata));
[M,N] = size(temp(:,:,1));
for i = 1:10
    temp = double(video(i).cdata) + temp;
end
imbkg = temp/10;

% Initialization for Kalman Filtering
centroidx = zeros(nframes,1);
centroidy = zeros(nframes,1);
predicted = zeros(nframes,4);
actual = zeros(nframes,4);

% % Initialize the Kalman filter parameters
% R - measurement noise,
% H - transform from measure to state
% Q - system noise,
% P - the status covarince matrix
% A - state transform matrix

R=[[0.2845,0.0045]',[0.0045,0.0455]'];
H=[[1,0]',[0,1]',[0,0]',[0,0]'];
Q=0.01*eye(4);
P = 100*eye(4);
dt=1;
A=[[1,0,0,0]',[0,1,0,0]',[dt,0,1,0]',[0,dt,0,1]'];

% loop over all image frames in the video
kfinit = 0;
th = 38;
for i=1:nframes
  imshow(video(i).cdata);
  hold on
  imcurrent = double(video(i).cdata);
 
  % Calculate the difference image to extract pixels with more than 40(threshold) change
  diffimg = zeros(M,N);
  diffimg = (abs(imcurrent(:,:,1)-imbkg(:,:,1))>th) ...
      | (abs(imcurrent(:,:,2)-imbkg(:,:,2))>th) ...
      | (abs(imcurrent(:,:,3)-imbkg(:,:,3))>th);

  % Label the image and mark
  labelimg = bwlabel(diffimg,4);
  markimg = regionprops(labelimg,['basic']);
  [MM,NN] = size(markimg);

  % Do bubble sort (large to small) on regions in case there are more than 1
  % The largest region is the object (1st one)
  for nn = 1:MM
      if markimg(nn).Area > markimg(1).Area
          tmp = markimg(1);
          markimg(1)= markimg(nn);
          markimg(nn)= tmp;
      end
  end

  % Get the upper-left corner, the measurement centroid and bounding window size
  bb = markimg(1).BoundingBox;
  xcorner = bb(1);
  ycorner = bb(2);
  xwidth = bb(3);
  ywidth = bb(4);
  cc = markimg(1).Centroid;
  centroidx(i)= cc(1);
  centroidy(i)= cc(2);

  % Plot the rectangle of background subtraction algorithm -- blue
  hold on
  rectangle('Position',[xcorner ycorner xwidth ywidth],'EdgeColor','b');
  hold on
  plot(centroidx(i),centroidy(i), 'bx');

  % Kalman window size
  kalmanx = centroidx(i)- xcorner;
  kalmany = centroidy(i)- ycorner;

  if kfinit == 0
      % Initialize the predicted centroid and volocity
      predicted =[centroidx(i),centroidy(i),0,0]' ;
  else
      % Use the former state to predict the new centroid and volocity
      predicted = A*actual(i-1,:)';
  end
  kfinit = 1;

  Ppre = A*P*A' + Q;
  K = Ppre*H'/(H*Ppre*H'+R);
  actual(i,:) = (predicted + K*([centroidx(i),centroidy(i)]' - H*predicted))';
  P = (eye(4)-K*H)*Ppre;

  % Plot the tracking rectangle after Kalman filtering -- red
  hold on
  rectangle('Position',[(actual(i,1)-kalmanx) (actual(i,2)-kalmany) xwidth ywidth],'EdgeColor','r','LineWidth',1.5);
  hold on
  plot(actual(i,1),actual(i,2), 'rx','LineWidth',1.5);
  drawnow;
end