有一段時(shí)間需要使用python生成shapefile文件撼泛,并且轉(zhuǎn)為kml文件,放到Google earth中展示僧诚,中間有過(guò)摸索特此記下:
環(huán)境搭建
讀寫(xiě)shape file需要兩個(gè)庫(kù) gdal 和pyshp,其中g(shù)dal我在網(wǎng)上看到需要什么C++編譯環(huán)境,弄了很久都沒(méi)有成功,后來(lái)直接下載了一個(gè)whl文件 自己pip install 安裝就行了些膨。下載地址下載完后,把這個(gè)文件復(fù)制到你的python路徑Scripts下 然后直接在路徑上cmd 輸入命令pip install +你下載的文件名钦铺,安裝好订雾,在命令行輸入:python 進(jìn)入python環(huán)境,import osgeo 沒(méi)有報(bào)錯(cuò)即為安裝成功~
讀取shapefile文件
我看到的維基百科shapefile文件主要由三部分構(gòu)成:
Shp:圖形格式矛洞。一個(gè)地形的圖片洼哎。
shx :圖形索引格式。幾何體位置索引沼本,記錄每一個(gè)幾何體在shp文件之中的位置噩峦,能夠加快向前或向后搜索一個(gè)幾何體的效率
Dbf:屬性數(shù)據(jù)格式,以dBaseIV的數(shù)據(jù)表格式存儲(chǔ)每個(gè)幾何形狀的屬性數(shù)據(jù)
我理解的讀取shapefile文件主要是使用dbf里面的數(shù)據(jù)抽兆。
代碼:
from osgeo import ogr
importjson
data
= ogr.Open('D:/work/python/Tif_to_png/shp/shape file文件名.shp') #返回一個(gè)DataSource對(duì)象
layer= data.GetLayer(0) #獲得第一層數(shù)據(jù)(多數(shù)Shapefile只有一層)
extent= layer.GetExtent() # 當(dāng)前圖層的地理范圍
print(f'the extent of the layer: {extent}')
srs= layer.GetSpatialRef()
print(f'the spatial reference system of
the data: {srs.ExportToPrettyWkt()}')
schema=[] # 當(dāng)前圖層的屬性字段
ldefn= layer.GetLayerDefn()
forn in range(ldefn.GetFieldCount()):
fdefn = ldefn.GetFieldDefn(n)
schema.append(fdefn.name)
print(f'the fields of this layer: {schema}')
features=[]
fori in range(layer.GetFeatureCount()):
feature = layer.GetFeature(i)
features.append(json.loads(feature.ExportToJson()))
print(f'the first feature represented with JSON: {features[0]}')
寫(xiě)shapefile文件
寫(xiě)shapefile文件识补,我主要使用pyshp這個(gè)庫(kù),安裝方式為:為 pip install pyshp
假如提示time out 可以嘗試:pip install PyShp -i https://pypi.tuna.tsinghua.edu.cn/simple/
代碼如下(已生成多個(gè)點(diǎn)為例):
import shapefile #這邊導(dǎo)入的名字是shapefile 不是pyshp,別到錯(cuò)了辫红。
w = shapefile.Writer('shapefiles/test/point')
w.field('你的字段名', 'C')
w.point(111,22)
w.record(字段名)
w.close()
我的理解:point是增加數(shù)值凭涂,而record是在增加關(guān)于這個(gè)數(shù)值的描述,其中w.point和w.record都可以循環(huán)執(zhí)行寫(xiě)入數(shù)據(jù)贴妻。
shapefile轉(zhuǎn)kml文件
這次需要在Linux安裝一個(gè)gdal切油,(其實(shí)windows應(yīng)該也可以,就是我還沒(méi)學(xué)會(huì))
安裝步驟:
tar xvf gal-2.2.1.tar.gz
cd gdal-2.2.1
sudo ./configure --with-python
Sudo make
Sudo make install
出現(xiàn)ImportError: No module named _gdal錯(cuò)誤解決方案:
sudo find / -name gdal.py
把這些路徑和自己Linux中python的路徑全部加到
sudo gedit /etc/profile這里面 格式為:
Export PYTHONPATH ********路徑********* :$PYTHPNPATH
- 執(zhí)行python命令 進(jìn)去import osgeo 沒(méi)有反應(yīng)就是成功了
把你需要轉(zhuǎn)的shapefile文件放到linux 路徑下名惩,一定要記得是三個(gè)文件(shp澎胡、shx、dbf)!!!
然后在Linux執(zhí)行命令:
ogr2ogr -f KML 轉(zhuǎn)換后的文件名.kml 轉(zhuǎn)換前的文件名.shp
update一下:寫(xiě)shapefile 可以去看pyshp的官方文檔,里面的demo非常詳細(xì)攻谁,也很容易入門稚伍。
地址:(https://github.com/GeospatialPython/pyshp#writing-shapefiles)