clc
clear all
close all

nome = 'concrete200mm500mms0deg.tif';
A=imread(nome);

A=double(A);

% PEARSON CORRELATION


min_displacement = 15;
dt = 0.0004; % segundos
t = dt;
line_ref = 1;
index=1;
for line = 2:size(A,1)
    S1=A(line_ref, 1:size(A,2));
    S2=A(line, 1:size(A,2));     

    S1=S1-mean(S1);
    S2=S2-mean(S2);
    
    finalCorr = -2;
    distance = 0;
    d = 0;
    corre = corr(S1',S2','type','Pearson');
    
    if (corre > finalCorr)
        finalCorr = corre;
        distance = d;
    end
    
    for i = 1:(0.01*size(S1,2))
        S1(i) = [];
        S2(length(S2)) = [];
        corre = corr(S1',S2','type','Pearson');
        d = d + 1;
        if (corre > finalCorr)
            finalCorr = corre;
            distance = d;
        end
    end    
    
    if distance > min_displacement
        displacement(index) = distance;
        dtime(index) = t;
        line_ref = line;
        index=index+1;
        t = 0.0004;
    else
        t = t + dt;
    end
end

% dx = displacement*72/1899;
dx = displacement*36/1455;

v = dx ./ dtime;
time = cumtrapz(dtime);

figure
hold on

plot(time, v, 'b');
xlabel('Time (s)')
ylabel('Velocity (mm/s)')