Thursday, 12 March 2015

Matlab Code For Face Detection And Tracking (Commented)

faceDetector = vision.CascadeObjectDetector();%creating a face detector object

obj =imaq.VideoDevice('winvideo', 1, 'YUYV_320x240','ROI', [1 1 320 240]);  %obj is the image aquisition object ,setting up the video device and aquire one frame at a time from a video device
set(obj,'ReturnedColorSpace', 'rgb');  % set is used for configuring or displaying image aquisition object properties                
figure('menubar','none','tag','webcam');%figure creates a new figure window using default property values

while (true)
    frame=step(obj);%
    bbox=step(faceDetector,frame);%the System object uses the step function to acquire single frames
 

    boxInserter  = vision.ShapeInserter('BorderColor','Custom',...
    'CustomBorderColor',[255 255 0]);%vision.ShapeInserter is a System object which is used to Draw rectangles, lines, polygons, or circles on an image
videoOut = step(boxInserter, frame,bbox);%the System object uses the step function to acquire single frames
 
    imshow(videoOut,'border','tight');%imshow is used to display an image
   
    f=findobj('tag','webcam');% find obj is used to Locate graphics objects with specific properties
   
    if (isempty(f));
        [hueChannel,~,~] = rgb2hsv(frame);% used to Determine whether array is empty


figure, imshow(hueChannel), title('Hue channel data');


rectangle('Position',bbox,'EdgeColor','r','LineWidth',1)% used to create a 2d rectangle object
hold off
noseDetector = vision.CascadeObjectDetector('Nose');%used to detect nose
faceImage    = imcrop(frame,bbox);%imcrop is used to crop an image
imshow(faceImage)  % imshow is used to show an image on the output screen
noseBBox     = step(noseDetector,faceImage);%the System object uses the step function to acquire single frames

noseBBox(1:1) = noseBBox(1:1) + bbox(1:1);
videoInfo    = info(obj);
ROI=get(obj,'ROI');%ROI: region of interest
VideoSize = [ROI(3) ROI(4)];

videoPlayer  = vision.VideoPlayer('Position',[300 300 VideoSize+30]);% setting up the video player
tracker = vision.HistogramBasedTracker;% creting a hostogram based tracker to track the face continiosly
initializeObject(tracker, hueChannel, bbox);% initialising the histogram based tracker

while (1)
   



    frame = step(obj);

    [hueChannel,~,~] = rgb2hsv(frame);

 
    bbox = step(tracker, hueChannel);

   
    videoOut = step(boxInserter, frame, bbox);

   
    step(videoPlayer, videoOut);
    pause (.2)
end


release(obj);
release(videoPlayer);

        close(gcf)
       
       

       
        break
    end
    pause(0.05)
end
release(obj)