This one drove me crazy today! If you try to sum values from rasters with different extent, the raster calcultor clips the result to their overlapping zone. This might make sense in most cases, but in many other cases it absolutely does not. Users should have a choice.

An old workaround (2013) is proposed on a page called Raster extent modification using QGIS. A Russian geographer wrote a QGIS 2.8 addon still available in the form of a python script. Most of his code handles the GUI, though, wich makes it complex and thus harder to adapt to QGIS 3.16.

For a fast solution, here is my proposal of a python script. It unifies the extent of all rasters in a folder (path/to/your/tiffs) . To use it, copy-paste it directly in the python script editor of QGIS, edit the path to your tiffs, and execute it. To access the script editor, click on buttons 1 and 2. To execute, button 3 :

import processing
from os import listdir
import re

# Get a list of all tif files in the directory
basedir = "path/to/your/tiffs"
files = listdir(basedir)
r = re.compile(".tif")
tifoutfiles = list(filter(r.match, files))

# Merge all the files to produce a single tif file covering all their extents.
tempmergefile = basedir + "tempmergefile.tif""gdal:merge", {'INPUT':tifoutfiles,'PCT':False,'SEPARATE':False,'NODATA_INPUT':None,'NODATA_OUTPUT':None,'OPTIONS':'','EXTRA':'','DATA_TYPE':5,'OUTPUT':tempmergefile})

# Then multiply the values of this tif file by 0. This produces a clean uniform raster of the desired extent.
tempmergefile2 = basedir + "tempmergefile2.tif""qgis:rastercalculator", {'EXPRESSION':'\"tempmergefile@1\" * 0','LAYERS':[tempmergefile],'CELLSIZE':0,'EXTENT':None,'CRS':None,'OUTPUT':tempmergefile2})

# Last, merge clean uniform raster with each original tif file. Careful: this loop only works if all "*-unified.tif" files created in a preceding run are erased beforehand in the directory
for t in tifoutfiles:
    outfile = t[0:-4] + "-unified.tif"
    print(outfile)"gdal:merge", {'INPUT':[t,basedir + 'tempmergefile2.tif'],'PCT':False,'SEPARATE':False,'NODATA_INPUT':0,'NODATA_OUTPUT':None,'OPTIONS':'','EXTRA':'','DATA_TYPE':5,'OUTPUT':outfile})
    outlayername = t.split("/")[-1][0:-4] + "u"


Leave a comment

Your email address will not be published. Required fields are marked *