[GIS] Clip raster with shapefile and set a value outside the mask

gdalgdalwarppythonrastershapefile

I want to clip a raster using a shapefile with the command:

gdalwarp -cutline INPUT.shp INPUT.tif OUTPUT.tif

From this answer. However I want to set the pixels outside the mask to a particular value (-9999 for example). I want to do it with gdalwarp so I can perform the same process in several files (In other words I don't want to use QGIS, ArcGIS, or any similar package). A Python programmatic approach would also be desirable, as currently I am calling gdalwarp from a Python script.

Best Answer

You need to use the -dstalpha option to gdalwarp e.g.:

gdalwarp -cutline INPUT.shp -crop_to_cutline -dstalpha INPUT.tif OUTPUT.tif

This will add an alpha band to the output tiff which masks out the area falling outside the cutline.

P.S. duplicate question