% Credit for this script goes to xcorr.net
% the script was essentially taken from https://xcorr.net/2011/05/27/whiten-a-matrix-matlab-code/


%% create Pool

pool=parpool();

%% Load Data
imgPath = ''; %path to the folder where the images are found
imgType = '*.png'; % change based on image type

[nonWhite, fileNames] = loadImages(imgPath, imgType);
%% Process Data

mX = bsxfun(@minus,nonWhite,mean(nonWhite)); %remove mean
fX = fft(fft(mX,[],2),[],3); %fourier transform of the images
spectr = sqrt(mean(abs(fX).^2)); %Mean spectrum
wX = ifft(ifft(bsxfun(@times,fX,1./spectr),[],2),[],3); %whitened X



disp('Whitening complete')

%% Get correct output format

rwX = real(wX);

rwX=rwX-min(rwX(:)); % shift data such that the smallest element of A is 0

rwX=rwX/max(rwX(:)); % normalize the shifted data to 1

disp('Correct output format')
%% Save Data
writePath = ''; % provide output path here

parfor idx = 1:length(occlFileNames)
   imwrite(reshape(rwX(idx,:,:), [16, 64]), [writePath fileNames{idx}]);
end

disp('Writing complete')

delete(pool);
