stackoverflow上看到的问题:
I have two vectors as Python lists and an angle. E.g.:
v = [3,5,0]
axis = [4,4,1]
theta = 1.2 #radian
What is the best/easiest way to get the resulting vector when rotating the v vector around the axis?
也就是v沿着axis转1.2弧度,求旋转后向量,发现答案都很复杂。贴个简单的,再加个难度,一般都是很多点。
import numpy as np
from scipy.spatial.transform import Rotation as R
def rot():
v=[3, 5, 0]
v=np.asarray([v,v])
axis=[4, 4, 1]
theta=1.2 # radian
a=np.asarray(axis)
b=a/np.linalg.norm(a)
r=R.from_rotvec(theta * b)
m=r.as_matrix()
c=np.matmul(m,v.T)
print(c.T)
结果:[2.74911638 4.77180932 1.91629719] 和得票最多回答一样。
补充一个四元数的方法,网上太多说四元数,从数学角度说的很复杂,从使用角度,这个工具就是来解决旋转的,那么还是上面的例子,
import numpy as np
from scipy.spatial.transform import Rotation as R
v = [3, 5, 0]
v = np.asarray([v, v])
# v = np.asarray(v)
axis = np.asarray([4, 4, 1])
theta = 1.2 # radian
def rot():
b = axis / np.linalg.norm(axis)
r = R.from_rotvec(theta * b)
m = r.as_matrix()
c = np.matmul(m, v.T)
print("旋转轴结果==", c.T)
def quat():
b = axis / np.linalg.norm(axis)
quat = np.append(np.sin(theta / 2) * b, [np.cos(theta / 2)])
r = R.from_quat(quat)
m = r.as_matrix()
c = np.matmul(m, v.T)
print("四元数结果===", c.T)
两种结果完全一样 注意四元数是如何构造的,先把旋转轴归一,然后实部在后面(这个和数学习惯不一样)