GDAL QGIS Raster Conversion – Convert QGIS Raster Calc Expression to Valid Syntax for gdal_calc

gdalgdal-calcqgisraster-calculator

I have been using QGIS Raster Calculator to patch Raster Bs values in where Raster As are 0 using the below expression

("A@1" = 0) * "B@1" + ("A@1" != 0) * "A@1"

I now want to do this using gdal_calc within a python script, but it keeps throwing up the error that my formula is an invalid syntax. How can I achieve the same results?

gdal_calc --calc "(A = 0) * B + (A != 0) * A" --format GTiff --type Float32 -A C:\Users\Public\try\A.tif --A_band 1 -B C:\Users\Public\try\B.tif --B_band 1 --outfile C:/Users/public/OUTPUT.tif

Best Answer

gdal_calc uses python syntax. In python = is used for variable assignment and == is for equality checking.

E.g.

>>> a = 123   
>>> print(a)
123 
>>> a == 123
True
>>> a == 1234
False

So the following should work:

gdal_calc --calc "(A == 0) * B + (A != 0) * A" --format GTiff --type Float32 -A C:\Users\Public\try\A.tif --A_band 1 -B C:\Users\Public\try\B.tif --B_band 1 --outfile C:/Users/public/OUTPUT.tif
Related Question