我有一堆重叠的Shapely多边形。每个形状代表对野外物体的一个特定观察。我想通过将多边形组合在一起来建立某种累积观察(热图?)。不只是联合:我想以这样的方式组合它们,我可以将它们组合在一起并形成对象实际位置的更好估计。什么是“光栅化”形状多边形最好的?
答案 0 :(得分:2)
或许可以一次添加一个多边形,保留一个不相交的形状列表,并记住每个多边形贡献的多边形:
import copy
from itertools import groupby
from random import randint, seed
from shapely.geometry import Polygon, box
from shapely.ops import cascaded_union
polygons = [
Polygon([(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)]),
Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]),
Polygon([(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)])
]
def check_shape(s):
return (s.geom_type in ['Polygon', 'MultiPolygon'] and not s.is_empty)
shapes = []
for p in polygons:
polygon = copy.deepcopy(p)
new_shapes = []
for shape_cnt, shape in shapes:
new_shapes.extend([
(shape_cnt, shape.difference(polygon)),
(shape_cnt+1, shape.intersection(polygon))
])
polygon = polygon.difference(shape)
new_shapes.append((1, polygon))
shapes = list(filter(lambda s: check_shape(s[1]), new_shapes))
for p in polygons:
print(p)
for cnt, g in groupby(sorted(shapes, key = lambda s: s[0]), key = lambda s: s[0]):
print(cnt, cascaded_union(list(map(lambda s: s[1], g))))
然后产生:
POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))
POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))
POLYGON ((1 1, 2 1, 2 2, 1 2, 1 1))
1 MULTIPOLYGON (((2 1, 2 0, 1 0, 1 1, 2 1)), ((0 1, 0 2, 1 2, 1 1, 0 1)))
2 MULTIPOLYGON (((1 0, 0 0, 0 1, 1 1, 1 0)), ((1 2, 2 2, 2 1, 1 1, 1 2)))