Python 将直线旋转成负坐标

Python 将直线旋转成负坐标,python,numpy,matrix,rotation,Python,Numpy,Matrix,Rotation,我正在尝试使用以下函数旋转一条线: def rotate_line(line, theta): angle_cos = numpy.cos(theta) angle_sin = numpy.sin(theta) ox, oy = line[0] for i in range(len(line)): px, py = line[i] qx = ox + angle_cos * (px - ox) - angle_sin *

我正在尝试使用以下函数旋转一条线:

def rotate_line(line, theta):
    angle_cos = numpy.cos(theta)
    angle_sin = numpy.sin(theta)
    ox, oy = line[0]
    
    for i in range(len(line)):
        px, py = line[i]
        qx = ox + angle_cos * (px - ox) - angle_sin  * (py - oy)
        qy = oy + angle_sin  * (px - ox) + angle_cos * (py - oy)
        
        line[i] = numpy.array([qx, qy])
    
    return line
但是我得到了这个结果(红色-原始,橙色-旋转),而不是预期的结果:

我尝试过各种其他函数,但它们都给出了相同的错误结果。为什么?

测试代码:

line = numpy.array([[1,1], [2,2], [3,3]])
print(line)
ax = plt.subplot()
ax.scatter(1, 1, color = 'green')
ax.plot(line[:, 0].tolist(), line[:, 1].tolist(), color = 'red')
line = rotate_line(line, numpy.deg2rad(90))
print(line)
ax.plot(line[:, 0].tolist(), line[:, 1].tolist(), color = 'orange')

代码中的问题是,您在
rotate_line
函数中修改了原始的
行。您需要引入一个新变量(例如,
new\u line
)来记录正交线的坐标。例如,您可以这样做:

import matplotlib.pyplot as plt
import numpy as np

def rotate_line(line, theta):
    angle_cos = np.cos(theta)
    angle_sin = np.sin(theta)
    ox, oy = line[0]

    new_line = np.zeros((line.shape[0], line.shape[1]))
    for i in range(len(line)):
        px, py = line[i]
        qx = ox + angle_cos * (px - ox) - angle_sin * (py - oy)
        qy = oy + angle_sin * (px - ox) + angle_cos * (py - oy)

        new_line[i] = np.array([qx, qy])

    return new_line

line = np.array([[1,1], [2,2], [3,3]])
print(line)
ax = plt.subplot()
ax.scatter(1, 1, color='green')
ax.plot(line[:, 0].tolist(), line[:, 1].tolist(), color='red')
line = rotate_line(line, np.deg2rad(90))
print(line)
ax.plot(line[:, 0].tolist(), line[:, 1].tolist(), color='orange')
plt.axis('scaled')
plt.show()
输出: