Python 按指定点旋转坐标点

这段代码定义了两个函数,分别实现二维坐标系中点的逆时针和顺时针旋转。通过输入旋转角度、待旋转点的坐标以及旋转中心点的坐标,可以计算出旋转后的新坐标。示例中展示了顺时针旋转90度后点(-1, 1)的新位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import math
import numpy as np


#逆时针旋转
def Nrotate(angle, valuex, valuey, pointx, pointy):
    valuex = np.array(valuex)
    valuey = np.array(valuey)
    nRotatex = (valuex - pointx) * math.cos(angle) - (valuey - pointy) * math.sin(angle) + pointx
    nRotatey = (valuex - pointx) * math.sin(angle) + (valuey - pointy) * math.cos(angle) + pointy
    return round(nRotatex, 2), round(nRotatey, 2)


#顺时针旋转
def Srotate(angle, valuex, valuey, pointx, pointy):
    valuex = np.array(valuex)
    valuey = np.array(valuey)
    sRotatex = (valuex - pointx) * math.cos(angle) + (valuey - pointy) * math.sin(angle) + pointx
    sRotatey = (valuey - pointy) * math.cos(angle) - (valuex - pointx) * math.sin(angle) + pointy
    return sRotatex, sRotatey


pointx = -1
pointy = 1
#参数(角度,要旋转的点,要绕的点)
sPointx, sPointy = Srotate(math.radians(90), pointx, pointy, 0, 0)
print(sPointx, sPointy)

### 实现 Z 轴旋转使坐标系对准空间指定 对于给定的空间中的某个,可以通过计算该相对于原的角度来构建一个围绕 Z 轴的旋转变换矩阵。此变换将使得新坐标系下的 X-Y 平面对应于原始坐标系下通过该和平行于XOY平面的新平面[^1]。 在 Python 中实现这一功能涉及以下几个方面: #### 计算角度 首先需要确定目标方向向量与当前坐标系之间的夹角。假设有一个指向特定的方向向量 \(\vec{v}=(x,y,z)\),则可以利用反正切函数 `atan2` 来获取所需的角度 θ: \[θ = atan2(y,x)\] 这一步骤确保了即使当 \(x\) 或者 \(y\) 接近零时也能得到正确的象限信息[^4]。 #### 构建旋转矩阵 基于上述计算出的角度 θ ,可以根据标准的二维旋转公式构造对应的三维旋转矩阵 R_z(θ): \[ R_{z}(θ)= \begin{bmatrix} cos⁡(θ)&-sin(θ)&0\\ sin(θ)& cos(θ) &0 \\ 0 & 0 &1 \end{bmatrix} \] 应用这个矩阵将会把任何位于 XOY 平面上的对象按照逆时针方向绕 Z 轴旋转相应角度。 #### 应用于实际数据 一旦有了旋转矩阵,就可以很容易地将其应用于具体的数据集上了。下面是一个简单的例子展示如何使用 NumPy 和 SciPy 完成这项工作: ```python import numpy as np from scipy.spatial.transform import Rotation as Rot def rotate_points_to_align_with_point(points, target_point): """ Rotate points so that the XY plane aligns with a new plane defined by the origin and target point. :param points: Array of shape (N, 3) representing N points in space. :param target_point: A single point represented as an array-like object of length 3. :return: The rotated set of points aligned according to the specified criteria. """ # Calculate angle between original orientation and desired one based on target point's coordinates theta = np.arctan2(target_point[1], target_point[0]) # Create rotation matrix around Z-axis using calculated angle c, s = np.cos(theta), np.sin(theta) rot_matrix = np.array([[c,-s,0], [s,c ,0], [0,0,1]]) # Apply transformation via dot product or equivalent method provided by libraries like Scipy r = Rot.from_matrix(rot_matrix) transformed_points = r.apply(points) return transformed_points ``` 这段代码定义了一个名为 `rotate_points_to_align_with_point` 的函数,它接收一组以及想要对齐的目标作为输入参数,并返回这些经适当旋转后的版本。注意这里的操作是在保持原有坐标的前提下完成的——即只改变了它们的位置而没有改变其相对距离关系[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值