% This is the function for the feature extraction of the 
% image-statistics-based method for recaptured image detection.
% cf. research report 'A simple and effective image-statistics-based 
% approach to detecting recaptured images from LCD screens'
% Author: Kai Wang
% GIPSA-Lab, AGPIG team, CNRS UMR5216, Grenoble, France
% Email: kai.wang@gipsa-lab.grenoble-inp.fr
% Usage: feature_vector = recap_feature_extraction(im)
% feature_vector: extracted 28-dimensional feature vector
% im: the input image in form of a matrix of pixel values
% Pixel values in the 'im' variable should be integers in the range from 0
% to 255.

function feature_vector = recap_feature_extraction(im)

% initialization
corr_size = 5;
half_window = (corr_size-1) / 2;
corrs1 = zeros(1,14);
corrs2 = zeros(1,14);

% converting to int16, a trick to be faster
im = int16(im);
height_im = size(im,1);
width_im = size(im,2);

% two simple filters
imtemp = im * 2;
h1 = [0 0 0; 1 0 1; 0 0 0];
h2 = [0 1 0; 0 0 0; 0 1 0];

% residue images
imdiff1 = imtemp - imfilter(im,h1);
imdiff2 = imtemp - imfilter(im,h2);

% trimming residues images
imdiff1(1,:) = [];
imdiff1(end,:) = [];
imdiff1(:,1) = [];
imdiff1(:,end) = [];
imdiff2(1,:) = [];
imdiff2(end,:) = [];
imdiff2(:,1) = [];
imdiff2(:,end) = [];

% extract the vector for the central pixel
height_imdiff = size(imdiff1,1);
width_imdiff = size(imdiff1,2);

% for residue image 1
central_pixels1 = imdiff1(half_window+1:height_imdiff-half_window,half_window+1:width_imdiff-half_window);
central_pixels1 = central_pixels1';
central_pixels_vec1 = double(central_pixels1(:));

% for residue image 2
central_pixels2 = imdiff2(half_window+1:height_imdiff-half_window,half_window+1:width_imdiff-half_window);
central_pixels2 = central_pixels2';
central_pixels_vec2 = double(central_pixels2(:));

% compute correlation coefficients
counter = 1;
for kk = 1:1:corr_size
    for jj = 1:1:kk
        if (jj==3)&&(kk==3)
            continue;
        end
        current_pixels1 = imdiff1(jj:height_imdiff-corr_size+jj,kk:width_imdiff-corr_size+kk);
        current_pixels1 = current_pixels1';
        current_pixels_vec1 = double(current_pixels1(:));
        corrs1(1,counter) = corr(central_pixels_vec1,current_pixels_vec1);
        
        current_pixels2 = imdiff2(jj:height_imdiff-corr_size+jj,kk:width_imdiff-corr_size+kk);
        current_pixels2 = current_pixels2';
        current_pixels_vec2 = double(current_pixels2(:));
        corrs2(1,counter) = corr(central_pixels_vec2,current_pixels_vec2);
        
        counter = counter + 1;
    end
end

% combine features from two residue images
corrs_all = [corrs1, corrs2];

% return feature vector
feature_vector = corrs_all;

end
