python如何实现数据集中每点绕某定点旋转一定角度
在 Python 中,可以使用二维旋转矩阵来让文件中的数据集绕某定点旋转相同的角度。假设数据集文件中包含一系列点的坐标(如 x, y),可以按照以下步骤进行旋转:
步骤
- 读取 .txt 文件 并解析坐标数据(假设数据集放在一个txt文件中)。
- 应用旋转变换:计算相对旋转中心的坐标。使用旋转矩阵进行计算:
- 将变换后的数据写回 .txt 文件。
示例代码:
import numpy as np
def rotate_point(x, y, xc, yc, angle):
"""绕 (xc, yc) 旋转点 (x, y) 角度 angle(角度制)"""
theta = np.radians(angle) # 角度转换为弧度
cos_theta, sin_theta = np.cos(theta), np.sin(theta)
# 计算旋转后的新坐标
x_new = xc + (x - xc) * cos_theta - (y - yc) * sin_theta
y_new = yc + (x - xc) * sin_theta + (y - yc) * cos_theta
return x_new, y_new
def rotate_txt_file(input_file, output_file, xc, yc, angle):
"""读取 txt 文件,旋转所有点,并写入新的 txt 文件"""
with open(input_file, 'r') as f:
lines = f.readlines()
rotated_points = []
for line in lines:
if line.strip(): # 确保不是空行
x, y = map(float, line.split()) # 解析坐标
x_new, y_new = rotate_point(x, y, xc, yc, angle)
rotated_points.append(f"{x_new:.6f} {y_new:.6f}\n")
with open(output_file, 'w') as f:
f.writelines(rotated_points)
# 示例调用
rotate_txt_file("points.txt", "rotated_points.txt", xc=0, yc=0, angle=30)
说明
1.输入格式:points.txt 每行包含 x y 两个数值,如:
1.0 2.0
3.0 4.0
5.0 6.0
2.旋转中心:参数 xc, yc 设定旋转中心。
3.旋转角度:angle 以角度为单位(如 30 表示逆时针旋转 30°)。
4.输出格式:rotated_points.txt 也以相同格式存储旋转后的坐标。
扩展
- 如果你的 .txt 文件数据格式不同(如 CSV 格式),可以使用 pandas 读取和写入。
- 如果要可视化旋转效果,可以使用 matplotlib 画出旋转前后的点。
旋转前后的效果图如下: