简体   繁体   English

在Python中从中点创建一个正方形多边形(面向随机)

[英]Create a square polygon (random oriented) from midpoints in Python

I have a midpoint (x,y) and i need to create a square polygon with random orientation using a 2D (random) planar rotation. 我有一个中点(x,y),我需要使用2D(随机)平面旋转来创建具有随机方向的正方形多边形。

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))]

This function creates the vertices of a square polygon without a specific orientation. 此函数创建没有特定方向的正方形多边形的顶点。 I wish to improve this function adding the possibility to rotation randomly these vertices (and with a specific angle if is possible) 我希望改进此功能,以增加随机旋转这些顶点的可能性(如果可能,并具有特定角度)

If I've understood you correctly, this should be able to do what you want: 如果我对您的理解正确,那么它应该可以执行您想要的操作:

from math import sin, cos, radians

def rotated_square(cx, cy, size, degrees=0):
    """ Calculate coordinates of a rotated square centered at 'cx, cy'
        given its 'size' and rotation by 'degrees' about its center.
    """
    h = size/2
    l, r, b, t = cx-h, cx+h, cy-h, cy+h
    a = radians(degrees)
    cosa, sina = cos(a), sin(a)
    pts = [(l, b), (l, t), (r, t), (r, b)]
    return [(( (x-cx)*cosa + (y-cy)*sina) + cx,
             (-(x-cx)*sina + (y-cy)*cosa) + cy) for x, y in pts]

print rotated_square(50, 50, 100)

Output: 输出:

[(0.0, 0.0), (0.0, 100.0), (100.0, 100.0), (100.0, 0.0)]

Note that in the general case, the resulting coordinates won't be integers. 请注意,在一般情况下,结果坐标不会是整数。

What this does effectively is first translate each coordinate to the origin by subtracting cx,cy from it, rotates that by the angle, and then un-translates it back by the same amount. 这样做的有效作用是,首先通过从坐标中减去cx,cy来将每个坐标转换为原点,然后将其旋转角度,然后将其取消平移相同的量。 This is necessary to compensate for the fact that rotation formulas usually are relative to origin of a coordinate system. 这对于补偿旋转公式通常相对于坐标系原点的事实是必要的。

having determined the four corner coordinates, you can rotate them relative to the origin (or midpoint) using a simple 2D Matrix Rotation: 确定了四个角坐标后,您可以使用简单的2D矩阵旋转将它们相对于原点(或中点)旋转:

http://en.wikipedia.org/wiki/Rotation_%28mathematics%29 (search for 2D rotation equation) http://en.wikipedia.org/wiki/Rotation_%28mathematics%29 (搜索2D旋转方程式)

x' = x cos(theta) - y sin(theta)
y' = x sin(theta) + y cos(theta)

You can use the built-in Python Math library for the cos/sin functions: http://docs.python.org/2/library/math.html section 9.2.3 您可以将内置的Python Math库用于cos / sin函数: http : //docs.python.org/2/library/math.html第9.2.3节

Math.cos(theta)
Math.sin(theta)

I hope this is of some use! 我希望这是有用的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM