%learning script for the NL predictor
%uses 6 images as training set
%stores the coefficients in NLcoeffs

image1 = double(imread('man.tif'));
image2 = double(imread('elaine.tif'));
image3 = double(imread('boats512x512.tif'));
image3 = double(imread('harbour512x512.tif'));
image4 = double(imread('bridge512x512.tif'));
image5 = double(imread('peppers512x512.tif'));
image6 = double(imread('airfield512x512.tif'));

image = [image1 image2 image3; image4 image5 image6];
%image = [image1'];
[row col] = size(image);

simage = reduceFunc(image, 'opt_NL');
dimage1 = image(1:2:row, 1:2:col);
dimage2 = image(2:2:row, 1:2:col);
dimage3 = image(1:2:row, 2:2:col);
dimage4 = image(2:2:row, 2:2:col);

part = partition(simage);
%part = zeros(size(simage));

M1lin = zeros([300 17]);
M2lin = zeros([300 17]);
M3lin = zeros([300 17]);
M4lin = zeros([300 17]);

if(0)
   M1lin = optimalNLPredictor(dimage1, simage, zeros(size(simage)));
   M2lin = optimalNLPredictor(dimage2, simage, zeros(size(simage)));
   M3lin = optimalNLPredictor(dimage3, simage, zeros(size(simage)));
   M4lin = optimalNLPredictor(dimage4, simage, zeros(size(simage)));
end
if(1)
   M1 = optimalNLPredictor(dimage1, simage, part, M1lin);
   M2 = optimalNLPredictor(dimage2, simage, part, M2lin);
   M3 = optimalNLPredictor(dimage3, simage, part, M3lin);
   M4 = optimalNLPredictor(dimage4, simage, part, M4lin);
end


figure(1);
rimage1 = NLpredictor(simage, M1, part);
imshow(rimage1/256);
variance(dimage1-rimage1)

figure(2);
rimage2 = NLpredictor(simage, M2, part);
imshow(rimage2/256);
variance(dimage2-rimage2)

figure(3);
rimage3 = NLpredictor(simage, M3, part);
imshow(rimage3/256);
variance(dimage3-rimage3)

figure(4);
rimage4 = NLpredictor(simage, M4, part);
imshow(rimage4/256);
variance(dimage4-rimage4)

rimage = zeros([row col]);
rimage(1:2:row, 1:2:col) = rimage1;
rimage(2:2:row, 1:2:col) = rimage2;
rimage(1:2:row, 2:2:col) = rimage3;
rimage(2:2:row, 2:2:col) = rimage4;

figure(5);
imshow(rimage/256);

variance(image - rimage)

clear NLcoeffs
NLcoeffs(:,:,1) = M1;
NLcoeffs(:,:,2) = M2;
NLcoeffs(:,:,3) = M3;
NLcoeffs(:,:,4) = M4;

