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

如何对2D矩形进行旋转、平移与缩放?(Python实现)

2D矩形坐标变换:旋转、平移、缩放的优雅实现

以下是针对需求优化后的完整代码,结合numpy的矩阵运算实现高效且简洁的坐标变换:

import matplotlib.pyplot as plt
import numpy as np

# 原始矩形坐标点(最后一个点与第一个点重合,用于绘图闭合)
original_points = np.array([
    [2, 1],
    [8, 1],
    [8, 4],
    [2, 4],
    [2, 1]
])

# 1. 按比例缩放(缩放因子2)
scale_factor = 2
scaled_points = original_points * scale_factor

# 2. 平移(X方向+1,Y方向+10)
translation = np.array([1, 10])
translated_points = scaled_points + translation

# 3. 顺时针旋转指定角度(示例:绕矩形自身中心旋转30度)
def rotate_points(points, angle_deg):
    # 将角度转换为弧度
    angle_rad = np.radians(angle_deg)
    # 顺时针旋转矩阵
    rot_matrix = np.array([
        [np.cos(angle_rad), np.sin(angle_rad)],
        [-np.sin(angle_rad), np.cos(angle_rad)]
    ])
    # 提取核心坐标点(排除最后一个重复的闭合点)
    core_points = points[:-1]
    # 计算矩形中心坐标
    center = np.mean(core_points, axis=0)
    # 三步旋转操作:平移到原点→旋转→平移回原中心
    rotated_core = (core_points - center) @ rot_matrix + center
    # 拼接闭合点,保持图形完整性
    rotated_points = np.vstack([rotated_core, rotated_core[0]])
    return rotated_points

rotated_points = rotate_points(original_points, 30)

# 绘图展示所有变换效果
plt.figure(figsize=(10, 8))
plt.plot(original_points[:, 0], original_points[:, 1], label='原始矩形', linestyle='-', color='blue')
plt.plot(scaled_points[:, 0], scaled_points[:, 1], label='缩放后', linestyle='--', color='green')
plt.plot(translated_points[:, 0], translated_points[:, 1], label='平移后', linestyle='-.', color='orange')
plt.plot(rotated_points[:, 0], rotated_points[:, 1], label='顺时针旋转30度后', linestyle=':', color='red')

plt.xlabel('X坐标')
plt.ylabel('Y坐标')
plt.title('2D矩形坐标变换效果')
plt.legend()
plt.grid(True)
plt.axis('equal')  # 保持坐标轴比例一致,避免图形变形
plt.show()

关键优化与原理说明

1. 坐标存储优化

将分散的x、y列表合并为numpy二维数组,每个点对应数组的一行,x、y为两列。这种结构能利用numpy的广播机制,一次性对所有点执行变换,避免逐个修改元素的冗余操作。

2. 缩放的正确实现

原代码手动修改部分点坐标会导致矩形变形,正确做法是对所有点的x、y同时乘以缩放因子:

scaled_points = original_points * scale_factor

numpy会自动对数组内每个元素执行乘法,无需循环或逐个修改。

3. 平移的优雅实现

利用numpy广播特性,直接给所有点加上平移向量即可:

translated_points = scaled_points + translation

相比列表推导,这种写法更简洁高效,尤其适合大量坐标点的场景。

4. 顺时针旋转的核心逻辑

旋转的关键是旋转矩阵和旋转中心:

  • 顺时针旋转α度的旋转矩阵为:
    [cosα   sinα]
    [-sinα  cosα]
    
  • 若直接绕原点旋转,矩形会偏离原位置,通常选择绕自身中心旋转,步骤为:
    1. 将所有点平移到原点(减去矩形中心坐标)
    2. 用旋转矩阵执行旋转
    3. 将旋转后的点平移回原中心位置

封装的rotate_points函数自动处理上述流程,同时保留了矩形的闭合点,确保绘图时图形完整。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:45:51