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

时间:2014-03-12 19:00:43

标签: python performance geometry

我有一个中点(x,y),我需要找到(优雅和蟒蛇风格)方形的顶点,旋转给定角度(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 个答案:

答案 0 :(得分:1)

您可能希望使用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