clc
close all

fname = '20171017-175848_AA3_UoB_5000V-10000V.MP4';

vr = VideoReader(fname);
frame = vr.readFrame();

imshow(frame);
title('Select ROI (rect)')
roi = getrect();

img = imcrop(frame, roi);
img = rgb2gray(img);

% h = imshow(img);
% 
% title('Select foreground')
% p = ginput(1);
% rowF = round(axes2pix(size(img, 2), get(h, 'XData'), p(2)));
% colF = round(axes2pix(size(img, 1), get(h, 'YData'), p(1)));
% indFore = sub2ind(size(img), rowF, colF); 
% 
% title('Select background')
% p = ginput(1);
% row = round(axes2pix(size(img, 2), get(h, 'XData'), p(2)));
% col = round(axes2pix(size(img, 1), get(h, 'YData'), p(1)));
% indBack = sub2ind(size(img), row, col); 

imageSegmenter(img)


basearea = 0;
relarea = zeros(1000, 1);
i = 1;
while vr.hasFrame()
    frame = vr.readFrame();
    
    img = imcrop(frame, roi);
    img = rgb2gray(img);
    
    
%     L = superpixels(img,2749);
%     BW = lazysnapping(img,L,indFore,indBack);

%     % Flood fill
%     tolerance = 50;
%     BW = grayconnected(img, rowF, colF, tolerance);
% 
%     % Close mask with disk
%     radius = 10;
%     decomposition = 0;
%     se = strel('disk', radius, decomposition);
%     BW = imclose(BW, se);
    
    BW = activecontour(img, mask, 10);
    
    imshow(BW)
    
    area = sum(BW(:));
    
    if basearea == 0
        basearea = area;
    end
    
    relarea(i) = area/basearea;
    i = i+1;
    
    if mod(i, 10) == 0
        disp(i)
    end
end

relarea = relarea(1:i-1);

plot(relarea)

save([fname(1:end-4) '_rel_def'], 'relarea')


