3

使用ogr2ogrin Python,我正在尝试将 a 转换CSV为 a shapefile。中的一列CSV名为“Polygon”,包含WKT如下内容:POLYGON((long lat, long lat, long lat, etc.))目前,我可以制作shapefile具有正确投影的多边形,但几何为空。

如何修改我的参数以使用每行中ogr2ogr的 正确创建几何?WKT目前我有这样的事情:

ogr2ogr.main(["", "-a_srs", "EPSG:4326", "-f", "ESRI Shapefile", "output.shp", "input.csv", "-nlt", "POLYGON"])
4

1 回答 1

2

我真的不习惯 ogr2ogr.py 但是如果你知道一些关于 ogr 的 python 绑定的基础知识,它可以很容易地完成。这是一个简单的例子,可以做你想做的事情。

import ogr, osr, csv

spatialref = osr.SpatialReference()  # Set the spatial ref.
spatialref.SetWellKnownGeogCS('WGS84')  # WGS84 aka ESPG:4326
driver = ogr.GetDriverByName("ESRI Shapefile") # Shapefile driver
dstfile = driver.CreateDataSource('output.shp') # Your output file

# Please note that it will fail if a file with the same name already exists
dstlayer = dstfile.CreateLayer("layer", spatialref, geom_type=ogr.wkbPolygon) 

# Add the other attribute fields needed with the following schema :
fielddef = ogr.FieldDefn("ID", ogr.OFTInteger)
fielddef.SetWidth(10)
dstlayer.CreateField(fielddef)

fielddef = ogr.FieldDefn("Name", ogr.OFTString)
fielddef.SetWidth(80)
dstlayer.CreateField(fielddef)

# Read the features in your csv file:
with open('/path/to/file.csv') as file_input:
    reader = csv.reader(file_input)  # Can be more intuitive with a DictReader (adapt to your needs)
    next(reader) # Skip the header
    for nb, row in enumerate(reader): 
        # WKT is in the second field in my test file :
        poly = ogr.CreateGeometryFromWkt(row[1])
        feature = ogr.Feature(dstlayer.GetLayerDefn())
        feature.SetGeometry(poly)
        feature.SetField("ID", nb) # A field with an unique id.
        feature.SetField("Name", row[0]) # The name (expected to be in the first column here)
        dstlayer.CreateFeature(feature)
    feature.Destroy()
    dstfile.Destroy()

此代码假定您的 CSV 有两列,第一列带有要使用的名称,第二列包含 WKT 中的几何图形,例如以下形式的内容:

"Name","Polygons"
"Name1","POLYGON((1 1,5 1,5 5,1 5,1 1))"
"Name2","POLYGON((6 3,9 2,9 4,6 3))"

当然,它需要根据您的具体情况进行调整,但是这段代码可以作为第一个开始,并且可以完成这项工作。
(如果你想要一些关于 GDAL/ogr python 绑定的其他例子,你可以看看这些食谱

于 2015-08-11T22:36:32.647 回答