[GIS] Compare two raster extents in QGIS

pythonqgisrasterraster-calculator

I have two grids, grid A representing observed extents of flooding and grid B representing simulated extents from a hydraulic model. The rasters have the same extent and grid size.

I want to be able to compare each pixel and create a new raster with 4 unique values (A/B/C/D equivalent in the table below) to show the difference between the two rasters:

enter image description here

If this was a shapefile field calculator problem I'd use a CASE logic like the one below but I'm struggling to identify a QGIS raster-based equivalent. Can anyone suggest anything I could try?

CASE
    WHEN "Modelled" > 0 AND "Observed" > 0 THEN D
    WHEN "Modelled" = 0 AND "Observed" > 0 THEN C
    WHEN "Modelled" > 0 AND "Observed" = 0 THEN B
    WHEN "Modelled" = 0 AND "Observed" = 0 THEN A
END

Best Answer

You can use the QGIS raster calculator for this, using boolean masks. An example:

(("grid1@1">0) AND ("grid2@1">0)) * 1
+ (("grid1@1"=0) AND ("grid2@1">0)) * 2
+ (("grid1@1">0) AND ("grid2@1"=0)) * 3
+ (("grid1@1"=0) AND ("grid2@1"=0)) * 4

where you can change 1, 2, 3, and 4 to be whatever values you like.

The way that this works is that the first part of each term is a boolean mask. ("grid1@1">0) AND ("grid2@1">0)) is True when your first condition is met, and it can be multiplied by your categorical value D (I used 1). The next three terms match your next three conditions.

Note

Steven Kay notes in the comments that the same expression can be performed without using AND by replacing it with a *. In this case, the first term looks like

(("grid1@1">0) * ("grid2@1">0)) * 1
Related Question