I am creating a QGIS plugin a part of which is like the SAGA Rasters sum tool. The user interface will have a widget to which the user will load the raster layers. I am trying to get the pixel-wise sum of values of the loaded rasters.
Like if the user loads 3 rasters R1, R2, R3 then for a pixel Pij, having values 5, 7 and 6 in R1, R2 and R3 respectively, in the new raster Pij = R1ij+R2ij+R3ij = 5+7+6 = 18
I am stuck up with both - creating the UI and the calculations.
So the first part of my question is about creating a QListWIdget and dragging and dropping the layers into the widget and using these layers for additions. The best I could get to was to add the QListWidget into the UI using QtCreator. Couldn't get to add and call layers from the QListWidget.
Here is the code I used with a push button to add layers in the QListWidget, but the layers add as a single row and I don't know how to use these for the actual calculations.
def add_rasters(self):
name=QFileDialog.getOpenFileNames(self.dlg, 'Select Rasters', '','*.tif')
name_str = str(name)
list = []
list.append(name)
self.dlg.listWidget.insertItem(2,name_str)
self.dlg.pushbutton.clicked.connect(self.add_rasters)
Using the above code the ListWidget gets filled up like:
(['C:/QGIS_plugin/rstr1.tif', 'C:/QGIS_plugin/rstr2.tif', 'C:/QGIS_plugin/rstr3.tif'], '*.tif')
Next I am querying about the calculations:
I can do the addition calculation by manually adding up all the layers in the list; but I could not figure out a way to do the calculation automatically for n-number of the layers loaded in the widget.
Below is my code for addition of layers already loaded in the QGIS map project.
import processing
from qgis.core import *
from PyQt5.QtCore import *
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
entries = []
myList=[layer for layer in QgsProject.instance().mapLayers().values()]
print(my_list)
for i in range(0, len(myList)):
raster = myList[i]
#readRst = QgsProcessingUtils.mapLayerFromString(raster)
ras1 = QgsRasterCalculatorEntry()
ras1.raster = raster
ras1.ref = "ext_lyr" + str(i+1) +"@1"
ras1.bandNumber = 1
entries.append(ras1)
formula = '(' + entries[0].ref + ' + ' + entries[1].ref + ')'
output = r"C:/QGIS_plugin/rstrs_sum.tif"
calc = QgsRasterCalculator(formula, output, 'GTiff', raster.extent(), raster.width(), raster.height(), entries)
calc.processCalculation()
I am afraid that I am unable to frame this question properly (mixing two questions), but I am myself not sure how this would work best. I have gone through several posts on this site and now I am completely lost!
I am quite new to python programming and QGIS, hence need help with the simplest things also. Hoping to get some help here with this.