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.

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

  • Yes, I've seen that post (I link it in my question), but that is not exactly what I am trying to achieve, I need the outside pixels to be set to a specific value, not just an alpha channel. – amaurs Jun 24 '16 at 15:32

It is -dstnodata you are asking for, not -dstalpha:

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

gdalwarp sets the area outside the -cutline polygon to -dstnodata, which can be a specified value (or one for each band), the nodata values from the input data set, or, if none of the two is available, some default value, which however is not set as nodata value on the output dataset. I don't know how GDAL determines that default value, but for Byte data, it is zero.

An alternative solution that was proposed here "is to use gdal_translate with -projwin to extract to shape envelope and then gdal_rasterize with -i to burn nodata where shape is missing." This solution also circumvents raster shifting or resampling.

But all of these are using GDAL command line tools.

Set one image to the values you want, copy the full file name of said raster, insert full file name into script below, and drop this script in Python box. Hit enter+enter and sit back and relax.

mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd, "")[0] refLayer = arcpy.mapping.ListLayers(mxd, "ReplaceWithNameofRaster.tif", df)[0] for Layer in arcpy.mapping.ListLayers(mxd, "", df): ... arcpy.mapping.UpdateLayer(df, Layer, refLayer)

  • The problem with this solution is that an ArcGIS installation is need. Thanks. – amaurs Jul 29 '16 at 15:35

Today, the pythonic solution would be to use rasterio. For clipping a raster with a polygon, they have an example in their docs.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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