% clear;clc;

userNames = {'hong', 'le', 'song', 'zheng', 'yuan', 'priya', ...
    'hui1', 'hui2', 'chenkai', 'irina', 'pang', 'wenhui'};

for ii = 1:length(userNames)
    user = userNames{ii};
    fileName = ['/Users/Admin/Documents/My_Personal_Site/zheng_sun/mov/' user '.m4v'];
    
    my_MOV_reader = VideoReader(fileName); % load a movie

    % Read the movie size properties including number of frames, movie width and movie height.
    my_nFrames = my_MOV_reader.NumberOfFrames;
    my_movie_width = my_MOV_reader.Width;
    my_movie_height = my_MOV_reader.Height;
    
    % Preallocate storage space for the image data from the movie to be imported.    
    my_movie_data(1:my_nFrames) = ...
        struct('cdata',zeros(my_movie_height,my_movie_width,3,'uint8'),'colormap',[]);
    
    for kk = 1:my_nFrames

        % Read a frame
        my_movie_data(kk).cdata = read(my_MOV_reader,kk);
        data = my_movie_data(kk).cdata;

        % Now to track red objects in real time
        % we need subtract the red component
        % from the grayscale image to extract the red components in the image.
        diff_im1 = imsubtract(data(:,:,1), rgb2gray(data));
        %Use a median filter to filter out noise
        diff_im2 = medfilt2(diff_im1, [3 3]);
        % Convert the resulting grayscale image into a binary image.
        diff_im3 = im2bw(diff_im2,0.28);
        
        diff_im4 = bwareaopen(diff_im3,500);
        
        % Label all the connected components in the image.
        bw = bwlabel(diff_im4, 8);
        
        % Here we do the image blob analysis.
        % We get a set of properties for each labeled region.
        stats = regionprops(bw, 'BoundingBox', 'Centroid');
        
        % Display the image
        subplot(211);imshow(data);
        hold on
        for object = 1:length(stats)
            bb = stats(object).BoundingBox;
            bc = stats(object).Centroid;
            if bc(1) > 550 % eliminate impossible false alarms that is too close to image boundaries
                continue;
            end
            rectangle('Position',bb,'EdgeColor','r','LineWidth',2)
            plot(bc(1),bc(2), '-m+')
            bc
            a=text(bc(1)+15,bc(2), strcat('X: ', num2str(round(bc(1))), '    Y: ', num2str(round(bc(2)))));
            set(a, 'FontName', 'Arial', 'FontWeight', 'bold', 'FontSize', 30, 'Color', 'white');
        end
        str=text(15, 15, ['Frame #' num2str(kk)]);
        set(str, 'FontName', 'Arial', 'FontWeight', 'bold', 'FontSize', 40, 'Color', 'white');
        
        hold off
        subplot(212);imshow(diff_im3);
        
        pause;
    end
    
end