Python中绕指定点旋转(及平移)点集的最优方法与示例
Python实现点集绕指定点旋转的方法
一、纯Numpy实现(无额外依赖)
这是最轻量化的方案,无需安装额外库,核心通过平移-旋转-平移三步完成:
- 将所有点坐标减去旋转中心,把旋转中心移至原点
- 应用旋转矩阵计算旋转后的坐标
- 将旋转后的坐标加回旋转中心,恢复到原坐标系
代码示例
import numpy as np import matplotlib.pyplot as plt def rotate_points(points, center, angle_deg): # 角度转弧度 angle_rad = np.deg2rad(angle_deg) # 定义旋转矩阵(逆时针为正方向) rot_matrix = np.array([ [np.cos(angle_rad), -np.sin(angle_rad)], [np.sin(angle_rad), np.cos(angle_rad)] ]) # 平移到原点 → 旋转 → 平移回原中心 translated = points - center rotated = translated @ rot_matrix return rotated + center # 生成测试点集 original_points = np.array([[1,2], [2,3], [3,2], [2,1]]) # 指定旋转中心与角度 rotate_center = np.array([2,2]) rotate_angle = 90 # 逆时针旋转90度 # 计算旋转后的点 rotated_points = rotate_points(original_points, rotate_center, rotate_angle) # 绘图对比 plt.figure(figsize=(8,6)) plt.scatter(original_points[:,0], original_points[:,1], label='原点点集', color='blue') plt.scatter(rotated_points[:,0], rotated_points[:,1], label='旋转后点集', color='red') plt.scatter(rotate_center[0], rotate_center[1], label='旋转中心', color='green', marker='*', s=150) plt.legend() plt.axis('equal') # 保持坐标轴比例,避免旋转后图形变形 plt.grid(True) plt.show()
二、使用Shapely实现(简洁几何操作)
如果需要处理更复杂的几何对象,Shapely的affinity.rotate函数可以直接对MultiPoint等对象执行旋转,无需手动处理矩阵,代码更简洁。
代码示例
import numpy as np import matplotlib.pyplot as plt from shapely.geometry import MultiPoint from shapely.affinity import rotate # 生成测试点集 original_points = [(1,2), (2,3), (3,2), (2,1)] # 转为Shapely的MultiPoint对象 multi_point = MultiPoint(original_points) # 指定旋转中心与角度(默认逆时针为正,负号表示顺时针) rotate_center = (2,2) rotate_angle = -90 # 顺时针旋转90度 # 执行旋转 rotated_multi_point = rotate(multi_point, rotate_angle, origin=rotate_center) # 提取坐标用于绘图 original_coords = np.array(multi_point.xy).T rotated_coords = np.array(rotated_multi_point.xy).T # 绘图对比 plt.figure(figsize=(8,6)) plt.scatter(original_coords[:,0], original_coords[:,1], label='原点点集', color='blue') plt.scatter(rotated_coords[:,0], rotated_coords[:,1], label='旋转后点集', color='red') plt.scatter(rotate_center[0], rotate_center[1], label='旋转中心', color='green', marker='*', s=150) plt.legend() plt.axis('equal') plt.grid(True) plt.show()
关键注意事项
- 角度方向:两种实现默认逆时针为正角度,顺时针旋转传入负角度即可
- 坐标轴比例:绘图时必须添加
plt.axis('equal'),否则旋转后的图形会因坐标轴比例失衡变形 - 多中心测试:只需修改
rotate_center变量,重复调用旋转函数即可快速对比不同旋转中心的效果
内容的提问来源于stack exchange,提问作者KansaiRobot
相关产品推荐
相关产品推荐

