如何将 Shapely 几何体保存到文件中并稍后将其加载到变量中

问题描述 投票:0回答:2

如何将

shapely.geometry.polygon.Polygon
对象保存到文件中(尤其是shapefile)并在需要时将其加载到Python环境中?

from shapely import geometry
q = [(82,32.261),(79.304,32.474),(77.282,30.261),(81.037,28.354)]
polygon = geometry.Polygon(q)

我想将

polygon
对象保存到 shapefile(或任何其他格式的文件)中,并希望稍后在需要时加载它。

python shapefile shapely
2个回答
1
投票

聚会迟到了。但这就是我喜欢的做法,用泡菜很好又简单。

from shapely import geometry
import pickle

# Make a polygon
q = [(82,32.261),(79.304,32.474),(77.282,30.261),(81.037,28.354)]
polygon = geometry.Polygon(q)

# Check it out
print('My new polygon: \n', polygon)


# Save polygon to disc
with open('./my_polygon', "wb") as poly_file:
    pickle.dump(polygon, poly_file, pickle.HIGHEST_PROTOCOL)

# Load polygon from disc
with open('./my_polygon', "rb") as poly_file:
    loaded_polygon = pickle.load(poly_file)

# Check it out again
print('My loaded polygon: \n', loaded_polygon)

输出:

My new polygon: 
 POLYGON ((82 32.261, 79.304 32.474, 77.282 30.261, 81.03700000000001 28.354, 82 32.261))
My loaded polygon: 
 POLYGON ((82 32.261, 79.304 32.474, 77.282 30.261, 81.03700000000001 28.354, 82 32.261))

干杯!


0
投票

另一个选项是 geojson 格式,使用

shapely.to_geojson
shapely.from_geojson

优点是该文件是人类可读的并且更易于共享,因为不建议跨设备共享pickle文件。

from shapely import Polygon, to_geojson, from_geojson

polygon = Polygon([(82, 32.261), (79.304, 32.474), (77.282, 30.261), (81.037, 28.354)])
filepath = "polygon.geojson"

# To GeoJSON
polygon_geojson_str = to_geojson(polygon)
with open(filepath, "w") as f:
    f.write(polygon_geojson_str)

# From GeoJSON
with open(filepath, "r") as f:
    polygon_geojson_str = f.read()
polygon_read = from_geojson(polygon_geojson_str)

# Check they are the same
print(polygon_geojson_str)
print()
print(polygon)
print(polygon_read)
assert polygon == polygon_read
{"type":"Polygon","coordinates":[[[82.0,32.261],[79.304,32.474],[77.282,30.261],[81.037,28.354],[82.0,32.261]]]}

POLYGON ((82 32.261, 79.304 32.474, 77.282 30.261, 81.037 28.354, 82 32.261))
POLYGON ((82 32.261, 79.304 32.474, 77.282 30.261, 81.037 28.354, 82 32.261))
© www.soinside.com 2019 - 2024. All rights reserved.