3

I have a couple hundred raster files that I want to find the sum for in order to perform some further calculation. I want to have the sum of each raster file placed in one Excel sheet.

enter image description here

I used to work on ArcGIS, so usually I would just use Model Builder to iterate the procedure, then save it all to an attribute table and export to CSV.

But now I no longer have access to ArcGIS, and I realized that you can't iterate in the QGIS graphical modeler. Is there a simple way to do this? I would prefer doing it without any scripting or code, because I just need to get this done quickly, but if it's absolutely necessary I don't mind.

0
3

In case you won't get any luck with QGIS modeller, you can run this script with QGIS python console:

enter image description here

The script:

from os import listdir

import processing

rast_dir='/raster/directory/'

ext_tpl=('tif','TIFF','TIF') #change if there are other raster formats in your directory

rast_lst=[fl for fl in listdir(rast_dir) if fl.endswith(ext_tpl)]

out_fl='outputfiledir/outputfile.csv'

with open(out_fl,'w') as fl:
    fl.write('raster_name,sum\n')
    for rast in rast_lst:
        
        res=processing.run("native:rasterlayerstatistics",
                            {'INPUT':rast_dir+rast,'BAND':1})
        rast_sum=res['SUM']
        fl.write(f'{rast},{rast_sum}\n')
5
  • 2
    @BERA yes, in case if extension is 'tif', or rast_lst=[fl for fl in listdir(rast_dir) if fl.endswith(('tif','TIFF','TIF'))] can be used, or any other tuple with extension, I'll edit the answer, thank you
    – YevKad
    Dec 31 '20 at 10:20
  • This works perfectly, thank you very much!
    – Ismail
    Dec 31 '20 at 11:20
  • I'd like to ask another question, is there any way to do the same thing but for mean instead of sum. I tried using res['MEAN'] instead of rast_mean=res['SUM'] but i don't think that exists...
    – Ismail
    Dec 31 '20 at 11:36
  • @Ismail hm, res["MEAN"] works fine for me. here's all the parameters available from my example: {'MAX': 148.0, 'MEAN': 71.44134233153648, 'MIN': 0.0, 'RANGE': 148.0, 'STD_DEV': 50.53710384890273, 'SUM': 4347348635.0, 'SUM_OF_SQUARES': 155415938959.4372}
    – YevKad
    Dec 31 '20 at 12:00
  • Ah yes it works, I just got a wierd error message but the excel file came out as i wanted it to
    – Ismail
    Dec 31 '20 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.