简体   繁体   English

用numpy插入角度旋转

[英]interpolating a rotation through an angle with numpy

I have a single point 我有一个

x = ..
y = ..
p = np.matrix([[x],[y]])

and I wish to rotate that point around the origin in increments of d degrees to get N = 360/d points. 我希望以d度为增量围绕原点旋转该点以获得N = 360 / d点。 For example I imagine the following function. 例如,我想象以下功能。

points = interpolate360(d, p)

The shape of points should be (2,N) 点的形状应为(2,N)

I can do the code in a loop using a new rotation matrix for each rotation and then concatenating the results but I was hoping for some kind of vectorized solution. 我可以使用一个新的旋转矩阵为每个旋转循环执行代码,然后将结果串联起来,但是我希望有某种矢量化解决方案。

Using numpy's matrix is probably not the best idea in most settings. 在大多数情况下,使用numpy matrix都不是最好的主意。 One way to solve your problem is creating a 3D array, where [n, :, :] holds the rotation matrix for the n -th angle. 解决问题的一种方法是创建一个3D数组,其中[n, :, :]保存第n个角度的旋转矩阵。 You cannot have a 3D matrix , so it can get messy if you mix array and matrix types and still want to rely on * doing matrix multiplication. 您无法拥有3D matrix ,因此如果您混合使用数组和矩阵类型并且仍然想依靠*进行矩阵乘法,则它会变得混乱。 If you stick with arrays, and np.dot to handle the matrix multiplications predictably, the following code works nicely. 如果您坚持使用数组,并坚持使用np.dot来可预测地处理矩阵乘法,则以下代码可以很好地工作。 It will actually also take a matrix , but first convert it to an ndarray : 它实际上也将使用一个matrix ,但首先将其转换为ndarray

def interpolate360(d, p):
    p = np.array(p)
    angles = np.arange(0, 2 * np.pi, d * np.pi / 180)
    sin = np.sin(angles)
    cos = np.cos(angles)

    rot_matrices = np.empty((angles.shape[0], 2, 2))
    rot_matrices[..., 0, 0] = cos
    rot_matrices[..., 0, 1] = -sin
    rot_matrices[..., 1, 0] = sin
    rot_matrices[..., 1, 1] = cos

    return np.dot(rot_matrices, p)

As the examples below show, this works if your input is a 1D row vector, a 2D single column vector, or a 2D array holding several column vectors: 如下例所示,如果您的输入是一维行向量,二维单列向量或包含多个列向量的二维数组,则此方法有效:

>>> interpolate360(90, [0, 1])
array([[  0.00000000e+00,   1.00000000e+00],
       [ -1.00000000e+00,   6.12323400e-17],
       [ -1.22464680e-16,  -1.00000000e+00],
       [  1.00000000e+00,  -1.83697020e-16]])
>>> interpolate360(90, [[0], [1]])
array([[[  0.00000000e+00],
        [  1.00000000e+00]],

       [[ -1.00000000e+00],
        [  6.12323400e-17]],

       [[ -1.22464680e-16],
        [ -1.00000000e+00]],

       [[  1.00000000e+00],
        [ -1.83697020e-16]]])
>>> interpolate360(90, [[1, 0], [0, 1]])
array([[[  1.00000000e+00,   0.00000000e+00],
        [  0.00000000e+00,   1.00000000e+00]],

       [[  6.12323400e-17,  -1.00000000e+00],
        [  1.00000000e+00,   6.12323400e-17]],

       [[ -1.00000000e+00,  -1.22464680e-16],
        [  1.22464680e-16,  -1.00000000e+00]],

       [[ -1.83697020e-16,   1.00000000e+00],
        [ -1.00000000e+00,  -1.83697020e-16]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM