堆叠多个匀称的多边形以形成热图

Stacking up multiple shapely polygons to form a heatmap

我有一堆形状重叠的多边形。每个形状代表对野外物体的一次特定观察。我想通过将多边形组合在一起来建立某种累积观察(热图?)。不仅仅是联合:我想以这样一种方式组合它们,以便我可以将它们组合在一起并形成对对象实际位置的更好估计。 "rasterize" 形状多边形最好的是什么?

也许可以通过一次添加一个多边形来继续,保留一个不相交形状的列表,并记住每个形状贡献了多少多边形:

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)))