首页 > 解决方案 > 给定外部坐标提取多边形的内部点

问题描述

我有一个多边形的边界坐标列表。我想根据我可以选择的某种网格间距从这个多边形中提取一些内部点。

例如,假设我有这个:

from shapely.geometry import MultiPoint
Polygon([(0,0),
        (1,0),
        (1,1),
        (0,1)])

在此处输入图像描述

这产生了一个简单的正方形。但是,我们可以想象这个正方形实际上是一个由无数个点填充的网格。对于这个例子,假设我想要一个正方形内的点列表,网格间距为 0.1。有没有办法提取这些点的列表?

对于加分,我们如何不仅获得内部点,而且获得 0.1 网格间距的所有边界点?

编辑:这个问题主要是针对非矩形形状提出的,目的是寻找县/省/区等形状的点。我只是用一个矩形作为一个简单的例子。但是,我接受了建议的解决方案。将为任何为非矩形对象提供更复杂解决方案的人投票

标签: pythongeopandasshapely

解决方案


  • 关于内部点的提取,基于网格形状,可以通过简单的数学来完成,如下所示:
from shapely.geometry import Polygon, MultiPoint
from math import ceil

# The setup
pol = Polygon([(0,0), (1,0), (1,1), (0,1)])
cell_size = 0.1

# Extract coordinates of the bounding box:
minx, miny, maxx, maxy = pol.bounds

# How many points in each dimension ?
rows = int(ceil((maxy - miny) / cell_size))
cols = int(ceil((maxx - minx) / cell_size))

# Actually generate the points:
pts = []
x, y = minx, miny
for countcols in range(cols):
    for countrows in range(rows):
        pts.append((x, y))
        y += cell_size
    x += cell_size
    y = miny

# Create the MultiPoint from this list
result_pts_interior = MultiPoint(pts)

结果:

结果1

但请注意,如果多边形不具有矩形形状,它还会生成位于多边形外部的点(您应该pol.intersects(Point(x, y))在将它们添加到列表之前测试它们是否与多边形相交)。


  • 关于边界点的提取,可以使用interpolateshapely LineStrings的方法来完成,如下所示:
from shapely.geometry import Polygon, MultiPoint
import numpy as np

# The setup
pol = Polygon([(0,0), (1,0), (1,1), (0,1)])
distance_between_pts = 0.1

boundary = pol.boundary # Boundary of polygon as a linestring
boundary_length = boundary.length # Its length
# Build a list of points spaced by 0.1 along this linestring:
pts_boundary = [
    boundary.interpolate(n, False) for n
    in np.linspace(0, boundary_length, int(boundary_length / distance_between_pts) + 1)
]
# Create the MultiPoint from this list
result_pts_boundary = MultiPoint(pts_boundary)

结果:

结果2


推荐阅读