TransWikia.com

NDVI calculation

Geographic Information Systems Asked by PiyaphatC on November 9, 2021

I am a newbie in PyQGIS. 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:parkLT05_L1TP_131047_19871207_20170418_01_T1_B3.tif'

land_4 = 'D:parkLT05_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:QGISappsPython37libcode.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.

One Answer

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]

Answered by Houska on November 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP