I am looking for developing python codes mainly for working with raster data, in particular satellite imagery from Landsat. I am familiar with GIS and RS and I usually work with QGIS, but I am new in python programming. I tried to write a script to calculate NDVI, such a first training sample, and I found a python code to make NDVI and to run in QGIS but in my case it doesn't work. Can anyone help me to understand why? I am working with the last version of QGIS Essen 2.14 and the code I used is the following:
#Calculate NDVI for QGIS
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
def NDVI (band4,band5,output):
entries=[ ]
#define raster 1 (band4)
raster1=QgsRasterCalculatorEntry()
raster1.ref='band4@1'
raster1.raster=band4
raster1.bandNumber=1
entries.append(raster1)
#define raster 2 (band5)
raster2=QgsRasterCalculatorEntry()
raster2.ref='band5@1'
raster2.raster=band5
raster2.bandNumber=1
entries.append(raster2)
#NDVI Processing
calc=QgsRasterCalculator('(band5@1+band4@1)/(band5@1-band4@1)',output,'GTiff',band4.extent(),band4.width(),band4.height(),entries)
calc.processCalculation()
canvas=qgis.utils.iface.mapCanvas()
layers=canvas.layers()
layers[0].name()
layers[1].name()
NDVI(layers[1],layers[0],'C:\Users\.....')
I would like to use it both to run like a script in the Python console of the QGIS, as well as to made a tool for the for the scripts in the processing toolbox (“create new script”).
Is it possible to save it as temporary file in the script, instead of giving a path?
Indeed the script as I wrote runs, but it doesn't produce any output. But, by putting quotes as suggested by Matte, the script works well and produces results although something wrong is happening because the resulting NDVI is not correct. I need to review it.