Python:从中点找到正方形的顶点(旋转和随机旋转)

0 投票
1 回答
1516 浏览
提问于 2025-04-17 22:00

我有一个中点(x,y),我需要优雅地用Python找到一个旋转了特定角度(t)的正方形的四个顶点。或者我可以随机添加一个参数t(角度)到我的函数中,当t等于r(=随机)时,四个顶点的位置就是随机的。

def get_square_plot(x, y, side):
    return [(x-(side/2), y+(side/2)), (x+(side/2), y+(side/2)), (x-(side/2), y-(side/2)), (x-(side/2), y-(side/2))]

其中x,y是中点的坐标,side是正方形的边长。

print get_square_plot(0, 0, 10)
[(-5.0, 5.0), (5.0, 5.0), (-5.0, -5.0), (-5.0, -5.0)]

1 个回答

2

你可能想用Numpy来旋转你的方块:

import numpy as np
import matplotlib.pyplot as plt

def RotM(alpha):
    """ Rotation Matrix for angle ``alpha`` """
    sa, ca = np.sin(alpha), np.cos(alpha)
    return np.array([[ca, -sa],
                     [sa,  ca]])

def getSquareVertices(mm, h, phi):
    """ Calculate the for vertices for square with center ``mm``,
        side length ``h`` and rotation ``phi`` """
    hh0 = np.ones(2)*h  # initial corner
    vv = [np.asarray(mm) + reduce(np.dot, [RotM(phi), RotM(np.pi/2*c), hh0])
          for c in range(5)]  # rotate initial corner four times by 90°
    return np.asarray(vv)


if __name__ == "__main__":
    """ Test getSquareVertices """

    fg,ax = plt.subplots(1,1)
    for h,phi in zip([1,2,3], [0.,np.pi/6, np.pi/4]):
        cc = (h,h) # center
        vv = getSquareVertices(cc, h, phi)
        print(vv)
        ax.plot(vv[:,0], vv[:,1], 'x-',
                label=u"$\phi$={:.1f}°".format(np.rad2deg(phi)))
    ax.legend(loc="best")
    ax.axis("equal")
    fg.canvas.draw()  # do the drawing
    plt.show() # enter event loop

这样可以得到Squares

撰写回答