Friday 27 May 2016

python - Reversing the order of features in a layer using OGR


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



Answer



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)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...