python - 将一个匀称的多边形切割成 N 个大小相等的多边形
问题描述
我有一个匀称的多边形。我想将这些多边形切割成n 个多边形,它们都具有或多或少相同大小的区域。大小相同是最好的,但近似值也可以。
我尝试使用这里描述的两种方法,这两种方法都是朝着正确方向迈出的一步,而不是我需要的。两者都不允许目标n
我调查了voronoi,对此我很陌生。此分析给出的最终形状将是理想的,但它需要点,而不是形状作为输入。
解决方案
这是我能做到的最好的。它不会导致每个多边形的表面积相等,但事实证明它可以满足我的需要。这会使用特定数量的点填充形状(如果参数保持不变,点数也会保持不变)。然后将这些点转换为 voronoi,然后将其转换为三角形。
from shapely import affinity
from shapely.geometry.multipolygon import MultiPolygon
from scipy.spatial import Voronoi
# Voronoi doesn't work properly with points below (0,0) so set lowest point to (0,0)
shape = affinity.translate(shape, -shape_a.bounds[0], -shape_a.bounds[1])
points = shape_to_points(shape)
vor = points_to_voronoi(points)
triangles = MultiPolygon(triangulate(MultiLineString(vor)))
def shape_to_points(shape, num = 10, smaller_versions = 10):
points = []
# Take the shape, shrink it by a factor (first iteration factor=1), and then
# take points around the contours
for shrink_factor in range(0,smaller_versions,1):
# calculate the shrinking factor
shrink_factor = smaller_versions - shrink_factor
shrink_factor = shrink_factor / float(smaller_versions)
# actually shrink - first iteration it remains at 1:1
smaller_shape = affinity.scale(shape, shrink_factor, shrink_factor)
# Interpolate numbers around the boundary of the shape
for i in range(0,int(num*shrink_factor),1):
i = i / int(num*shrink_factor)
x,y = smaller_shape.interpolate(i, normalized=True).xy
points.append( (x[0],y[0]))
# add the origin
x,y = smaller_shape.centroid.xy
points.append( (x[0], y[0]) ) # near, but usually not add (0,0)
points = np.array(points)
return points
def points_to_voronoi(points):
vor = Voronoi(points)
vertices = [ x for x in vor.ridge_vertices if -1 not in x]
# For some reason, some vertices were seen as super, super long. Probably also infinite lines, so take them out
lines = [ LineString(vor.vertices[x]) for x in vertices if not vor.vertices[x].max() > 50000]
return MultiLineString(lines)
这是输入形状:
这是之后shape_to_points
:
这是之后points_to_voronoi
然后我们可以对 voronoi 进行三角测量:
推荐阅读
- powershell - 学生AD帐户的年度汇总
- css - 如何从 Google 字体中获取黑色字体粗细
- node.js - 如何在 create-react-app 构建中找到未知错误?
- nlp - 从句子中提取关系概念
- ocaml - 表达式预期类型单元,但它已经这样做了
- laravel - 如何在 laravel 中创建下拉菜单
- php - WooCommerce - 删除前端随处可见的尺寸
- c++ - 函数调用优先级的重载和模板特化
- python - 如何获得具有相同 ID、具有父评论 ID 的同一类的 ID 评论回复(使用 Selenium 刮板数据)
- uiwebview - 与 SFAuthenticationSession 或 SFSafariViewController 共享 REST API 会话 cookie