Subtractions and divisions are not possible when using the QGIS Raster Calculator from a python script within the QGIS python console: Error code:4 (Parsing Error?). Additions and Multiplications work well. PYthon 2.7, QGIS 2.14 & 16.

import qgis.core, processing, glob, 
from qgis.core import QgsMapLayerRegistry, QgsRasterLayer
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry

InputPath = "D:/Heckmann.M/NigerABN/1_Projekte/14_Landsat/trialcbs/"
band2Path = glob.glob(InputPath+"*_sr_band2.tif")[0]
band5Path = glob.glob(InputPath+"*_sr_band5.tif")[0]
rband2 = QgsRasterLayer(band2Path, "name2")
rband5 = QgsRasterLayer(band5Path, "name5")
iface.addRasterLayer(band2Path, "Band2")
iface.addRasterLayer(band5Path, "Band5")
outputPathQ = "D:/Heckmann.M/NigerABN/1_Projekte/14_Landsat/trialcbs/QGIS_35_sub7.tif"

def calc_MNDWI(green, MIR, rasterFile, MNDWI_file):
    entries = []
    # Define band GREEN 
    green = QgsRasterCalculatorEntry()
    green.ref = 'green@1'
    green.raster = rband2
    green.bandNumber = 1

    MIR = QgsRasterCalculatorEntry()
    MIR.ref = 'MIR@1'
    MIR.raster = rband5
    MIR.bandNumber = 1

    calc = QgsRasterCalculator('(MIR@1-green@1)', MNDWI_file, 'GTiff',  rasterFile.extent(), rasterFile.width(), rasterFile.height(), entries)
    print "Calculation Result", calc.processCalculation()
    iface.addRasterLayer(MNDWI_file,'MNDWI QGIS')

calc_MNDWI(band2Path,band5Path, rband2, outputPathQ) 
  • 1
    Try putting double quotation marks when calling your raster. E.g. calc = QgsRasterCalculator('("MIR@1" - "green@1")',...) – Joseph Sep 5 '16 at 10:44

Your Answer

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

Browse other questions tagged or ask your own question.