Affine Transformation matrix for mapping a triangle to another

3.2k Views Asked by At

I'm trying to write a function in Matlab that will give me a matrix T that can be used to multiply points in homogeneous coordinates. This is achieved my mapping a triangle1 to a triangle2 (I'm given 2x3 matrices witch each, and each column is a vertex in 2D).

The way I approached it was by getting each triangle to the origin and placing them in extended matrices (A and B). Then T should be A^-1 * B. I get row reduced of [A | B] which will give me [I | A^-1 * B], then extract the A^-1 * B portion to return as T

This is the code I came up with:

function T = affineMapping(triangle1,triangle2)

v1_x = triangle1(1,1); v1_y = triangle1(2,1); v2_x = triangle1(1,2); v2_y = triangle1(2,2); v3_x = triangle1(1,3); v3_y = triangle1(2,3);

w1_x = triangle2(1,1); w1_y = triangle2(2,1); w2_x = triangle2(1,2); w2_y = triangle2(2,2); w3_x = triangle2(1,3); w3_y = triangle2(2,3);

%Here I go from a basis triangle (1,0), (0,1), (0,0) to triangle 1
A = [ (v1_x - v3_x) (v1_y - v3_y) 0,
      (v2_x - v3_x) (v2_y - v3_y) 0,
      v3_x v3_y 1];

%Here I go from a basis triangle (1,0), (0,1), (0,0) to triangle 2
B = [ (w1_x - w3_x) (w1_y - w3_y) 0,
      (w2_x - w3_x) (w2_y - w3_y) 0,
      w3_x w3_y 1];

T = [A,B];
T = rref(T);
T = [T(:,4), T(:,5), T(:,6)];

When I test it however, it doesn't seem to be correct. I can't pinpoint where I went wrong. Is the math for obtaining T correct?

1

There are 1 best solutions below

0
On BEST ANSWER

Suppose that your linear transformation is $T(p)=Ap$, where $p$ is in homogeneous coordinates. Let $p_i=[t_{1ix},t_{1iy},1]^T$ and $q_i=[t_{2ix},t_{2iy},1]^T$ where $t_{kix}$ and $t_{kiy}$ are the $x$ and $y$ coordinates of vertex $i$ in triangle $k$.

It should be clear that $$ q_1=Ap_1,\ q_2=Ap_2,\ q_3=Ap_3, $$ which can be rewritten in block matrix notation as $$ [q_1,q_2,q_3]=A[p_1,p_2,p_3]. $$ This gives the transformation matrix as $$ A=[q_1,q_2,q_3][p_1,p_2,p_3]^{-1}. $$

Spoiler solution:

The relevant Matlab code, given your inputs, is A=[triangle2;1,1,1]/[triangle1;1,1,1].