%% Introduction
% This Script calculates the Keyholedepth and Keyholearea for each frame
%% Script Starts from here
% Empty Workspace, close windows, clear Command Window...
 clc;
 clear all;
 close all hidden;
%% Load Video from current folder
 currentFolder = pwd;
 currentFolder = strcat(currentFolder,'\');
% Find the current avi video in the folder
 current_video=dir(strcat(currentFolder,'*.avi'));
 filename=convertCharsToStrings('3. RawXRayVideo.mp4'); 
 vid = VideoReader(cell2mat(filename));
 nFrames = vid.NumFrames; %Number of frames
%% Define videos
% Initial video
 mov(1:nFrames) = struct('cdata',zeros(vid.Height,vid.Width, 3,'uint16'),'colormap',[]); % initial video without editing
% Keyhole parameters
 movK_1 = mov;  %bw video of not cropped video
 movK_2 = mov;  %video with edge detection
 movK_3 = mov;  %cropped bw video to region of interest (keyhole)
% Videos for brightness/contrast adjustments 
 mov_adjust = cell(nFrames,1);
 mov_adjust_diff = cell(nFrames,1);
%% Define matrices
% Initial Surface
 surface_edge_top = []; %Matrix for "top" surface edge
% Keyhole
 Keyhole_FrontWay = []; %Matrix for position data for the front edge of the keyhole
 Keyhole_Depth = []; %Matrix for position data of lowest point of the keyhole
 %% Define variables for tracking 1/2
 thresh_I_1 = 35; %threshold for surface edge detection
 column_search_s = vid.width/2; %column in which to find the bottom of the surface area (in bw video frame 1)
 Offset_Columns = 40; %Offset for search of the last frame (40 Columns "time" to have a positive return)
%% Find Initial Surface-borders
for k = 1 %Find the surface edges in first frame (without Keyhole/melted surgface)  
   % definition of image and basic adjustments 
    mov(k).cdata = read(vid,k); %define video variable
    a = mov(k).cdata;  
    a = rgb2gray(a); %convert rgb video to grayscale
    a = imadjust(a); %auto-adjust brightness and contrast
   % binarizing image and detect edges of surface
    a(a < thresh_I_1) = 0;
    a(a >= thresh_I_1) = 255;
    a_e = edge(a,'sobel');
   % save the top surface line (first white pixel in each column) to matrix 
    for z = 1 : vid.width %For all columns 
            surface_top=find(a_e(:,z),1==1); %Find first white pixel in current column z
            surface_edge_top(1,z)=surface_top; %Save surface to matrix
            surface_edge_bottom=find(a_e(:,column_search_s),1==1,'last'); %Find last white pixel
                                                                          %in defined column for "bottom" edge
    end
end
%% Define variables for tracking 2/2
 s_k_corr1 = 30; %s(urface)k(eyhole)corr(ection)1
 s_k_corr2 = 15; %2
 keyhole_find_row = surface_edge_bottom + s_k_corr1; %define row in which to the find keyhole edge
 crop_para = [0 surface_edge_bottom + s_k_corr2 vid.width vid.height-surface_edge_bottom-s_k_corr2]; %cropping parameter for brightness adjustment below surface
% Variables for binarising video
 brightness_increaser1 = 10; %factor for brightness adjustment
 brightness_increaser2 = 40; %factor for brightness adjustment
 thresh_K = 3; %threshold for binarizing keyhole video
%% Subtract static background
% Adjust brightness of ROI (below surface bottom) and calculate dynamic backround
 mean_brightness = zeros(nFrames,1); %create a 0 matrix 
 counter = 1; %counter for frames
 vid = VideoReader(cell2mat(filename));
 while hasFrame(vid) %while frame is available to read
   mean_brightness(counter) = mean(double(rgb2gray(imcrop(readFrame(vid), crop_para))), 'all'); %calculate the mean brightness in the ROI, write to matrix
   counter = counter + 1; 
 end
 mean_global = mean(mean_brightness); %calculate the mean brightness of all frames + all pixels of the ROI
 vid = VideoReader(cell2mat(filename));
 counter = 1; %new counter
 StatImage1 = zeros(vid.Height, vid.Width); %create a 0 matrix, video size
 while hasFrame(vid) %while frame is available to read
   StatImage1 = StatImage1 + double(rgb2gray(readFrame(vid)))/mean_brightness(counter)*mean_global; %adjust brightness of each frame, write all to one matrix (static background)
   counter = counter + 1; 
 end
 StatImage2 = StatImage1/counter; %create one image with usable values (static background)
%% Further brightness adjustments, subtract staic background from video
for k = 1 : nFrames %for all frames of the video
    mov(k).cdata = read(vid,k);
    a = mov(k).cdata;
    a = double(rgb2gray(a))/mean_brightness(k)*mean_global-StatImage2; %adjust brightness,subtract static background image
    a(a<0) = 0; %eliminate negative pixel values
    mov_adjust{k} = a;
    mov_adjust{k} = mov_adjust{k}/mean_brightness(k)*brightness_increaser2; %further brighntess adjustment
    maxb = max(mov_adjust{k},[],'all'); %maximum pixel value of frame
    minb = min(mov_adjust{k},[],'all'); %minimum pixel value of frame
    if k == 1 || maxb > max_brightness %find the highest pixel value of the video
        max_brightness = maxb;
    end
    if k == 1 || minb < min_brightness %find the lowest pixel value of the video
        min_brightness = minb;
    end
end

for k = 1 : nFrames
    mov_adjust{k} = (mov_adjust{k} - min_brightness)/(max_brightness - min_brightness)*brightness_increaser1; %brightness adjustment
    if k < nFrames 
        mov_adjust_diff{k} = abs(mov_adjust{k + 1} -  mov_adjust{k}); %subtract the current frame from next frame
        movK_1(k).cdata = mov_adjust_diff{k}; %define keyholevideo (grayscale)
       % binarize Keyholevideo
        movK_1(k).cdata(movK_1(k).cdata < thresh_K) = 0; %threshold found iterative
        movK_1(k).cdata(movK_1(k).cdata >= thresh_K) = 1;
        movK_1(k).cdata = bwareaopen(movK_1(k).cdata,500,4); %remove objects (two-dimensional four-connected neighborhood) smaller than 500 pixels
        movK_1(k).cdata = imfill(movK_1(k).cdata,4,"holes"); %fill holes in video (in keyhole) 4-dimensional neighbors
       % Edge detection for Keyhole
        movK_2(k).cdata = edge(movK_1(k).cdata,'sobel'); %use of sobel operator (Sobel approximation to the derivative)
        movK_2(k).cdata = bwareaopen(movK_2(k).cdata,50); %remove smaller than 50 pixel objects
       % remove first image from keyholevideo
        movK_3(k).cdata = movK_1(k).cdata - movK_1(1).cdata;
        movK_3(k).cdata(movK_3(k).cdata < 0) = 0; %eliminate negative pixel values
    end 
    %% calculation of keyholeparameters (depth, speed) in edge detection video
     keyhole=movK_2(k).cdata;
    % search for front edge of keyhole
     keyholefront = fliplr(keyhole); %mirror the video (find searches from left->right)
     KeyholePosFront = find(keyholefront(keyhole_find_row,:),1 == 1 ); % Keyholepos gespiegelt
     KeyholePosFront = vid.Width - KeyholePosFront; %mirror data back to make it usable
     keyholefront = flip(rot90(keyholefront),2); %mirror back and turn upside down to find depth (find searches left->right, top->down)
     [KeyholeDep_Column,KeyholeDep_Row] = find(keyholefront,1 == 1 ); %seperate columns and rows
     if KeyholeDep_Column >0 
        Keyhole_Depth(k,1) = k; %write frames to matrix for plot
        Keyhole_Depth(k,2) = (vid.height-KeyholeDep_Row)-surface_edge_top(1,KeyholeDep_Column); %calculate the depth of the keyhole (initial surface->depth of edge)
     end
     if KeyholePosFront > 0 %write postion data of keyhole and frames to matrix
        Keyhole_FrontWay = [Keyhole_FrontWay ;[KeyholePosFront,k]]; 
     end
    % Find last frame and pixel (with offset/range) of keyhole in the video
     LastData_K = find(Keyhole_FrontWay>(vid.width-Offset_Columns),1); %find last data in range of Offset_Columns
     if LastData_K > 0 %if last data found
        LastFrame_K = Keyhole_FrontWay(LastData_K,2);
        LastPixel_K = Keyhole_FrontWay(LastData_K,1);
     end
end
%% Keyholespeed calculation to define accurate ROI
 FirstPixel_K = Keyhole_FrontWay(1,1); 
 FirstFrame_K = Keyhole_FrontWay(1,2);
 WayKeyhole = LastPixel_K - FirstPixel_K; 
 TimeKeyhole = LastFrame_K - FirstFrame_K;
 VKeyhole = WayKeyhole / TimeKeyhole;
%% Cropping Video of Keyhole (bin) for calculation of keyholearea
 trackwidth = 100; %Tracking/Cropping width for keyhole(100 columns)
 Offset_Crop_K = 30; %Offset for cropping the width of the video
for k = FirstFrame_K : LastFrame_K
    Pos_Track = (k+1-FirstFrame_K) * VKeyhole; %calculate position of the keyhole for each frame
    Pos_Track = round(Pos_Track); %round to use it as pixel value
    Column_crop_K_3 = Pos_Track-(trackwidth-Offset_Crop_K); %calculate the left column for cropping the video
    if Column_crop_K_3 < 1 %if keyhole is not (yet) found 
        Column_crop_K_3 = 1;
    end
    height_K_1 = Keyhole_Depth(k,2); %height of the video
   % Crop the video to keyhole position/ROI 
    crop_para_K_3=[Column_crop_K_3+25 surface_edge_top(1,Pos_Track)+20 trackwidth-40 height_K_1+10]; %some iterative found offsets
    movK_3(k).cdata = imcrop(movK_3(k).cdata,crop_para_K_3); %crop the video
   %% Area calculation Keyhole
    Area_K_3 = bwarea(movK_3(1,k).cdata); %use bwarea to calculate area of white pixels per frame
    Keyhole_Area(k,1) = k; %save frames for plot
    Keyhole_Area(k,2) = Area_K_3; %save area to matrix
end
%% Prepare data for plot
 Keyhole_Depth(:,1) = Keyhole_Depth(:,1)*20; %frames to time
 Keyhole_Depth(:,3) = medfilt1(Keyhole_Depth(:,2))*2; %use of one dimensional median filter for depth data / *2 for pixel to length (micrometer)
 Keyhole_Area(:,1) = Keyhole_Area(:,1)*20; %frames to time
 Keyhole_Area(:,3) = medfilt1(Keyhole_Area(:,2))*4; %...and for area data / *4 for pixel to area (micrometer^2)
%% plot graphs
 figure(1)
 plot(Keyhole_Depth(88:543,1),Keyhole_Depth(88:543,3));
 title('Keyhole depth')

 figure(2)
 plot(Keyhole_Area(105:552,1),Keyhole_Area(105:552,3));
 title('Keyhole Area')
