我想要做的是在给定角度上旋转2D numpy数组。我正在采用的方法是使用旋转矩阵。旋转矩阵我定义为:
angle = 65.
theta = (angle/180.) * numpy.pi
rotMatrix = numpy.array([[numpy.cos(theta), -numpy.sin(theta)],
[numpy.sin(theta), numpy.cos(theta)]])
我要旋转的矩阵是成形的(1002,1004)。但是,出于测试目的,我创建了一个形状为(7,6)
的2D数组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]])
现在,当我在2D数组上应用旋转矩阵时,出现以下错误:
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):
我做错了什么?
答案 0 :(得分:7)
矩阵尺寸需要兼容才能获得矩阵产品。您正在尝试将7x6矩阵与2x2矩阵相乘。这在数学上并不一致。将2D旋转应用于2D矢量以获得变换后的坐标才真正有意义。
仅当左手矩阵的列数等于右手矩阵行数时才定义矩阵乘积的结果。
答案 1 :(得分:6)
您似乎在寻找scipy.ndimage.interpolation.rotate或类似内容。如果您特别需要90度,180度或270度旋转(不需要插值),则numpy.rot90会更好。
答案 2 :(得分:1)
您可能需要查看skimage.transform。该模块有几个有用的功能,包括rotation。重写已经完成的事情没有任何意义。
答案 3 :(得分:0)
不能使用二维矩阵旋转任何 ndim 向量。
我没有在 numpy 中找到内置函数。我希望这是一个非常常见的功能,应该在那里。如果你找到了,请告诉我。
同时我有自己的创建功能。
def rotate(vector, theta, rotation_around=None) -> np.ndarray:
"""
reference: https://en.wikipedia.org/wiki/Rotation_matrix#In_two_dimensions
:param vector: list of length 2 OR
list of list where inner list has size 2 OR
1D numpy array of length 2 OR
2D numpy array of size (number of points, 2)
:param theta: rotation angle in degree (+ve value of anti-clockwise rotation)
:param rotation_around: "vector" will be rotated around this point,
otherwise [0, 0] will be considered as rotation axis
:return: rotated "vector" about "theta" degree around rotation
axis "rotation_around" numpy array
"""
vector = np.array(vector)
if vector.ndim == 1:
vector = vector[np.newaxis, :]
if rotation_around is not None:
vector = vector - rotation_around
vector = vector.T
theta = np.radians(theta)
rotation_matrix = np.array([
[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)]
])
output: np.ndarray = (rotation_matrix @ vector).T
if rotation_around is not None:
output = output + rotation_around
return output.squeeze()
if __name__ == '__main__':
angle = 30
print(rotate([1, 0], 30)) # passing one point
print(rotate([[1, 0], [0, 1]], 30)) # passing multiple points