%%
close all
index = 'marui2';
index0 = index;
image_path = [pwd '\'];
img_list=dir([image_path,index]);
Demo0
points = data(1).points;

save([index '-points66.mat'],'points')
save([index0 '-points66.mat'],'points')

testpoints = load('data-points66.mat');
testpoints = testpoints.points;
meanpoints = load([index '-points66.mat']);
% meanpoints = load('123.jpg-warp.png-points66.mat');
meanpoints = meanpoints.points;
Ta = testpoints;
Ta(:,3)= 1;
Ma = meanpoints;
Ma(:,3) = 1;
lossmin = 100000;
Abest = zeros(3);
for iter =1:100
    a=randperm(66);
    a = a(1:3);
    testp = testpoints(a,:);
    meanp = meanpoints(a,:);
    T = testp;
    T(:,3)= 1;
    M = meanp;
    M(:,3) = 1;
    A = M\T;
    loss = (Ma*A-Ta);
    loss = abs(loss);
    loss = sum(loss(:))
    if loss<lossmin
        lossmin=loss;
        Abest = A;
    end
end
save([index0 '-Abest.mat'],'Abest');


meanface = imread([image_path,index]);
meanface = im2double(meanface);
imwrite(meanface, [index0 '-meanface.bmp']);


meanface=imread([index0 '-meanface.bmp']);
meanface = im2double(meanface);
[s1 s2 s3]=size(meanface);
if s1 <200 ||s2<200
    meanface= imresize(meanface,max(ceil(200/s1),ceil(200/s2)));
end

testface = imread(['syntheticface.png']);
testface = im2double(testface);
warpmean = testface;
warpmean(:,:,:)=0;
mask = testface(:,:,1)>0;
% mask(:,:)=1;
% warpnormal = warpmean;
% tic
[m1 m2]=size(mask)
[s1 s2 s3] = size(meanface);
for ii=1:m1
    for jj=1:m2
        if mask(ii,jj) ==1
            T = [jj,ii,1];
            M = T/Abest
            
%             M = [jj,ii,1];
%             T = (M)*inv(Abest)
%             T = T./T(3);
% if T(1)>0&&T(2)>0
if ceil(M(2))<s1 && ceil(M(1))<s2&&ceil(M(2))>0&&ceil(M(1))>0
            warpmean(ii,jj,:) = meanface(ceil(M(2)),ceil(M(1)),:);
%             warpnormal(ceil(T(2)),ceil(T(1)),:) = meannormal(ii,jj,:);
end
        end
    end
end
% toc
figure,imshow(warpmean)
img = warpmean;
mask = img(:,:,1)~=0;
        img1 = reshape(img,[90000 3]);
%         imgmean = sum(img1(:))/sum(mask(:))/3;
        imgmean = sum(img1,1)/sum(mask(:));
        img1 = img1-repmat(imgmean,[90000 1]);
%         img1 = img1-repmat(imgmean,[90000 3]);
        img1= reshape(img1,[300 300 3]);
        img1 = img1./max(img1(:));
        imwrite(img, [index0 '-warp.bmp']);
        imwrite(img1,[index0 '-meannorm.bmp'])