您可以使您的VectMath.rotate_x
函数旋转向量数组,然后使用 slice 来获取 & 将数据放入a
:
a = np.array(
[[[ 0.5, 0.5, 50., ],
[ 50.5, 50.5, 100., ],
[ 0.5, 100.5, 50., ],
[ 135. , 90. , 45., ]],
[[ 50.5, 50.5, 100., ],
[ 100.5, 0.5, 50., ],
[ 100.5, 100.5, 50., ],
[ 45. , 90. , 45., ]],
[[ 100.5, 100.5, 50., ],
[ 100.5, 100.5, 0., ],
[ 0.5, 100.5, 50., ],
[ 90. , 0. , 90., ]]])
def rotate_x(v, deg):
r = np.deg2rad(deg)
c = np.cos(r)
s = np.sin(r)
m = np.array([[1, 0, 0],
[0, c,-s],
[0, s, c]])
return np.dot(m, v)
vectors = a[:, :-1, :]
angles = a[:, -1, 0]
for i, (vec, angle) in enumerate(zip(vectors, angles)):
vec_rx = rotate_x(vec.T, angle).T
a[i, :-1, :] = vec_rx
print a
输出:
[[[ 5.00000000e-01 -3.57088924e+01 -3.50017857e+01]
[ 5.05000000e+01 -1.06419571e+02 -3.50017857e+01]
[ 5.00000000e-01 -1.06419571e+02 3.57088924e+01]
[ 1.35000000e+02 9.00000000e+01 4.50000000e+01]]
[[ 5.05000000e+01 -3.50017857e+01 1.06419571e+02]
[ 1.00500000e+02 -3.50017857e+01 3.57088924e+01]
[ 1.00500000e+02 3.57088924e+01 1.06419571e+02]
[ 4.50000000e+01 9.00000000e+01 4.50000000e+01]]
[[ 1.00500000e+02 -5.00000000e+01 1.00500000e+02]
[ 1.00500000e+02 6.15385017e-15 1.00500000e+02]
[ 5.00000000e-01 -5.00000000e+01 1.00500000e+02]
[ 9.00000000e+01 0.00000000e+00 9.00000000e+01]]]
如果有很多三角形,如果我们可以在没有 python for 循环的情况下旋转所有向量,可能会更快。
这里我通过展开矩阵乘积来进行旋转计算:
x' = x
y' = cos(t)*y - sin(t)*z
z' = sin(t)*y + cos(t)*z
所以我们可以向量化这些公式:
a2 = np.array(
[[[ 0.5, 0.5, 50., ],
[ 50.5, 50.5, 100., ],
[ 0.5, 100.5, 50., ],
[ 135. , 90. , 45., ]],
[[ 50.5, 50.5, 100., ],
[ 100.5, 0.5, 50., ],
[ 100.5, 100.5, 50., ],
[ 45. , 90. , 45., ]],
[[ 100.5, 100.5, 50., ],
[ 100.5, 100.5, 0., ],
[ 0.5, 100.5, 50., ],
[ 90. , 0. , 90., ]]])
vectors = a2[:, :-1, :]
angles = a2[:, -1:, 0]
def rotate_x_batch(vectors, angles):
rad = np.deg2rad(angles)
c = np.cos(rad)
s = np.sin(rad)
x = vectors[:, :, 0]
y = vectors[:, :, 1]
z = vectors[:, :, 2]
yr = c*y - s*z
zr = s*y + c*z
vectors[:, :, 1] = yr
vectors[:, :, 2] = zr
rotate_x_batch(vectors, angles)
print np.allclose(a, a2)