
%% this file is used to calculate the motion saliency for video frames based on motion contrast

function m_smap = motion_contrast(uv)
    
% load '.\flow_code\optical_flow_result\all_res\beverly01_9';

[row col dim] = size(uv);
row_blk_num = row/8;
col_blk_num = col/8;
x_mv = uv(:, :, 1);
y_mv = uv(:, :, 2);
mv = uv;

%% the following metrics are calcualted for CSF
array_x = zeros(row_blk_num, col_blk_num);
array_y = zeros(row_blk_num, col_blk_num);
avg_x_mv = zeros(row_blk_num, col_blk_num);
avg_y_mv = zeros(row_blk_num, col_blk_num);
avg_mv = zeros(row_blk_num, col_blk_num, 2);
for i = 1:row_blk_num
    for j = 1:col_blk_num
        array_x(i, j) = i;
        array_y(i, j) = j;
        avg_x_mv(i, j) = mean2(x_mv(1 + ((i - 1)*8) : i*8, 1 + ((j - 1)*8) : j*8));
        avg_y_mv(i, j) = mean2(y_mv(1 + ((i - 1)*8) : i*8, 1 + ((j - 1)*8) : j*8));
        avg_mv(i, j, 1) = mean2(mv(1 + ((i - 1)*8) : i*8, 1 + ((j - 1)*8) : j*8, 1));
        avg_mv(i, j, 2) = mean2(mv(1 + ((i - 1)*8) : i*8, 1 + ((j - 1)*8) : j*8, 2));
    end
end



dist = zeros(row_blk_num, col_blk_num, row_blk_num, col_blk_num);
csf = zeros(row_blk_num, col_blk_num, row_blk_num, col_blk_num);
x_mv_diff = zeros(row_blk_num, col_blk_num, row_blk_num, col_blk_num);
y_mv_diff = zeros(row_blk_num, col_blk_num, row_blk_num, col_blk_num);
mv_diff = zeros(row_blk_num, col_blk_num, row_blk_num, col_blk_num);
for i = 1:row_blk_num
    for j = 1:col_blk_num
        dist(i, j, :, :) = sqrt((i - array_x).^2 + (j - array_y).^2);
        csf(i, j, :, :) = (1/(20*(sqrt(2*pi))))*exp(-(dist(i, j, :, :).^2/(2*20.^2)));
        x_mv_diff(i, j, :, :) = avg_x_mv(i, j) - avg_x_mv;
        y_mv_diff(i, j, :, :) = avg_y_mv(i, j) - avg_y_mv;
    end
end

for i = 1:row_blk_num
    for j = 1:col_blk_num
        m_smap(i, j) = sum(sum(csf(i, j, :, :) .* (sqrt(x_mv_diff(i, j, :, :).^2 + y_mv_diff(i,j,:,:).^2))));
    end
end

m_smap = imresize(m_smap, [row col]);
m_smap = mat2gray(m_smap);



end