2

Having two line segments (in the same 2D plane) defined by four endpoints a, b, c, and d how to calculate transformation matrix which will transform first line segment into second?

I found this answer to be almost what I need - I just cant translate it into code.

Community
  • 1
  • 1
vbarbarosh
  • 3,502
  • 4
  • 33
  • 43
  • It would be a different answer depending on whether the line segments are in the same 2D plane or 3D space. If it's the former, it's a simple translation and rotation. If it's the latter, it's a translation and three successive rotations. Those matricies are easily expressed in terms of rotation angles. – duffymo Feb 19 '17 at 14:30
  • Line segments are in the same 2D plane, and scaling is also relevant. – vbarbarosh Feb 19 '17 at 14:43
  • The rotational transformation is unitary, no scaling issue. Use the cross product to calculate the sine of the rotational angle and use it in the rotation matrix: https://en.wikipedia.org/wiki/Rotation_matrix – duffymo Feb 19 '17 at 14:45
  • @duffymo Can you help with the implementation? – vbarbarosh Feb 19 '17 at 15:01
  • Can? Yes. Will I? No. – duffymo Feb 19 '17 at 15:16

2 Answers2

3

Find lengths of segments len_ab, len_cd

translation matrix by (-a.x, -a.y)

rotation matrix by angle

 atan2((d.x-c.x)*(b.y-a.y)-(d.y-c.y)*(b.x-a.x), 
       (d.x-c.x)*(b.x-a.x)+(d.y-c.y)*(b.y-a.y)

scaling by both axes with coefficient len_cd/len_ab

translation by (c.x, c.y)

MBo
  • 77,366
  • 5
  • 53
  • 86
0

assuming the same scale factor on both x,y axises you can: compute rotation angle:

ang = acos(dot(b-a,d-c)/|b-a|*|d-c|)

and scale:

scale = |d-c|/|b-a|

construct 2D homogenuous 3x3 transform matrix with origin = (0,0) then convert a to c' by it and translate by:

translate = d-d'

Another option is to solve this algebraically:

M * p = p'

Where M is 3x3 homogenuous transfrom matrix

    | m0 m1 m2 |
M = | m3 m4 m5 |
    |  0  0  1 | 

The p=(x,y,1) is original point (a,b) and p'=(x,y,w) is transformed point (c,d) so it forms this linear system:

m0.ax + m1.ay + m2 = cx
m3.ax + m4.ay + m5 = cy
m0.bx + m1.by + m2 = dx
m3.bx + m4.by + m5 = dy
m0.ux + m1.uy + m2 = vx
m3.ux + m4.uy + m5 = vy
ux = 0.5*(ax+bx)
uy = 0.5*(ay+by)
vx = 0.5*(cx+dx)
vy = 0.5*(cy+dy)

so just solve the m0,m1,m2,m3,m4,m5 and you have the matrix ...

For more info see:

Community
  • 1
  • 1
Spektre
  • 49,595
  • 11
  • 110
  • 380