Sunday 23 August 2015

gdal - How to conditionnally assign a new value to pixels of a raster image?


Given a topographic GIS raster of one country crop.tif:


Given a know pixel value such as elevation (z) is +73 :


$ gdallocationinfo crop.tif 1 1 -valonly
> 73


Given an elevation threshold n = 50 (meters)


How to set the value of all/this pixels where z >= n to 50 ?


The solution should be with gdal or in console.




Related to : Gdal: How to get a pixel's value from raster image?, gdal_polygonize.py.




EDIT: I eventually used the formula --calc="50*(A>50)" --NoDataValue=0 standing for "new calc where value set as 50 when value in input A > 50, else value set as 0"



gdal_calc.py -A input.tif --outfile=result.tif --calc="50*(A>50)" --NoDataValue=0





Answer



The best all round tool here is a raster calculator.


gdal_calc is a GDAL raster calculator implemented in Python here, with some examples here.


If you e.g. wants to keep values above +50:


gdal_calc.py -A input.tif --outfile=result.tif --calc="A*(A>50)" --NoDataValue=0

You can specify several files -A to -Z, where each of them get a corresponding variable in the expression.


In this case, the boolean expression (A>50) returns either 1 or 0, and is then multiplied with A. The result is then stored in the corresponding pixel in outputfile.


Not sure if you need a programmatic approach or a manual one, but QGis has a raster calculator. See related question with answer here.



No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...