给定外部坐标提取多边形的内部点

Extract interior points of polygon given the exterior coordinates

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

例如,假设我有这个:

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

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

对于bonus points,我们如何不仅得到内部点,而且得到0.1格间距的所有边界点?

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

  • 关于内部点的提取,基于网格形状,可以用简单的数学来完成,像这样:
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)

结果:

但请注意,如果多边形不是矩形,它也会生成位于多边形外部的点(然后在将它们添加到列表)。


  • 关于边界点的提取,可以使用shapely LineStrings的interpolate方法来完成,像这样:
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)

结果: