%-------------------------------------------------------------------------
%
% Author: Brandon Smith
% Class: Computer Vision (CS766) -- Fall 2007
% Professor: Li Zhang
% Project 2 - Panoramic Mosaic Stitching
%
% Description:
% p and ptick should be matrices of height 2 and width 4.
% p(1,1) = x1, p(2,1) = y1, p(1,2) = x2, etc...
%
% returns H, the homography -- a 3 x 3 matrix that gets us from
% p to ptick.
%
%-------------------------------------------------------------------------
function [H] = solve_for_homography(p, ptick)

xtick1 = ptick(1,1);
ytick1 = ptick(2,1);
xtick2 = ptick(1,2);
ytick2 = ptick(2,2);
xtick3 = ptick(1,3);
ytick3 = ptick(2,3);
xtick4 = ptick(1,4);
ytick4 = ptick(2,4);

x1 = p(1,1);
y1 = p(2,1);
x2 = p(1,2);
y2 = p(2,2);
x3 = p(1,3);
y3 = p(2,3);
x4 = p(1,4);
y4 = p(2,4);

A = [x1 y1 1 0  0  0 -xtick1*x1 -xtick1*y1 -xtick1; ...
     0  0  0 x1 y1 1 -ytick1*x1 -ytick1*y1 -ytick1; ...
     x2 y2 1 0  0  0 -xtick2*x2 -xtick2*y2 -xtick2; ...
     0  0  0 x2 y2 1 -ytick2*x2 -ytick2*y2 -ytick2; ...
     x3 y3 1 0  0  0 -xtick3*x3 -xtick3*y3 -xtick3; ...
     0  0  0 x3 y3 1 -ytick3*x3 -ytick3*y3 -ytick3; ...
     x4 y4 1 0  0  0 -xtick4*x4 -xtick2*y4 -xtick4; ...
     0  0  0 x4 y4 1 -ytick4*x4 -ytick2*y4 -ytick4];
 
[eigVec, eigVal] = eig(A'*A);

minEigValIndex = 1;
min = eigVal(1,1);
for i=1:9
    if(eigVal(i,i) < min)
        min = eigVal(i,i);
        minEigValIndex = i;
    end
end

h = eigVec(:,minEigValIndex);

H = [h(1) h(2) h(3); h(4) h(5) h(6); h(7) h(8) h(9)];

