[GIS] Use Values from Raster Statistics (e.g. sum of all cells) in Raster Calculator

qgisrasterraster-calculator

I need to do calculations on raster layers which require the sum of all cells of the raster. I've used the zonal statistics tool for that but it gets a little annoying to do those extra steps (run the plugin, open the Attribute table, copy the sum…).

Is there a way I can calculate and use the values of raster statistics directly inside a raster calculator?

Even better would be to calculate those values from a raster created in the same step:

A*B*C / Sum (A*B*C)

Best Answer

A calculation like

A*B*C / Sum (A*B*C)

will perform the A*B*C operation twice. To avoid that duplicate effort instead do it in two steps

X = A*B*C
X / Sum(X)

Storing A*B*C has an immediate payoff. To implement the Sum operation, use a zonal summary operator with the entire raster as the zone. That requires placing a constant, non-null value at every non-null cell of the raster. A simple way to accomplish this is to equate the raster with itself, thus:

ZonalSum(X, X==X)

(The syntax for ZonalSum will depend on the platform and the version of the software.)

The full workflow therefore is

X = A*B*C
X / ZonalSum(X, X==X)
Related Question