I would like use r.mapcalculator in a PyQGIS processing script to change values from one raster in another accordingly. I don't know how to call the variables row and col, which are now read as simple strings in the following code:

processing.runalg('grass:r.mapcalculator',{"amap": rlayer, "bmap": emptylayer, 
"formula": "amap[row,col]=bmap[(%i+row*%i),(%i+col*%i)]"% (offset,scale,offset,scale), 
"GRASS_REGION_PARAMETER": "%f,%f,%f,%f"% (xmin, xmax, ymin, ymax), "outfile": bdry_resamp})

Does anyone know the correct syntax to use this?

It would be fine to do it manually calling the module from the processing toolbox in QGIS as well, but then I would have to specify the 'formula' as well.

1 Answer 1


For completness also here: I am not familiar with the peculiarities of Processing in PyQGGIS. However, a map-calculator command like:

r.mapcalc expression="amap=bmap[1,1]"

would make “amap” a copy of “bmap” where pixel values are shifted one pixel to the left and one up.

Thus, you processing formula might look like this (not tested...):

"amap=bmap[(%i+%i),(%i+%i)]"% (offset,scale,offset,scale)

See also: https://grass.osgeo.org/grass73/manuals/r.mapcalc.html#the-neighborhood-modifier

Edit: OK, obviously I did not read your question carefully enough. Use r.mapcalc (and not r.mapcalculator), upated code above.

  • I only did some initial test to run your suggestion in a script and manually with the formula 'amap=bmap[30,30]'. The former doesn't give any error (and no result), the later a 'Parse error' for the formula in the log file. I guess I only did something small wrong and it could work as you suggest. However, I now solved it by reading both raster with gdal.Open(), reading the data as a array with band.ReadAsArray(0, 0, cols, rows), iterating over all rows and columns, writing the modified values to a new array and writing that to a new raster with gdal.GetDriverByName('GTiff').Create(). Nov 21, 2016 at 12:14

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.