4

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.

asked Mar 22, 2021 at 8:35
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\''. Commented Mar 22, 2021 at 9:15
  • @user30184 Thanks a lot! It works! It looks that simple but I didn't make it up. Commented Mar 22, 2021 at 9:48

1 Answer 1

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\''

answered Mar 22, 2021 at 9:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.