% https://ch.mathworks.com/help/vision/ug/automatically-propagate-labels-in-video.html

clc
clearvars;
close all;

video_file = 'dog_bump.mp4';
video = VideoReader(video_file);

% Skip ahead to frame
frame = read(video, 150);

% Read an image and define the bounding box
objectFrame = readFrame(video);
objectFrame = imrotate(objectFrame, -90);
objectRegion = [211,481,65,65];

% Draw the puppy
objectImage = insertShape(objectFrame,'rectangle',objectRegion,'ShapeColor','red');
figure;
imshow(objectImage);
title('Red box shows object region');

%% Add tracked features

points = detectMinEigenFeatures(im2gray(objectFrame),'ROI',objectRegion);

pointImage = insertMarker(objectFrame,points.Location,'+');
figure;
imshow(pointImage);
title('Detected interest points');

%% Initialize a tracker, track the puppy

% Initialize tracker
tracker = vision.PointTracker('MaxBidirectionalError',1);
initialize(tracker,points.Location,objectFrame);

outputVideo = VideoWriter('track_dog'); 
outputVideo.FrameRate = video.FrameRate;

open(outputVideo); 

while hasFrame(video)
    frame = readFrame(video);
    frame = imrotate(frame, -90);
    [points,validity] = tracker(frame); % Tracks each frame 
    out = insertMarker(frame,points(validity, :),'+'); % Display the features
    writeVideo(outputVideo, out); 
end

close(outputVideo); 
disp('Processed video saved.');
