Skip to main content
 首页 » 编程设计

python之将旋转矩阵应用于 xy 坐标

2024年12月31日8lvdongjie

我有 xy 坐标表示给定空间上的主题。它是从另一个点引用的,因此偏离中心。在 longitudinal 中,axes 未沿 x 轴 对齐。

下面随机生成的 ellipse 表明了这一点:

import numpy as np 
from matplotlib.pyplot import scatter 
 
xx = np.array([-0.51, 51.2]) 
yy = np.array([0.33, 51.6]) 
means = [xx.mean(), yy.mean()]   
stds = [xx.std() / 3, yy.std() / 3] 
corr = 0.8         # correlation 
covs = [[stds[0]**2          , stds[0]*stds[1]*corr],  
    [stds[0]*stds[1]*corr,           stds[1]**2]]  
 
m = np.random.multivariate_normal(means, covs, 1000).T 
scatter(m[0], m[1]) 

为了拉直坐标,我考虑将矢量应用于旋转矩阵。

这样的东西行得通吗?

angle = 65. 
theta = (angle/180.) * np.pi 
 
rotMatrix = np.array([[np.cos(theta), -np.sin(theta)],  
                     [np.sin(theta),  np.cos(theta)]]) 

这似乎也是一个愚蠢的问题,但是有没有办法确定 xy 坐标的结果 vector 是否垂直?还是您只需要尝试使用旋转角度?

请您参考如下方法:

您可以使用 sklearn.decomposition.PCA (主成分分析)使用 n_components=2 提取旋转点云所需的最小角度,使其主轴水平。

可运行的例子

import numpy as np 
import matplotlib.pyplot as plt 
from sklearn.decomposition import PCA 
 
np.random.seed(1) 
 
xx = np.array([-0.51, 51.2]) 
yy = np.array([0.33, 51.6]) 
means = [xx.mean(), yy.mean()]   
stds = [xx.std() / 3, yy.std() / 3] 
corr = 0.8         # correlation 
covs = [[stds[0]**2,       stds[0]*stds[1]*corr],  
        [stds[0]*stds[1]*corr, stds[1]**2]] 
 
m = np.random.multivariate_normal(means, covs, 1000) 
 
pca = PCA(2) 
 
# This was in my first answer attempt: fit_transform works fine, but it randomly  
# flips (mirrors) points across one of the principal axes. 
# m2 = pca.fit_transform(m) 
 
# Workaround: get the rotation angle from the PCA components and manually  
# build the rotation matrix. 
 
# Fit the PCA object, but do not transform the data 
pca.fit(m) 
 
# pca.components_ : array, shape (n_components, n_features) 
# cos theta 
ct = pca.components_[0, 0] 
# sin theta 
st = pca.components_[0, 1] 
 
# One possible value of theta that lies in [0, pi] 
t = np.arccos(ct) 
 
# If t is in quadrant 1, rotate CLOCKwise by t 
if ct > 0 and st > 0: 
    t *= -1 
# If t is in Q2, rotate COUNTERclockwise by the complement of theta 
elif ct < 0 and st > 0: 
    t = np.pi - t 
# If t is in Q3, rotate CLOCKwise by the complement of theta 
elif ct < 0 and st < 0: 
    t = -(np.pi - t) 
# If t is in Q4, rotate COUNTERclockwise by theta, i.e., do nothing 
elif ct > 0 and st < 0: 
    pass 
 
# Manually build the ccw rotation matrix 
rotmat = np.array([[np.cos(t), -np.sin(t)],  
                   [np.sin(t),  np.cos(t)]]) 
 
# Apply rotation to each row of m 
m2 = (rotmat @ m.T).T 
 
# Center the rotated point cloud at (0, 0) 
m2 -= m2.mean(axis=0) 
 
fig, ax = plt.subplots() 
plot_kws = {'alpha': '0.75', 
            'edgecolor': 'white', 
            'linewidths': 0.75} 
ax.scatter(m[:, 0], m[:, 1], **plot_kws) 
ax.scatter(m2[:, 0], m2[:, 1], **plot_kws) 

输出

警告:pca.fit_transform() 有时会翻转(镜像)点云

主要成分可以随机显示为正数或负数。在某些情况下,您的点云可能看起来上下颠倒,甚至在其主轴之一上镜像。 (要对此进行测试,请更改随机种子并重新运行代码,直到您观察到翻转。)有一个深入的讨论 here (基于 R,但数学是相关的)。要纠正此问题,您必须将 fit_transform 行替换为手动翻转一个或两个分量的符号,然后将符号翻转后的分量矩阵乘以点云数组。