3

I'm working on rasterizing some polygons using gdal_rasterize. This works great, but I want the rasterize command to place features with lower FIDs on top of those with higher FIDs. (Gdal_rasterize currently takes the latest polygon and burns that value onto the raster).

I can think of a way to do it by manually swapping the rings for the polygons, but is there a faster way reverse the order of features in a layer?

Hoping for a simple reverse sort function? I'm working with OGR/GDAL on Python 2.x

6

If you are happy using the ogr2ogr utility you can accomplish this feature reversal by including an SQL statement in the command. For example, the following will create a new shapefile with the features in reverse order:

ogr2ogr -sql "SELECT * FROM layer ORDER BY fid DESC" destfile.shp srcfile.shp

If you need to have this reversal happen inside of your Python script you can use the datasource's ExecuteSQL() method to return a new layer that can be passed to the gdal.RasterizeLayer() function:

rev_lyr = ds.ExecuteSQL("SELECT * FROM layer ORDER BY fid DESC")
gdal.RasterizeLayer(out_ds, [1], rev_lyr)
  • This is perfect. Though I'm having some issues with the SQL command. When I create the layer, I call it "polygons" and when I run the command I use: "SELECT * FROM polygons ORDER BY fid DESC" but I'm getting this error: ERROR 1: SELECT from table polygons failed, no such table/featureclass. – user81442 Sep 8 '17 at 18:41
  • 1
    @user81442 The SQL syntax is, by default at least, OGR SQL (gdal.org/ogr_sql.html) and the name of the layer when querying shapefiles defaults to the file name without the .shp extension. So try substituting 'layer' with the file name that the DataSource object references. – Ali Sep 8 '17 at 19:00
  • You can view the underlying name of the Layer object using lyr.GetName() – Ali Sep 8 '17 at 19:06
  • That did it, using lyr.GetName() made it work. Thanks! – user81442 Sep 8 '17 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.