3

I've got a shapefile with set of points with a column "test_class" of String type in the attribute table. enter image description here

I need to rasterize these points with setting pixel's value for each class and typically I use:

gdal_rasterize -burn 1 -where "test_class='classA'" points.shp raster.tif

and it works. At now I need to automate the procedure in Python. A simple test works fine:

import gdal
raster = gdal.Open("raster.tif", gdal.GA_Update)
shp = "points.shp"
OPTIONS = gdal.RasterizeOptions(burnValues=[1])
gdal.Rasterize(raster, shp, options=OPTIONS)

But when I try tu use "where" option:

OPTIONS = gdal.RasterizeOptions(burnValues=[1], where='"test_class"="classA"')

I'm getting an error:

ERROR 1: "classA" not recognised as an available field.

I was trying to use "where" with many combinations of characters ', ", without, and it still doesn't work.

I am open to any other solutions. I was tested rasterio library but it is very slow. I use Python 3.7 and GDAL 3.0.2.

2
  • In the SQL syntax the field names (identifiers) appear either between double quotes, or if they are simple withour quotes, and strings between single quotes. An orthodox way to use in the command line would be -where "\"test_class\"='classA'". I believe that in your Python case you should use where='"class"=\'classA\''.
    – user30184
    Mar 22 at 9:15
  • @user30184 Thanks a lot! It works! It looks that simple but I didn't make it up.
    – rybomar
    Mar 22 at 9:48
3

The notation "classA" would mean that there is a field called classA. If you need it to be treated as a value and not as a column name you should use single quotes in your condition, so 'classA'. Additionally you need to escape these single quotes, since they appear inside a Python string. So something like @user30184 suggested in his comment.

where='"test_class"=\'classA\''

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.