将numpy坐标数组旋转45度

j2datikz  于 2023-01-13  发布在  其他
关注(0)|答案(1)|浏览(249)

我有一个2x32的numpy数组,包含x,y坐标A,我想把它旋转45度,绕着中心旋转.

x = np.tile([1,2,3,4],8)
y = np.repeat([1,2,3,4,5,6,7,8],4)
A = np.vstack((x,y)) # just a quick example

有没有一个快速简便的方法来做到这一点?

j0pj023g

j0pj023g1#

步骤:
1.使用平移使数据在原点居中
1.围绕原点旋转数据(顺时针旋转45度=-pi/4弧度)
1.将数据转换回原始中心
使用一些线性代数:

import numpy as np

x = np.tile([1,2,3,4],8)
y = np.repeat([1,2,3,4,5,6,7,8],4)
A = np.vstack((x,y)) # just a quick example

# Rotation matrix as in e.g. https://en.wikipedia.org/wiki/Rotation_matrix
theta = -np.pi / 4
rotate = np.array([
    [np.cos(theta), -np.sin(theta)],
    [np.sin(theta),  np.cos(theta)]
])

# Translation vector is the mean of all xs and ys. 
translate = A.mean(axis=1, keepdims=True)

应用变换:

out = A - translate    # Step 1
out = rotate @ out     # Step 2
out = out + translate  # Step 3

相关问题