【问题标题】:How to get the coordinates of grid points inside a polygon in Python?如何在Python中获取多边形内网格点的坐标?
【发布时间】:2021-01-07 20:58:15
【问题描述】:

我想输入一个多边形的4个顶点的坐标,指定点的数量来划分多边形的边(等分),目标是生成一个矩阵,该矩阵带有多边形内部的网格点的坐标.

下图可能更好地解释了我的目标:

所以在这种情况下,我将输入点 (P) 的坐标并指定我希望网格为 3 x 2。输出将是一个 3 x 2 矩阵,其坐标为网格的坐标 (x,y)点 (N)。

我进行了很多搜索,但仍然找不到这样做的方法,老实说,我对 Python 一点经验都没有。我发现使用 numpy 的 meshgrid 结合 matplotlib.path 的 contains_points 在多边形内创建网格但我不知道如何获取网格点的坐标。我看到 shapely 在此类问题中被大量使用,但同样,我没有这方面的经验,因此不胜感激!

提前谢谢大家!

【问题讨论】:

  • 有点不清楚您需要什么帮助。如果您需要数学方面的帮助,这不是正确的社区。如果您在实现算法时需要帮助,您应该以一种可以重现您卡住的地方的方式发布您的代码。 stackoverflow.com/help/how-to-ask

标签: python grid coordinates polygon shapely


【解决方案1】:

为了解释该方法,我们分为三个步骤:

  1. 在 4 边形的每一边找到记号
  2. 找到网格线
  3. 找到网格线的交点
def det(a, b):
    return a[0] * b[1] - a[1] * b[0]

ticks = []
A = (1, 2)  # wlog., suppose the polygon is ABCD;
B = (3, 2)
C = (3, 4)
D = (1, 4)
polygon = [A, B, C, D]
n = 3  # number of parts on each side of the grid

# we first find ticks on each side of the polygon
for j in range(4):  # because we are talking about 4-gons
    temp_ticks = []
    for i in range(n-1):
        t = (i+1)*(1/n)
        Ex = polygon[j][0] * (1-t) + polygon[(j+1) % 4][0] * t
        Ey = polygon[j][1] * (1-t) + polygon[(j+1) % 4][1] * t
        temp_ticks.append((Ex, Ey))
    if j < 2:
        ticks.append(temp_ticks)
    else: # because you are moving backward in this part
        temp_ticks.reverse()
        ticks.append(temp_ticks)

# then we find lines of the grid
h_lines = []
v_lines = []
for i in range(n-1):
    h_lines.append((ticks[0][i], ticks[2][i]))
    v_lines.append((ticks[1][i], ticks[3][i]))
        
# then we find the intersection of grid lines
for i in range(len(h_lines)):
    for j in range(len(v_lines)):
        line1 = h_lines[i]
        line2 = v_lines[j]
        xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
        ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])
        div = det(xdiff, ydiff)
        if div == 0:
            raise Exception('lines do not intersect')

        d = (det(*line1), det(*line2))
        x = det(d, xdiff) / div
        y = det(d, ydiff) / div
        print(x,y) # this is an intersection point that you want

注意:寻找线交点的部分代码来自here

【讨论】:

  • 完美,这正是我想要的!我只需要稍微更改代码即可为垂直和水平线获得不同的“网格每一侧的零件数量”。无论如何,这是一个很好的解决方案,我的问题现在解决了,感谢您的帮助!
  • 不客气。如果这是解决方案,请将其标记为正确答案。这有助于其他人在将来遇到这个问题时。
猜你喜欢
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
  • 2011-04-19
  • 2011-12-05
  • 1970-01-01
  • 2019-12-27
相关资源
最近更新 更多