我一直在尝试创建一个功能,该功能基本上与QGIS的“溶解”功能相同。我认为这将超级容易,但显然并非如此。因此,从我收集到的信息来看,在这里使用fiona配合体形应该是最好的选择。我刚开始弄乱矢量文件,所以这个世界对我和python来说都是新的。
对于这些示例,我使用的是位于此处http://tinyurl.com/odfbanu的County shapefile, 所以这里是我收集的一些代码,但找不到使它们协同工作的方法
目前,我最好的方法是基于以下方法:https : //sgillies.net/2009/01/27/a-more-perfect-union-continued.html。它工作正常,并且我获得了52个状态的列表作为Shapely几何形状。如果有更直接的方法来完成此部分,请随时发表评论。
from osgeo import ogr
from shapely.wkb import loads
from numpy import asarray
from shapely.ops import cascaded_union
ds = ogr.Open('counties.shp')
layer = ds.GetLayer(0)
#create a list of unique states identifier to be able
#to loop through them later
STATEFP_list = []
for i in range(0 , layer.GetFeatureCount()) :
feature = layer.GetFeature(i)
statefp = feature.GetField('STATEFP')
STATEFP_list.append(statefp)
STATEFP_list = set(STATEFP_list)
#Create a list of merged polygons = states
#to be written to file
polygons = []
#do the actual dissolving based on STATEFP
#and append polygons
for i in STATEFP_list :
county_to_merge = []
layer.SetAttributeFilter("STATEFP = '%s'" %i )
#I am not too sure why "while 1" but it works
while 1:
f = layer.GetNextFeature()
if f is None: break
g = f.geometry()
county_to_merge.append(loads(g.ExportToWkb()))
u = cascaded_union(county_to_merge)
polygons.append(u)
#And now I am totally stuck, I have no idea how to write
#this list of shapely geometry into a shapefile using the
#same properties that my source.
因此,从我所看到的内容来看,本书的内容确实不是直截了当的,我真的只想要同一个shapefile,而只是将国家分解为州,我什至不需要太多的属性表,但我很好奇,看看如何传递从源到新创建的shapefile。
我发现了许多用fiona编写的代码,但是我永远无法使其与我的数据一起使用。如何将Shapely几何图形写入shapefile中的示例?:
from shapely.geometry import mapping, Polygon
import fiona
# Here's an example Shapely geometry
poly = Polygon([(0, 0), (0, 1), (1, 1), (0, 0)])
# Define a polygon feature geometry with one attribute
schema = {
'geometry': 'Polygon',
'properties': {'id': 'int'},
}
# Write a new Shapefile
with fiona.open('my_shp2.shp', 'w', 'ESRI Shapefile', schema) as c:
## If there are multiple geometries, put the "for" loop here
c.write({
'geometry': mapping(poly),
'properties': {'id': 123},
})
这里的问题是如何对几何列表进行同样的操作,以及如何重新创建与源相同的属性。