clear all
close all
clc
%% RETRIEVE HARDWARE INFORMATION
% DETERMINING THE ADAPTOR NAME
imaqhwinfo

% DETERMINING THE DEVICE ID 
info = imaqhwinfo('kinect')

% DETERMINING THE SUPPORTED VIDEO FORMATS
dev_info = imaqhwinfo('kinect',1)

%% CREATE A VIDEO INPUT OBJECT
vid = videoinput('kinect',1,'Infrared_640x480')

% VIEWING THE VIDEO INPUT OBJECT SUMMARY
vid

%% PREVIEW THE VIDEO STREAM 
preview(vid)

closepreview(vid)
%% CONFIGURE OBJECT PROPERTIES 
% VIEW OBJECT PROPERTIES
get(vid)
get(getselectedsource(vid))

% SETTING OBJECT PROPERTIES
vid.TriggerRepeat = inf;

vid.FrameGrabInterval = 5;

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

%% ACQUIRE IMAGE DATA
% CREATE VIDEO IPUT OBJECT 
vid = videoinput('kinect',1,'Infrared_640x480')

vid.ReturnedColorSpace = 'grayscale'

% SET VIDEO INPUT OBJECT PROPERTIES FOR THIS APPLICATION
vid.TriggerRepeat = 100;
vid.FrameGrabInterval = 5;

% SET VALUE OF A VIDEO SOURCE OBJECT PROPERTY
vid_src = getselectedsource(vid);
vid_src.Tag = 'motion detection setup';

% CREATE A FIGURE WINDOW
img_IR = getsnapshot(vid);
figure(1)
imshow(img_IR)

% START ACQUIRING FRAMES
start(vid)

% CALCULATE DIFFERENCE IMAGE AND DISPLAY IT
while(vid.FramesAvailable >= 2)
    data = getdata(vid,2); 
    diff_im = imabsdiff(data(:,:,:,1),data(:,:,:,2));
    imshow(diff_im);
    drawnow     % update figure window
end

data = getdata(vid);

stop(vid)



% %% CONVERT TO GRAYSCALE IMAGE
img_gray = im2gray(img_IR);
imshow(img_gray);

img_gray_thresh = imbinarize(img_gray);

s=imfill(img_gray_thresh ,'holes');

imshow(s)
imshowpair(img_gray, img_gray_thresh, 'montage')