python - 给定外部坐标提取多边形的内部点
问题描述
我有一个多边形的边界坐标列表。我想根据我可以选择的某种网格间距从这个多边形中提取一些内部点。
例如,假设我有这个:
from shapely.geometry import MultiPoint
Polygon([(0,0),
(1,0),
(1,1),
(0,1)])
这产生了一个简单的正方形。但是,我们可以想象这个正方形实际上是一个由无数个点填充的网格。对于这个例子,假设我想要一个正方形内的点列表,网格间距为 0.1。有没有办法提取这些点的列表?
对于加分,我们如何不仅获得内部点,而且获得 0.1 网格间距的所有边界点?
编辑:这个问题主要是针对非矩形形状提出的,目的是寻找县/省/区等形状的点。我只是用一个矩形作为一个简单的例子。但是,我接受了建议的解决方案。将为任何为非矩形对象提供更复杂解决方案的人投票
解决方案
- 关于内部点的提取,基于网格形状,可以通过简单的数学来完成,如下所示:
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)
结果:
但请注意,如果多边形不具有矩形形状,它还会生成位于多边形外部的点(您应该pol.intersects(Point(x, y))
在将它们添加到列表之前测试它们是否与多边形相交)。
- 关于边界点的提取,可以使用
interpolate
shapely 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)
结果:
推荐阅读
- vba - 你能告诉我这是怎么回事吗?“VBA 网络登录”,它不起作用
- javascript - V8 是否只编译我们想要运行的代码?
- swift - 懒惰是不行的!不能在属性初始化器中使用实例成员“字段”;属性初始化程序在“自我”可用之前运行
- spring - 异常:java.sql.SQLDataException:不支持从 TIMESTAMP 到 java.lang.Long 的转换
- javascript - 当用户登录时,注销按钮必须显示,但它不会立即显示。为什么会这样?
- javascript - 带括号符号的扩展运算符
- kubernetes - 如何使用 Kubernetes 查看失败的作业
- r - 在 R 中的 NETCDF 中填充值
- mongodb - 我们可以在模型级别应用投影吗?即使在聚合或 $lookup 中也可以访问该模型
- c# - C#进程无法访问该文件,因为它正被另一个进程使用-删除文件时