在 python 中旋转网格使其与向量平行

rotate a mesh in python to be parallel to a vector

我有两个网格(称为 A 和 B),我在 python 中使用 open3d 库进行交互(很高兴使用 import trimesh 或其他更好的东西)。网格A是曲面结构,网格B近似于平面。

我需要旋转网格,使我感兴趣的表面面向相机。 为了识别我需要的表面,我编写了将网格转换为点云的函数,并为网格 A 创建了最适合的球体,为网格 B 创建了最适合的平面。这些工作非常好并且与对象很好地匹配。

我需要旋转网格,但一直不知道如何执行旋转。

我的输入数据:

对于网格 A: 网格的质心 A 坐标和其最佳拟合球体的坐标(+ 其半径)- 我想旋转网格使其垂直于上述数据描述的向量?

对于网格 B: 网格 B 坐标的质心和最佳拟合平面的法线矢量 - 我想旋转网格,使其垂直于上述数据描述的矢量

我不知道那个库,但也许你可以尝试在 Matplotlib 的 Affine2D() class 中旋转你的对象。

具体来说,试试这个函数: mtransforms.Affine2D().rotate()

首先,您必须导入它:matplotlib.transforms as mtransforms

解决了! 创建了两个向量作为 numpy 数组,向量 1 和向量 2,并找到了 open3d 命令来使网格居中并在两个向量之间应用旋转矩阵。认为这很容易受到万向节锁定的影响,但我无法理解四元数,它对我的​​使用场景来说效果很好。

#this function to create a rotation matrix was taken from 
def rotation_matrix_from_vectors(vec1, vec2):

    a, b = (vec1 / np.linalg.norm(vec1)).reshape(3), (vec2 / np.linalg.norm(vec2)).reshape(3)
    v = np.cross(a, b)
    c = np.dot(a, b)
    s = np.linalg.norm(v)
    kmat = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
    rotation_matrix = np.eye(3) + kmat + kmat.dot(kmat) * ((1 - c) / (s ** 2))
    return rotation_matrix
#to move the mesh to 0,0,0 (using open3d library)
mesh.translate(-mesh.get_center())
# to rotate the mesh to variable vector2, i set it to np.array([0,0,1]) = in line with z axis again using open3d library
mesh.rotate(rotation_matrix_from_vectors(vector1,vector2),center=(0,0,0))