python - 将由 4 个元组组成的矩形向左或向右旋转

标签 python python-3.x rotation gis

我正在开发一个程序来操作 GIS 数据,但对于这个精确的问题,我试图围绕左下角旋转 4 个点的矩形。我有 1 个元组描述左下角: x,y=40000,40000 我还得到了长度 x 和长度 y、x_displacementy_displacement。我有一个角度,theta,以度为单位。我想将矩形向左或向右旋转最多 90 度,因此 theta 可以是 -89 到 89 度。负角度应将角向左旋转;向右为正角。我将矩形表示为这样: http://i.imgur.com/pp3hFyA.jpg

    x_displacement=100
    y_displacement=100
    x = 40000
    y = 40000
    x1 = x
    y1 = y + a.y_displacement
    x2 = x + a.x_displacement
    y2 = y + a.y_displacement
    x3 = x + a.x_displacement
    y3 = y
    #describes the other 4 corners of the rectangle

Coord 是一个保存 x 和 y 值的类。 coords 是 Coord 类项目的列表。

    c = Coord(x, y)
    coords.append(c)
    c = Coord(x1, y1)
    coords.append(c)
    c = Coord(x2, y2)
    coords.append(c)
    c = Coord(x3, y3)
    coords.append(c)
    #Adds each corner to the list of coordinates
    theta = math.radians(a.angle)
    newcoords = []
    for c in coords:
        newcoords.append(Coord((c.x * math.cos(theta) - c.y * math.sin(theta)),
                              (c.x * math.sin(theta) + c.y * math.cos(theta))))
    coords=newcoords

我怀疑我做错了一些相对微不足道的事情,但我已经在这个问题上停留了很长一段时间了。 此代码生成一个新的矩形,该矩形要么是畸形的,要么具有负角,而不是根据需要稍微向左旋转的角。 我在这里看到了很多关于旋转矩形的帖子,但似乎没有一个是直接重复的,因为它们不处理负角度。如果有任何指点,我将不胜感激!

最佳答案

正如一些评论者提到的,您正在围绕 (0, 0) 点旋转,而不是左下点。当我们构建坐标时,我们可以:

  • 首先在 (0, 0) 点构造形状<​​/li>
  • 旋转它
  • 将其翻译到需要的位置

下面给出了一个使用普通列表而不是 Coord 对象的示例,但我确信它说明了这一点。

import math


def rotate(xy, theta):
    # https://en.wikipedia.org/wiki/Rotation_matrix#In_two_dimensions
    cos_theta, sin_theta = math.cos(theta), math.sin(theta)

    return (
        xy[0] * cos_theta - xy[1] * sin_theta,
        xy[0] * sin_theta + xy[1] * cos_theta
    )


def translate(xy, offset):
    return xy[0] + offset[0], xy[1] + offset[1]


if __name__ == '__main__':
    # Create the square relative to (0, 0)
    w, h = 100, 100

    points = [
        (0, 0),
        (0, h),
        (w, h),
        (w, 0)
    ]

    offset = (40000, 50000)
    degrees = 90
    theta = math.radians(degrees)

    # Apply rotation, then translation to each point
    print [translate(rotate(xy, theta), offset) for xy in points]

作为奖励,这应该适用于相对于 (0, 0) 定义的任何点集,无论它们是否形成任何合理的多边形。

关于python - 将由 4 个元组组成的矩形向左或向右旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39879924/

相关文章:

python-3.x - PyCharm 中的 Folium map 问题

python - discord.py 机器人重写 AttributeError : 'Bot' object has no attribute 'send_message'

javascript - 如何在 PaperJS 中围绕一个点向鼠标旋转?

javascript - Three.js:结合 tween.js 围绕世界轴旋转对象

python - 有没有更好的方法来处理以文本模式写入 csv 并以二进制模式读取?

python - 我想将列表中一个能被 2 整除的数字与下一个能被 5 整除的数字交换

python - 在 python 中读取 json 值时出现无效参数错误

text - 如何使用 OpenLayers 3 旋转文本和 View

python - 如何读取边缘列表以制作 scipy 稀疏矩阵

python - 如何在 PostgreSQL 9.3 x64 Windows 7 上安装 PL/Python?