python - 堆叠多个形状良好的多边形以形成热图

标签 python matplotlib shapely

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

最佳答案

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

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

关于python - 堆叠多个形状良好的多边形以形成热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39216767/

相关文章:

python - 匀称的 .contains() 方法但包括边界?

python - 无法使用 Linux Alpine docker 为 AWS lambda 构建 zip 文件

Python 请求 : Don't wait for request to finish

python - python会使用multiprocessing.sharedctypes收集共享内存中分配的内存吗?

python - 如何使用 csv dictreader、matplotlib 和 numpy 创建概率密度函数图?

python - sns regplot 剪切我的第一个和最后一个数据点

Python:如何对列表中的元素进行分组并获取组的总和

python - 在 Pandas 中分配日期

python - 同一图中的多个等值线图

python - 如何从 Shapely 多边形中切出 x 和 y 坐标? [类型错误: 'Polygon' object is not iterable]