Skip to main content
 首页 » 编程设计

python之如何使用 transformations.py 旋转一个点

2024年10月24日15fff_TT

如何使用流行的 transformations.py library绕轴旋转一个点?

我试图将一个点绕 z 轴旋转 90 度,但我没有得到预期的结果,尽管该文件的文档有几个创建变换矩阵的示例,但实际上并没有说明如何使用这些矩阵来应用转换。我的代码是:

from math import pi 
import transformations as tf 
import numpy as np 
 
alpha, beta, gamma = 0, 0, pi/2. 
origin, xaxis, yaxis, zaxis = (0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1) 
Rx = tf.rotation_matrix(alpha, xaxis) 
Ry = tf.rotation_matrix(beta, yaxis) 
Rz = tf.rotation_matrix(gamma, zaxis) 
R = tf.concatenate_matrices(Rx, Ry, Rz) 
 
point0 = np.array([[0, 1, 0, 0]]) 
 
point1 = R * point0 
#point1 = R * point0.T # same result 
#point1 = np.multiply(R, point0) # same result 
#point1 = np.multiply(R, point0.T) # same result 
point1_expected = np.array([[1, 0, 0, 0]]) 
 
assert point1.tolist() == point1_expected.tolist() # this fails 

计算 point1 为:

[[  0.00000000e+00  -1.00000000e+00   0.00000000e+00   0.00000000e+00] 
 [  0.00000000e+00   6.12323400e-17   0.00000000e+00   0.00000000e+00] 
 [  0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00] 
 [  0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00]] 

这对我来说毫无意义。将一个 4x4 矩阵乘以一个 4x1 矩阵应该得到一个 4x1,而不是另一个 4x4。我做错了什么?

请您参考如下方法:

transformations.py 使用 np.array 对象,而不是 np.matrix,即使在 whatever_matrix 中也是如此功能。 (这是一件好事,因为 np.matrix 太可怕了。)您需要使用 dot 进行矩阵乘法:

point1 = R.dot(point0) 

此外,出于某种原因,您已将 point0 设为行向量。它应该是列向量或普通的一维向量:

point0 = np.array([0, 1, 0, 0])