TransWikia.com

Incorrect results while cropping with gdalwarp and cutlineSQL

Geographic Information Systems Asked by PKG on October 2, 2021

Environment: Windows 10, Python 3.7, Numpy 1.18 and GDAL 3.0.2

enter image description here

Data required:

  1. Single band raster
  2. Polygons on same area with an attribute "name"

enter image description here

The code below works fine and cuts the data for all 3 polygons

ds = gdal.Warp('cut.tif', 'ndvi.tif', format = 'GTiff', cutlineDSName = 'parcel.shp')

if ds is None:
    print('Failed')
else:
    print('Success')
# prints Success

enter image description here

But this does not work

ds = gdal.Warp('first-wrong.tif', 'ndvi.tif', format = 'GTiff', 
               cutlineDSName = 'parcel.shp', 
               cutlineSQL = 'SELECT * FROM parcel', 
               cutlineWhere = 'name = "first"')

if ds is None:
    print('Failed')
else:
    print('Success')
# prints Success but gives same result as previous

Expected output:
enter image description here

Is this a bug or am I missing something?

One Answer

Your where clause is using double quotes for the string literal.

The OGR SQL documentation specifies single quotes are required for strings. Double quotes are used for field names (only required if they contain special characters or reserved words):

String literals and identifiers quoting

Strict SQL92 rules are applied regarding string literals and identifiers quoting.

String literals (constants) must be surrounded with single-quote characters. e.g. WHERE a_field = 'a_value' Identifiers (column names and tables names) can be used unquoted if they don’t contain special characters or are not a SQL reserved keyword. Otherwise they must be surrounded with double-quote characters. e.g. WHERE "from" = 5.

This works:

ds = gdal.Warp('first-right.tif', 'ndvi.tif', format = 'GTiff',
                cutlineDSName='parcel.shp',
                cutlineWhere='name = 'first'')

Or

ds = gdal.Warp('first-right.tif', 'ndvi.tif', format = 'GTiff',
                cutlineDSName='parcel.shp',
                cutlineWhere="name = 'first'")

enter image description here

Correct answer by user2856 on October 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP