To cut a raster I saw some solutions suggesting gdalwarp with cropToCutline and cutlineSQL options.

poly = item.geometry.asWkt()
ds = 'raster.tif'
sql = f"select ST_GeomFromText('{poly}',4326)"
finaloutwarp = 'warped.tif'  
g = gdal.Warp(finaloutwarp, ds, cropToCutline=True, cutlineSQL=sql, format="GTiff")
g = None

But the output is the same as the input ds dataset. Not sure where it is going wrong. Here item.geometry is a QgsRubberband geometry. Any other method is also welcome.

  • In ArcGIS you can use the tool extract by mask. Commented Jul 25, 2021 at 4:48
  • 1
    I need to plug this code in a QGIS Plugin so no option of ArcGIS Commented Jul 25, 2021 at 5:05
  • Is there any error thrown. You have a type in your query, it should be an space between select and ST_GeomFromText Commented Jul 25, 2021 at 9:07
  • @Francisco No that was just a typo in the question.Edited now. Commented Jul 25, 2021 at 9:51
  • is your raster in epsg:4326?
    – Ian Turton
    Commented Jul 26, 2021 at 7:24

1 Answer 1

from osgeo import gdal

gdal.Warp(destNameOrDestDS = outputpath, # directory output
          srcDSOrSrcDSTab  = inputpath, # directoy intput
          cutlineDSName    = shapefile or geojson, # vector file
          cropToCutline    = True, # Select True
          copyMetadata     = True, # optional
          dstNodata        = 0)    # if you have values of zeros

Your Answer

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

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