Stacking up multiple shapely polygons to form a heatmap
<p>I have a bunch of Shapely polygons that overlap. Each shape represents one particular observation of the object in the wild. I want to build up some sort of a cumulative observation (heatmap?) by combining the polygons together. Not just the union: I want to combine them in such a way that I can threshold it together and form a better estimate of where the object actually is. What is the best to "rasterize" the shapely polygon?</p>

<p>one could perhaps proceed by adding one polygon at a time, keep a list of disjoint shapes and remember for each of them how many polygons contributed:</p>

<pre><code>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))))
</code></pre>

<p>This then produces:</p>

<pre><code>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)))
</code></pre>

python matplotlib shapely