【问题标题】:How to test if a matrix is a rotation matrix?如何测试矩阵是否是旋转矩阵?
【发布时间】:2018-12-17 03:07:19
【问题描述】:

我有一个任务来检查一个矩阵是否是一个旋转矩阵,我编写代码如下:

import numpy as np    

def isRotationMatrix(R):
    # some code here
    # return True or False

R = np.array([
    [0, 0, 1],
    [1, 0, 0],
    [0, 1, 0],
])
print(isRotationMatrix(R))  # Should be True
R = np.array([
    [-1, 0, 0],
    [0, 1, 0],
    [0, 0, 1],
])
print(isRotationMatrix(R))  # Should be False

我不知道如何实现函数isRotationMatrix


我的幼稚实现,它只适用于 3x3 矩阵:

def isRotationMatrix(R_3x3):
    should_be_norm_one = np.allclose(np.linalg.norm(R_3x3, axis=0), np.ones(shape=3))
    x = R_3x3[:, 0].ravel()
    y = R_3x3[:, 1].ravel()
    z = R_3x3[:, 2].ravel()
    should_be_perpendicular = \
        np.allclose(np.cross(x, y), z) \
        and np.allclose(np.cross(y, z), x) \
        and np.allclose(np.cross(z, x), y)
    return should_be_perpendicular and should_be_norm_one

【问题讨论】:

  • 不是投反对票的人,但是虽然您的问题标题很明确,但您的“我看了,什么也没找到,请,谢谢”的内容不构成问题。

标签: python numpy rotational-matrices


【解决方案1】:

我正在使用this 定义旋转矩阵。旋转矩阵应满足条件M (M^T) = (M^T) M = Idet(M) = 1。这里M^T表示M的转置,I表示单位矩阵,det(M)表示矩阵M的行列式。

您可以使用以下python代码检查矩阵是否为旋转矩阵。

import numpy as np

''' I have chosen `M` as an example. Feel free to put in your own matrix.'''
M = np.array([[0,-1,0],[1,0,0],[0,0,1]]) 

def isRotationMatrix(M):
    tag = False
    I = np.identity(M.shape[0])
    if np.all((np.matmul(M, M.T)) == I) and (np.linalg.det(M)==1): tag = True
    return tag    

if(isRotationMatrix(M)): print 'M is a rotation matrix.'
else: print 'M is not a rotation matrix.'  

【讨论】:

  • 如果矩阵是方阵,是否可以将条件简化为M(M^T) = Idet(M) = I
  • @MadLee :是的,如果矩阵是方阵,则条件可以简化为M (M^T) = Idet(M) = I。 =)
  • 仅供参考,有时 np.linalg.det(M)==1.0 由于浮点错误而无法工作。
  • @MadLee :尝试使用 np.linalg.det(M)==1 。我改了帖子。
  • 我想你的意思是\det(M)=1,对吧? I 通常是单位矩阵,不是行列式计算的结果。此外,仅当M 描述了正确的旋转时,这才是正确的;它也可以描述一个improper rotation,然后是det(M)=−1
【解决方案2】:

一个旋转矩阵是一个orthonormal matrix,它的行列式应该是1。
我的工具:

import numpy as np


def isRotationMatrix(R):
    # square matrix test
    if R.ndim != 2 or R.shape[0] != R.shape[1]:
        return False
    should_be_identity = np.allclose(R.dot(R.T), np.identity(R.shape[0], np.float))
    should_be_one = np.allclose(np.linalg.det(R), 1)
    return should_be_identity and should_be_one


if __name__ == '__main__':
    R = np.array([
        [0, 0, 1],
        [1, 0, 0],
        [0, 1, 0],
    ])
    print(isRotationMatrix(R))  # True
    R = np.array([
        [-1, 0, 0],
        [0, 1, 0],
        [0, 0, 1],
    ])
    print(isRotationMatrix(R))  # True
    print(isRotationMatrix(np.zeros((3, 2))))  # False

【讨论】:

  • 可能要考虑isRotationMatrix(np.zeros((3, 2))) 应该返回false,而不是errorring。
  • @Eric 谢谢你的建议,我编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
相关资源
最近更新 更多