在Python中从中点创建一个正方形多边形(面向随机) [英] Create a square polygon (random oriented) from midpoints in Python

查看:78
本文介绍了在Python中从中点创建一个正方形多边形(面向随机)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个中点(x,y),我需要使用2D(随机)平面旋转来创建具有随机方向的正方形多边形.

I have a midpoint (x,y) and i need to create a square polygon with random orientation using a 2D (random) planar rotation.

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)

输出:

[(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.

这有效的方法是首先通过从坐标中减去cx,cy来将每个坐标转换为原点,将其旋转一定角度,然后将其取消平移相同的量.这对于补偿旋转公式通常相对于坐标系原点的事实是必要的.

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. This is necessary to compensate for the fact that rotation formulas usually are relative to origin of a coordinate system.

这篇关于在Python中从中点创建一个正方形多边形(面向随机)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆