As to the SAGA Raster calculator (QGIS Processing Toolbox | SAGA | Raster calculus | Raster calculator
).
SAGA formula is:
ifelse(or(b > 3, b = 3), a + 1, a)
A catch is that b >= 3
becomes OR(b>3, b=3)
. OR(x,y)
returns true (1), if at least one of both x, y is true.
I think it's easier to use GDAL raster calculator. I execute the tool manually once in QGIS, press Ctrl+Alt+H and copy the command. Then write the loop.
To create the output names you can use layer.source()
and os.path.join
with os.path.basename
.
For first band, and mean:
import os
output_folder = r'/home/bera/Desktop/GIStest/rasters/'
for layer in QgsProject.instance().mapLayers().values(): #For all layers in the map
print(layer)
#########Extract first band
#Create the output name
#layer.source()
#'/home/bera/Desktop/GIStest/4bandraster.tif'
#os.path.basename(layer.source()) #
#'4bandraster.tif'
output1 = os.path.join(output_folder, os.path.basename(layer.source()).replace('.tif', '_firstbandonly.tif'))
#'/home/bera/Desktop/GIStest/rasters/4bandraster_suffix.tif'
processing.run("gdal:rastercalculator", {'INPUT_A':layer,'BAND_A':1,'INPUT_B':None,
'BAND_B':None,'INPUT_C':None,'BAND_C':None,'INPUT_D':None,'BAND_D':None,
'INPUT_E':None,'BAND_E':None,'INPUT_F':None,'BAND_F':None,'FORMULA':'A',
'NO_DATA':None,'RTYPE':5,'OPTIONS':'','EXTRA':'','OUTPUT':output1})
########Mean of bands 1,2,3,4:
output2 = os.path.join(output_folder, os.path.basename(layer.source()).replace('.tif', '_mean1234.tif'))
processing.run("gdal:rastercalculator", {'INPUT_A':layer,'BAND_A':1,'INPUT_B':layer,'BAND_B':2,'INPUT_C':layer,'BAND_C':3,'INPUT_D':layer,'BAND_D':4,'INPUT_E':None,'BAND_E':None,'INPUT_F':None,'BAND_F':None,'FORMULA':'(A+B+C+D)/4','NO_DATA':None,'RTYPE':5,'OPTIONS':'','EXTRA':'','OUTPUT':output2})
print("Done")
Best Answer
WHY THIS HAPPENS:
From your screenshots it looks as if some of your layers have cells without data (NA-values). Otherwise it would not be possible to display the layers above each other (unless you have set specific values to be transparent).
If you perform calculations on cells with NA-values e.g.
NA + x
orNA * x
(x being a decimal or integer value) the raster calculator will yield results that are also NA for the given cell.This is, why you have output for just a few cells - these are cells, where all 4 overlapping layers hold a non-NA value.
WHAT TO DO ABOUT IT:
Depending on the goal of your calculation (not clearly stated). I would recommend you:
Fill NoData Cells
tool. This will replace NA with a given value.