我已经用这个把头撞了好几个小时了,我似乎不知道我做错了什么。在
我正在尝试生成一个旋转矩阵,它将向量与一个特定的轴对齐(我最终将转换更多的数据,因此拥有旋转矩阵非常重要)。在
我觉得我的方法是对的,如果我在各种向量上测试它,它的效果很好,但是转换后的向量总是有点偏离。在
下面是我用来测试方法的完整代码示例:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import matplotlib as mpl
def get_rotation_matrix(i_v, unit=None):
# From http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q38
if unit is None:
unit = [1.0, 0.0, 0.0]
# Normalize vector length
i_v = np.divide(i_v, np.sqrt(np.dot(i_v, i_v)))
# Get axis
u, v, w = np.cross(i_v, unit)
# Get angle
phi = np.arccos(np.dot(i_v, unit))
# Precompute trig values
rcos = np.cos(phi)
rsin = np.sin(phi)
# Compute rotation matrix
matrix = np.zeros((3, 3))
matrix[0][0] = rcos + u * u * (1.0 - rcos)
matrix[1][0] = w * rsin + v * u * (1.0 - rcos)
matrix[2][0] = -v * rsin + w * u * (1.0 - rcos)
matrix[0][1] = -w * rsin + u * v * (1.0 - rcos)
matrix[1][1] = rcos + v * v * (1.0 - rcos)
matrix[2][1] = u * rsin + w * v * (1.0 - rcos)
matrix[0][2] = v * rsin + u * w * (1.0 - rcos)
matrix[1][2] = -u * rsin + v * w * (1.0 - rcos)
matrix[2][2] = rcos + w * w * (1.0 - rcos)
return matrix
# Example Vector
origv = np.array([0.47404573, 0.78347482, 0.40180573])
# Compute the rotation matrix
R = get_rotation_matrix(origv)
# Apply the rotation matrix to the vector
newv = np.dot(origv.T, R.T)
# Get the 3D figure
fig = plt.figure()
ax = fig.gca(projection='3d')
# Plot the original and rotated vector
ax.plot(*np.transpose([[0, 0, 0], origv]), label="original vector", color="r")
ax.plot(*np.transpose([[0, 0, 0], newv]), label="rotated vector", color="b")
# Plot some axes for reference
ax.plot([0, 1], [0, 0], [0, 0], color='k')
ax.plot([0, 0], [0, 1], [0, 0], color='k')
ax.plot([0, 0], [0, 0], [0, 1], color='k')
# Show the plot and legend
ax.legend()
plt.show()
我已链接找到方法here。为什么它产生的变换总是有一点偏差???在
您需要规范
uvw
才能使其正常工作。所以更换u,v,w=np.交叉(i\U v,单位)
与
这基本上与您已经拥有的
i_v = np.divide(i_v, np.sqrt(np.dot(i_v, i_v)))
行相同。在但你可以做得更好,完全避免trig:
^{pr2}$最后一个表达式来自维基百科页面:
相关问题 更多 >
编程相关推荐