You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python或Jupyter Notebook中按指定角度及公式旋转对象?

在Python/Jupyter Notebook中按指定角度旋转对象

核心旋转公式

2D平面内,将点$(x, y)$绕原点逆时针旋转$\theta$角度后,新坐标$(x', y')$的计算公式为:
x' = x * cosθ - y * sinθ
y' = x * sinθ + y * cosθ

实现方案

1. 导入依赖库

用numpy处理数值计算,matplotlib在Jupyter中直观展示旋转效果:

import numpy as np
import matplotlib.pyplot as plt

2. 封装旋转函数

基于公式实现通用旋转函数,支持单个点或批量点集:

def rotate_points(points, angle_deg):
    # 角度转弧度(numpy三角函数默认用弧度)
    angle_rad = np.radians(angle_deg)
    # 构造旋转矩阵
    rotation_matrix = np.array([
        [np.cos(angle_rad), -np.sin(angle_rad)],
        [np.sin(angle_rad), np.cos(angle_rad)]
    ])
    # 矩阵乘法完成旋转
    return np.dot(points, rotation_matrix.T)

3. 示例:旋转多边形对象

以正方形为例,旋转后对比原图形:

# 定义中心在原点的正方形顶点
square_vertices = np.array([[1, 1], [-1, 1], [-1, -1], [1, -1], [1, 1]])
# 旋转90度
rotated_square = rotate_points(square_vertices, 90)

# Jupyter中可视化
plt.figure(figsize=(6, 6))
plt.plot(square_vertices[:, 0], square_vertices[:, 1], label='原图形', color='blue')
plt.plot(rotated_square[:, 0], rotated_square[:, 1], label='旋转90度后', color='orange')
plt.axis('equal')  # 保证坐标轴比例一致,避免图形变形
plt.legend()
plt.show()

4. 绕任意点旋转的扩展

如果需要绕非原点的点$(a, b)$旋转,步骤如下:

  • 将所有点的坐标减去$(a, b)$,把旋转中心移到原点
  • 调用上述旋转函数完成旋转
  • 将旋转后的坐标加上$(a, b)$,恢复到原坐标系

示例代码片段:

def rotate_around_point(points, angle_deg, center):
    # 平移到原点
    translated = points - center
    # 旋转
    rotated = rotate_points(translated, angle_deg)
    # 平移回原位置
    return rotated + center

内容的提问来源于stack exchange,提问作者George

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 13:15:34