

%% (1) Randomly-select partial dataset
% Getting full frame list
frame_directory = 'data/frames/';
video_names = dir( [frame_directory 'sample*' ]);
full_frame_names = {};
counter = 1;
for videoIdx = 1:length( video_names )
    frame_names = dir( [frame_directory video_names(videoIdx).name '/*.jpg']);
    for frameIdx = 1:length( frame_names )
        full_frame_names{ counter, 1 } = [...
            frame_names(frameIdx).folder...
            '/' frame_names(frameIdx).name];
        counter=counter+1;
    end
end

% Random select & copy
trainset_directory = 'data/trainset/';
if ~isdir(trainset_directory), mkdir(trainset_directory); end
n_all_image = length(full_frame_names);
n_train_image = 101;
rng(abs(010-6207-8179)) % Fix random seed
target_frame_number = randi( n_all_image, [1 n_train_image] );
for frameIdx = 1:n_train_image
    copyfile( full_frame_names{target_frame_number(frameIdx)}, trainset_directory );
end

%% (2) Manual segmentation
mask_directory = trainset_directory;
img_list = dir( [trainset_directory 'frame*.jpg'] );
close all;
for frameIdx = 1:length(img_list)
    img_fname = img_list(frameIdx).name;
    mask_fname = ['mask' img_list(frameIdx).name(6:end-4) '.jpg'];
    frame = imread( [trainset_directory img_fname] );
    
    % Visualization
%     open frame; figure(1); clf; imagesc( frame ); drawnow; colormap gray;
    
    % Check existence
    if exist([trainset_directory mask_fname])
        disp(['Already exist::: ' trainset_directory mask_fname]);
    else
        figure(2); clf;
        gcf_pos = [50 50 1500 600];
        set(gcf, 'Position', gcf_pos, 'Color', [1 1 1]);
        
        % Segmentation
        subplot(1,2,1);
        try % if exist
            mask = image_ROI_selection(frame, [ 'Select area' ...
                '.. imgIdx=' num2str(sprintf('%04d',frameIdx))]);
        catch % in case of no mouse
            mask  = zeros(size(frame));
        end
        xlabel(img_fname)
        set(gca, 'FontSize', 15, 'Box', 'off', 'LineWidth', 2);
        
        % Show result
        subplot(1,2,2);
        imagesc( mask ); colormap gray;
        title('Result mask (binary)');
        drawnow;
        imwrite( mask, [mask_directory mask_fname]);
    end
end
%open mask
zip( 'data/trainset.zip', 'data/trainset/')
zip( 'data/frames.zip','data/frames/' )

%% Subfunction
function mask = image_ROI_selection(I, textInput)
if nargin == 1, textInput = ''; end
colormap(gray);
imshow(uint8(I), 'DisplayRange', [], 'InitialMagnification',600/max(size(I))*100 );
title( textInput )

%%-- Display instructions to user
%title('click points to make an initial contour, right click to close contour and finish');
disp('click points to make an initial contour,');
disp('right click to close contour and finish');

%%-- begin getting points
[y1 x1 b] = ginput(1);
xi = x1;
yi = y1;
if(b ~= 1) return; end

[ny nx c] = size(I);
mask = zeros(ny,nx);

while(1)
    x2 = x1;
    y2 = y1;
    [y1 x1 b] = ginput(1);
    
    if(b ~= 1)
        x1 = xi;
        y1 = yi;
    end
    
    %%--figure out the length of x & y component
    lx = x2-x1;
    ly = y2-y1;
    
    %%--figure out line length = pythagorian length + fudge factor
    len = ceil((lx^2+ly^2)^(1/2))+1;
    
    %%--make a linearly spaced vector (some values repeated)
    x = round(x1:(lx)/(len-1):x2);
    y = round(y1:(ly)/(len-1):y2); %make another one for y
    
    %%--if it was a constant level the lines above mess up make a constant line
    if(length(x) == 0)
        x = round(x1) * ones(1,len);
    end
    if(length(y) == 0)
        y = round(y1) * ones(1,len);
    end
    
    this_index2 = sub2ind(size(mask),x, y);
    if size(this_index2) == [1 1]
        title('Try Again!', 'FontSize', 18)
        sprintf Try_Again!
    end
    
    try  mask(this_index2) = 1; end
    idx = find(mask==1);
    backup_mask = mask;
    %%-- draw the users line in the image (color or grayscale)
    if(c-1)
        Ir = I(:,:,1); Ig = I(:,:,2); Ib = I(:,:,3);
        Ir(idx) = 0;
        Ig(idx) = 255;
        Ib(idx) = 0;
        I(:,:,1) = Ir; I(:,:,2) = Ig; I(:,:,3) = Ib;
    else
        I(idx) = 255;
    end
    imshow(uint8(I),'DisplayRange', [], 'InitialMagnification', 600/max(size(I))*100);
    title( textInput )
    if(b ~= 1) break; end
end
mask = bwfill(mask, 'holes');
% mask = ~mask;
end
