% Adapted by Anthony Ripa from code writen by Prof Alex Berg

% Demo code for correspondence (part 2)
% Alex Berg aberg@cs.stonybrook.edu


% simple example with least squares
%
% this example maps 1d points (the x values) to 1d points (the y
% values)
%
% for your assignment you will need to find affine mappings between
% 2d points.
%
%

clear all

dname1 = 'pics/source.jpg';
dname2 = 'pics/target.jpg';
I1 = imread(dname1);
I2 = imread(dname2);

figure(1);
clf
axis([0 100 0 100]);
imagesc(I1);
hold on
fprintf('left click on points, right click to stop.\n');
x=[];
y=[];
count=0;
while (1)                             % Round 1
    count=count+1;
  [px,py,pk]=ginput(1); % get click
  if (pk==1),
      x(end+1)=px;
      y(end+1)=py;
      a(count,1) = px;
      a(count,2) = py;
      plot(x(end),y(end),'k.');
  else
      break
  end
end

x=x';
y=y';
a

figure(1);
clf
axis([0 10 0 10]);
imagesc(I2);
hold on
fprintf('left click on points, right click to stop.\n');
count=0;
while (1)                             % Round 2
    count=count+1;
  [px,py,pk]=ginput(1); % get click
  if (pk==1),
      b(count,1) = px;
      b(count,2) = py;
      plot(px,py,'k.');
  else
      break
  end
end

b;

plot(x,y,'k.');  % plot click coordinates


x_hom = [x, ones(size(x,1),1)];
a_hom = [a, ones(size(a,1),1)];

a_hom;

m = x_hom\y; % matrix left divide, try help mldivide

ex = a_hom\b;
ex;                              % this is my transformation matrix

b2 = a_hom * ex;
b2;                    

% plot(x,x_hom*m,'r.-');
for i=1:length(x),
%    plot([x(i) x(i)],[x_hom(i,:)*m y(i)],'b-');
end
% plot(b2(:,1) , b2(:,2),'g');

set(gca, 'position', [0 0 1 1], 'visible', 'off')   
 print('target.png', '-dpng')
pause
[I2,xdata,ydata] = imtransform(I1,maketform('affine', ex))
h = imshow(I2,'XData',xdata,'YData',ydata)
%h = imshow(mask);
a = 0.5; % set transparency of the blocks in the mask
set(h, 'AlphaData', 1);
set(gca, 'position', [0 0 1 1], 'visible', 'off')   
 print('align.png', '-dpng')
pause
set(h, 'AlphaData', a);
set(gca, 'position', [0 0 1 1], 'visible', 'off')   
print('fusion.png', '-dpng')