将 shapely.geometry.polygons 列表导出为 esri shapefile

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

我有一个形状多边形的列表,

polygons
。我想将它们全部导出到 esri shapefile 图层。这是多边形列表中的第一个特征:

POLYGON ((484 169, 485 169, 485 170, 486 170, 486 171, 487 171, 487 170, 488 170, 488 169, 490 169, 490 170, 492 170, 492 172, 494 172, 494 178, 493 178, 493 179, 492 179, 492 180, 487 180, 487 179, 485 179, 485 176, 484 176, 484 171, 483 171, 483 170, 484 170, 484 169))

有描述如何在各种来源执行此操作的文档,例如 this one,但是,我在实施它时遇到了麻烦。这是我试图应用于我的数据集的上述文档中的代码:

#A binary array (not actually my array though)
filtered_labels = np.array([1,0,0,0,1,0,1,0],[0,0,0,0,1,0,0,1])

#init generator
shapes = rio.features.shapes(filtered_labels)

# get srs
srs = osr.SpatialReference()
srs.ImportFromWkt(spatial_image.GetProjection())

#create polygons. "Ploygons" is a list of polygons
polygons = [shapely.geometry.Polygon(shape[0]["coordinates"][0]) for shape in shapes if shape[1] == 1]

polygon = polygons[0]

# Here is where the converting and exporting starts
#-----------------------------------------------------------------------------------
# Save extent to a new Shapefile
outShapefile = "C:\\Users\\maxduso.stu\\Desktop\\FCOR_599\\project_work\\data\\shapes\\cds.shp"
outDriver = ogr.GetDriverByName("ESRI Shapefile")

# Remove output shapefile if it already exists
if os.path.exists(outShapefile):
    outDriver.DeleteDataSource(outShapefile)

# Create the output shapefile
outDataSource = outDriver.CreateDataSource(outShapefile)
outLayer = outDataSource.CreateLayer('cds',
                            srs = spatial_image.GetSpatialRef())

# Add an ID field
idField = ogr.FieldDefn("id", ogr.OFTInteger)
outLayer.CreateField(idField)

# Create the feature and set values
featureDefn = outLayer.GetLayerDefn()
feature = ogr.Feature(featureDefn)
geom = ogr.CreateGeometryFromWkb(polygon.wkb)
feature.SetGeometry(geom)
feature.SetField("id", 1)
outLayer.CreateFeature(feature)
feature = None

# Save and close DataSource
inDataSource = None
outDataSource = None

奇怪的是,我收到的错误交替出现:

TypeError: in method 'Feature_SetGeometry', argument 2 of type 'OGRGeometryShadow *'

AttributeError: 'NoneType' object has no attribute 'CreateLayer'

老实说,我什至不知道哪里出了问题,因为我不明白所有的功能创建是如何工作的。如果你能指出我正确的方向,我将非常感激。

谢谢!

python polygon shapefile osgeo
© www.soinside.com 2019 - 2024. All rights reserved.