[gdal-dev] Speeding up OGR in python

Jose Gomez-Dans jgomezdans at gmail.com
Thu Dec 11 17:52:46 EST 2008


Hi,
I am using the Python OGR bindings to create a shapefile with a regularly
spaced grid over some multipolygons. I only want to have grid cells when the
centroid of the cell falls within one of my multipolygons. My code is simple
and rustic, but seems to be working. However, it is taking a long time to
run, I suspect due to the large number of nested loops. I am attaching the
code. The polygons in world.shp are fairly complex, but I was just wondering
whether there might be something really obvious here. As for versions,
OGR/GDAL is 1.5.3 and it is compiled with GEOS 2.2.3.

#!/usr/bin/python
from osgeo import ogr
from osgeo import osr

g_world = ogr.Open("world.shp")
Lworld = g_world.GetLayer(0)
feat_world = Lworld.GetFeature(0)
geom_world = feat_world.GetGeometryRef()

t_srs = osr.SpatialReference()
t_srs.SetFromUserInput('WGS84')
drv = ogr.GetDriverByName('ESRI Shapefile')
ds = drv.CreateDataSource('/tmp/output_grid.shp')
layer = ds.CreateLayer(ds.GetName(), geom_type = ogr.wkbPolygon, srs =
t_srs)
layer.CreateField(ogr.FieldDefn('id', ogr.OFTInteger))

x_res = 0.5
y_res = 0.5
gid = 0
geom_coll = []
for xc in xrange(-18, 52, 1):
    for yc in xrange(-36,36,1):
        wkt = "POLYGON((%f %f,%f %f,%f %f,%f %f,%f %f))"% \
                    ( xc-x_res, yc-y_res, xc+x_res, yc-y_res, xc+x_res,
yc+y_res,\
                    xc-x_res,yc+y_res,xc-x_res, yc-y_res)

        geom = ogr.Geometry(type=ogr.wkbPolygon)
        geom = ogr.CreateGeometryFromWkt(wkt)
        geom.AssignSpatialReference ( t_srs )
        geom_coll.append ( geom )

for iw in xrange ( geom_world.GetGeometryCount() ):
    gw = geom_world.GetGeometryRef ( iw)
    for geom in geom_coll:
        if gw.Contains ( geom.Centroid()):
            gid += 1
            feat = ogr.Feature(feature_def=layer.GetLayerDefn())
            feat.SetGeometryDirectly(geom)
            feat.SetFID( 1 )
            feat.SetField('id', gid)
            layer.CreateFeature(feat)
            feat.Destroy()

ds.Destroy()


-- 
Department of Geography, University College London
Gower Street, London WC1E 6BT, UK
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.osgeo.org/pipermail/gdal-dev/attachments/20081211/1aff833a/attachment-0001.html


More information about the gdal-dev mailing list