1

I am looking for developing python codes mainly for working with raster data, in particular satellite imagery from Landsat. I need to write a script (into the QGIS Script Editor) to make operations between Raster data and number (float). I know how to define the Raster but I don't know how to define the number to make it work. I am working with the last version of QGIS Essen 2.14 and I tried the following code to make a simple sum between a raster and number but it doesn't work:

##RED=raster
##a=number 0.5
##XXX=output raster

from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry

# Get layer object
layer1 = processing.getObject(RED)
# Get number
number1 = a

def xxx (RED,a,output):
    entries=[]

    #define raster 1 ("RED")
    raster1=QgsRasterCalculatorEntry()
    raster1.ref='RED@1'
    raster1.raster=RED
    raster1.bandNumber=1
    entries.append(raster1)

    #define number1 ("a")
    number1=QgsRasterCalculatorEntry()
    number1.ref='a'
    number1.float=a
    entries.append(number1)


    #XXX Processing
    calc=QgsRasterCalculator('("RED@1"+a)',output,'GTiff',RED.extent(),RED.width(),RED.height(),entries)
    calc.processCalculation()

xxx(layer1,number1,XXX)
  • Try replacing QgsRasterCalculator('("RED@1"+a)' with QgsRasterCalculator('("RED@1"+' + a + ')'. – Joseph Apr 21 '16 at 9:35
  • by replacing with '("RED@1"+'+a+')' I get the following message: "cannot concatenate 'str' and 'float' objects" – Nico_77 Apr 21 '16 at 10:14
  • 1
    Ah, forgot that it needs to be converted to string. Try replacing a with str(a), so that it reads QgsRasterCalculator('("RED@1"+' + str(a) + ')' – Joseph Apr 21 '16 at 10:19
  • The following layers were not correctly generated. XXX You can check the log messages to find more information about the execution of the algorithm – Nico_77 Apr 21 '16 at 13:08
  • I got it it is: – Nico_77 Apr 21 '16 at 13:15
2

I got it:

##RED=raster
##a=number 0.0
##XXX=output raster

import numpy
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry

# Get layer object
layer1 = processing.getObject(RED)
# Get number
number1 = a

def xxx (RED,a,output):
    entries=[]

    #define raster 1 ("RED")
    raster1=QgsRasterCalculatorEntry()
    raster1.ref='RED@1'
    raster1.raster=RED
    raster1.bandNumber=1
    entries.append(raster1)

    #define number1 ("a")
    number1='a'

    #XXX Processing
    calc=QgsRasterCalculator('("RED@1"+' + str(a) + ')',output,'GTiff',RED.extent(),RED.width(),RED.height(),entries)
    calc.processCalculation()

xxx(layer1,number1,XXX)
  • Way to go, nice one! :) – Joseph Apr 21 '16 at 13:19

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.