%Track a Face
%vision.HistogramBasedTracker System object

clear all;
close all;
clc;

%Create System objects for reading and displaying video and for drawing a bounding box of the object
videoFileReader = vision.VideoFileReader('vipcolorsegmentation.avi');
videoPlayer = vision.VideoPlayer();
shapeInserter = vision.ShapeInserter('BorderColor','Custom','CustomBorderColor',[1 0 0]);

%Read the first video frame, which contains the object. Convert the image to HSV color space. Then define and display the object region
objectFrame = step(videoFileReader);
objectHSV = rgb2hsv(objectFrame);
objectRegion = [40, 45, 25, 25];
objectImage = step(shapeInserter, objectFrame, objectRegion);

figure
imshow(objectImage)
title('Red box shows object region');

%(Optionally, you can select the object region using your mouse. The object must occupy the majority of the region. Use the following command.)
%figure; imshow(objectFrame); objectRegion=round(getPosition(imrect))


%Set the object, based on the hue channel of the first video frame.
tracker = vision.HistogramBasedTracker;
initializeObject(tracker, objectHSV(:,:,1) , objectRegion);

%Track and display the object in each video frame. 
%The while loop reads each image frame, converts the image to HSV color space, 
%then tracks the object in the hue channel where it is distinct from the background. 
%Finally, the example draws a box around the object and displays the results.
while ~isDone(videoFileReader)
  frame = step(videoFileReader);
  hsv = rgb2hsv(frame);
  bbox = step(tracker, hsv(:,:,1));

  out = step(shapeInserter, frame, bbox);
  step(videoPlayer, out);
  pause(0.1);
end


%Release the video reader and player.
release(videoPlayer);
release(videoFileReader);




