[GIS] Replacing 0 values of a raster with values from another raster in QGIS

qgisrasterraster-calculatorsaga

What I want to do is pretty straight forward: I have two raster with the same crs, resolution and extent. Both rasters show the number of days an area is flooded so they just have two values. Raster a consists of 0 and 183; raster b of 0 and 149. Logically, the area that is flooded only 149 days (b) is a little bigger than the area that is flooded 183 days (a).

Now I want to combine both maps. The formula I think should work using the saga raster calculator is:

ifelse(eq(a,0), b, a) .

In my opinion it translates to "If a pixel of map a is equal to 0 then use the pixel value of map b if not, keep the pixel value of a" So the result should be a map having just three values: 183, 149 and 0, right? But no, the resulting map has all kind of weird (i cannot explain them) values where map a is 0 and map b is 149. It seems like some transition from 183 over 149 to 0.

Why is that, or is it a bug?

Ps: Here is an example for one of the grey pixels of the calculated map: a=0, b=149 but the calculated map has a value of 128.30
enter image description here

Best Answer

Solution using SAGA Raster Calculator

I performed a quick test and you should probably use this expression:

ifelse(a=0,b,a)

instead of the one you provided (also, choose 8 byte floating point number as Output Data Type parameter).

Using these sample rasters:

enter image description here

and the provided formula, I get:

enter image description here

where gray zones are equal to 149 and white zones are equal to 183 (there are also few cells with different values in the upper left of the raster, but I think it is due to the way with which I reproduced the problem, so the starting rasters maybe were not perfectly aligned).


EDIT

Solution using QGIS Raster Calculator

I have just found another approach, which seems to work. Use the QGIS Raster Calculator instead of the SAGA Raster Calculator: you will find it from Raster >> Raster Calculator.

Apply the first calculation using this expression:

("a@1"=0)* "b@1"

where a@1 is the raster A and b@1 is the raster B. This operation replaces all the 0 values from the raster A with the values from the raster B.

Then, do a second calculation on the previous result using this expression:

"result@1" + "a@1"

You will get this result:

enter image description here

as expected (I hope).

Related Question