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

蹲街弑〆低调 提交于 2019-12-13 21:01:01

问题


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)


回答1:


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




回答2:


having determined the four corner coordinates, you can rotate them relative to the origin (or midpoint) using a simple 2D Matrix Rotation:

http://en.wikipedia.org/wiki/Rotation_%28mathematics%29 (search for 2D rotation equation)

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

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

I hope this is of some use!



来源:https://stackoverflow.com/questions/22364828/create-a-square-polygon-random-oriented-from-midpoints-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!