将Shapely STRtree存储到文件中以供重用

问题描述

我有数量惊人的形状几何多边形,保存在shapefile中。我将它们加载到一个整齐的STRTree中。每次运行程序时都必须重新计算其信封,似乎效率很低。有没有办法(可能有泡菜)来存储整棵树?甚至将它们与Redis一起存储也会很有用。

谢谢!

解决方法

再三考虑... 酸洗实际上并没有多大帮助,因为strtree所做的基本上所有酸洗都是将每个单个几何转换为wkb格式并编写将它们全部保存到一个文件中(请参见注释here)。取消酸洗会从wkb重新创建这些几何,然后使用它们创建新的STRtree。因此,无论哪种方式都将再次计算边界。


尽管我尚未在所有几何类型上对其进行过测试,但似乎仍可以进行酸洗。

import pickle

from shapely.geometry import Polygon
from shapely.strtree import STRtree

polys = [Polygon(((i,i),(i + 1,(i,i + 1))) for i in range(100)]
strtree = STRtree(polys)

with open('strtree.pickle','wb') as f:
    pickle.dump(strtree,f)

然后在另一个过程中

import pickle

from shapely.geometry import Point

with open('strtree.pickle','rb') as f:
    strtree = pickle.load(f)

print(strtree.nearest(Point(39.8,39.8)).wkt)
# POLYGON ((40 40,41 40,40 41,40 40))

shapely==1.7.1中有an update,当解开某些STRtree对象时避免了段错误。因此,您可能需要获取最新版本。