Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy matrix combination

I have a rotation matrix and translation vector as corresponding numpy objects. What is the best way to combine them into a 4x4 transform matrix? Are there any functions which allow to avoid dummy element-wise copying?

like image 993
Andy Silver Avatar asked Nov 02 '15 15:11

Andy Silver


1 Answers

There are many ways to do this; here are two.

You can create an empty 4x4 array. Then the rotation matrix and the translation vector can each be copied into the 4x4 transform matrix with slice assignment. For example, R and t are the rotation matrix and translation vector, respectively.

In [23]: R
Out[23]: 
array([[ 0.51456517, -0.25333656,  0.81917231],
       [ 0.16196059,  0.96687621,  0.19727939],
       [-0.8420163 ,  0.03116053,  0.53855136]])

In [24]: t
Out[24]: array([ 1. ,  2. ,  0.5])

Create an empty 4x4 array M, and fill it with R and t.

In [25]: M = np.empty((4, 4))

In [26]: M[:3, :3] = R

In [27]: M[:3, 3] = t

In [28]: M[3, :] = [0, 0, 0, 1]

In [29]: M
Out[29]: 
array([[ 0.51456517, -0.25333656,  0.81917231,  1.        ],
       [ 0.16196059,  0.96687621,  0.19727939,  2.        ],
       [-0.8420163 ,  0.03116053,  0.53855136,  0.5       ],
       [ 0.        ,  0.        ,  0.        ,  1.        ]])

Or you can assemble the transform matrix with functions such as numpy.hstack and numpy.vstack:

In [30]: M = np.vstack((np.hstack((R, t[:, None])), [0, 0, 0 ,1]))

In [31]: M
Out[31]: 
array([[ 0.51456517, -0.25333656,  0.81917231,  1.        ],
       [ 0.16196059,  0.96687621,  0.19727939,  2.        ],
       [-0.8420163 ,  0.03116053,  0.53855136,  0.5       ],
       [ 0.        ,  0.        ,  0.        ,  1.        ]])

Note that t[:, None] (which could also be spelled t[:, np.newaxis] or t.reshape(-1, 1)) creates a 2-d view of t with shape (3, 1). This makes the shape compatible with M in the call to np.hstack.

In [55]: t[:, None]
Out[55]: 
array([[ 1. ],
       [ 2. ],
       [ 0.5]])
like image 60
Warren Weckesser Avatar answered Nov 16 '22 08:11

Warren Weckesser