2

I start to write my own simple code to automatically calculate NDVI from Landsat 5.

Here is my code:

from PyQt5.QtGui import *
from qgis.analysis import *

land_3 = 'D:\park\LT05_L1TP_131047_19871207_20170418_01_T1_B3.tif'
land_4 = 'D:\park\LT05_L1TP_131047_19871207_20170418_01_T1_B4.tif'

rasterb3 = iface.addRasterLayer(land_3, "B3")
rasterb4 = iface.addRasterLayer(land_4, "B4")

ir = QgsRasterCalculatorEntry()
r = QgsRasterCalculatorEntry()

ir = rasterb4
r = rasterb3

arr = (ir, r, ir, r)

exp = "1.0*(%s-%s)/(1.0*(%s+%s)"%arr

output = 'D:\\park\\output.tif'
e = rasterb3.extent()
w = rasterb3.width()
h = rasterb3.height()
entries = [ir,r]
ndvi = QgsRasterCalculatorEntry()
ndvi = QgsRasterCalculator(exp, output, "GTiff", e, w, h, entries)

ndvi.processCalculation()

lyr = iface.addRasterLayer(output,"NDVI")

But this error shown up:

Traceback (
most recent call last):
  File "D:\QGIS\apps\Python37\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 25, in <module>
TypeError: index 0 has type 'QgsRasterLayer' but 'QgsRasterCalculatorEntry' is expected.
3
  • which line gives the error? It doesn't look like it's e = rasterb3.extent(), but line 25 is that in your code.
    – Noura
    Commented Jun 9, 2020 at 10:08
  • my 25th line is ndvi = QgsRasterCalculator(exp,output,"GTiff",e,w,h,entries)
    – PiyaphatC
    Commented Jun 9, 2020 at 10:22
  • 2
    there is a missing parentheses in your exp
    – radouxju
    Commented Mar 23, 2021 at 8:08

1 Answer 1

0

I think your assignments aren't setting up QgsRasterCalculatorEntry properly. Right now, first you make ir (and r) empty QgsRasterCalculatorEntries. Then you reassign them to be the corresponding layers. That doesn't initialize them to have the right values as a QgsRasterCalculatorEntry, but reassigns them to be the layer instead. Then exp uses string operations, but I doubt passing 4 layers to string concatenation coerces that to the layer names (I'm not sure).

The correct way to do this can probably be gleaned from How to evaluate raster calculator expressions from the console? I think you're on the right track I think with using QgsRasterCalculatorEntry, but you will need to set its .ref and .raster manually, and then use the .ref in setting up your exp.

[Not tested, not at my QGIS machine today]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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