function tform = GetTransform( p1, p2, normalize )
%Code written by Jim Patrick for project 2 in CEG725 2/16/2009
%GetTransform computes the 3X3 projective transformation matrix based on
%the provided match points.  At least 4 points are needed.

[m n] = size(p1);
zero = zeros(n,1);  one = ones(n,1);

if normalize, [k1,p1] = Normalize(p1); [k2,p2]=Normalize(p2); end

A = [p1(1,:)' p1(2,:)' one  zero     zero     zero -p2(1,:)'.*p1(1,:)' -p2(1,:)'.*p1(2,:)'; ...
	 zero     zero     zero p1(1,:)' p1(2,:)' one   -p2(2,:)'.*p1(1,:)'  -p2(2,:)'.*p1(2,:)'];
b = [p2(1,:)'; p2(2,:)'];

if rank(A) < 8
    tform = eye(3,3);
else
    tform = reshape([A\b; 1], [3 3])'; %transpose because matlab is column major
    if normalize, tform=inv(k2)*tform*k1; end
end
tform = tform/tform(3,3);
end
