前言
针对遥感深度学习方面:目前很多深度学习的样本变得开源,但是标签格式样式较多如shapefile、geojson等,如何实现两者之间的相互转化,比较重要。
一、geopandas库介绍
geopandas是一个开源项目,可以轻松的处理地理空间数据,其中矢量格式相互转化只是其很小的一方面。
二、shapefile与geojson转换
1.引入geopandas库
首先需要安装geopandas库,如果使用anaconda虚拟环境,则相对较简单。直接打开conda控制面板,然后输入 conda install geopandas即可;若没有使用虚拟环境,同样也可以在pycharm中使用pip install geopandas。此部分不在赘述。
2.导入库,矢量转化。
geojson转shapefile代码如下(示例):
import geopandas as gpd
#geojson_file为待转化的geojson路径
geojson_file = r'xxx/xx/xx/xx.geojson'
#shp_file为转化后的shapfile保存路径
shp_file = r'xxx/xxx/xx/xx/xx.shp'
out_data = gpd.read_file(geojson_file)
out_data.to_file(shp_file, driver='ESRI Shapefile', encoding='utf-8')
shapefile转geojson代码如下(示例):
import geopandas as gpd
#geojson_file为转化后的geojson保存路径
geojson_file = r'xxx/xx/xx/xx.geojson'
#shp_file为待转化的shapefile路径
shp_file = r'xxx/xxx/xx/xx/xx.shp'
out_data = gpd.read_file(shp_file)
crs = out_data.crs
out_data = gpd.GeoSeries(out_data.geometry, crs=crs).simplify(tolerance=0.0002)
out_data.to_file(geojson_file, driver='GeoJSON', encoding="utf-8")
总结
其实两段代码并不难理解,就是使用geopandas打开矢量文件,然后对在内存中的矢量数据进行一个另存为的操作。核心就是使用geopandas库。