Python 使用旋转矩阵在一个角度上旋转 2D 阵列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20840692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:20:45  来源:igfitidea点击:

Rotation of a 2D array over an angle using rotation matrix

pythonarraysmatrixrotation2d

提问by The Dude

What I want to do is to rotate a 2D numpy array over a given angle. The approach I'm taking is using a rotation matrix. The rotation matrix I defined as:

我想要做的是在给定的角度旋转 2D numpy 数组。我采用的方法是使用旋转矩阵。我定义的旋转矩阵为:

angle = 65.
theta = (angle/180.) * numpy.pi

rotMatrix = numpy.array([[numpy.cos(theta), -numpy.sin(theta)], 
                         [numpy.sin(theta),  numpy.cos(theta)]])

The matrix I want to rotate is shaped (1002,1004). However, just for testing purposes I created a 2D array with shape (7,6)

我要旋转的矩阵的形状为 (1002,1004)。但是,仅出于测试目的,我创建了一个形状为 (7,6) 的二维数组

c = numpy.array([[0,0,6,0,6,0], [0,0,0,8,7,0], [0,0,0,0,5,0], [0,0,0,3,4,0], [0,0,2,0,1,0], [0,8,0,0,9,0], [0,0,0,0,15,0]])

Now, when I apply the rotation matrix on my 2D array I get the following error:

现在,当我在二维数组上应用旋转矩阵时,出现以下错误:

c = numpy.dot(rotMatrix, c)
print c

c = numpy.dot(rotMatrix, c)
ValueError: matrices are not aligned
Exception in thread Thread-1 (most likely raised during interpreter shutdown):

What am I doing wrong?

我究竟做错了什么?

采纳答案by mathematician1975

Matrix dimensions will need to be compatible in order to obtain a matrix product. You are trying to multiply a 7x6 matrix with a 2x2 matrix. This is not mathematically coherent. It only really makes sense to apply a 2D rotation to a 2D vector to obtain the transformed coordinates.

矩阵维度需要兼容才能获得矩阵乘积。您正在尝试将 7x6 矩阵与 2x2 矩阵相乘。这在数学上是不连贯的。将 2D 旋转应用于 2D 矢量以获得变换后的坐标才真正有意义。

The result of a matrix product is defined only when the left hand matrix has column count equal to right hand matrix row count.

仅当左侧矩阵的列数等于右侧矩阵的行数时,才定义矩阵乘积的结果。

回答by veda905

You may want to look at skimage.transform. This module has several useful functions including rotation. No sense in rewriting something that is already done.

你可能想看看skimage.transform。这个模块有几个有用的功能,包括旋转。重写已经完成的事情是没有意义的。

回答by hawkjo

You seem to be looking for scipy.ndimage.interpolation.rotate, or similar. If you specifically want 90, 180, or 270 degree rotations, which do not require interpolation, then numpy.rot90is better.

您似乎正在寻找scipy.ndimage.interpolation.rotate或类似内容。如果你特别想要 90、180 或 270 度旋转,不需要插值,那么numpy.rot90更好。