I'm newbie to programming in pyqgis.
I need to perform a simple "GeoTiff * A" type of calculation(where A is a constant), but I am struggling to do so.
I tried processing.runalg('saga:rastercalculator') but failed 'coz my constant is NOT a raster.
I suppose I should be using 'qgismodelertools:calculator' or possibly something like to what they use here http://geoexamples.blogspot.it/2012/12/raster-calculations-with-gdal-and-numpy.html
Gene's answer iss succinct and logical but rasterio does not come out of the QGIS 2.8 box, which I'm using from OSGEO4W.
In the meantime, I used EikeMike's useful code by turning it into a working, callable function:
def raster_calc(RGBI_DS,outFile,constant): import processing, os, time, subprocess, array from osgeo import gdal from osgeo.gdalnumeric import * from osgeo.gdalconst import * # Read Raster dataset GDALRgbiDS = gdal.Open(RGBI_DS, GA_ReadOnly ) band1rot = GDALRgbiDS.GetRasterBand(1) # Convert band to Array Rdata = BandReadAsArray(band1rot) * 1.0 # calculate raster * constant dataOut = (Rdata * constant) # Export result as Geotiff driver = gdal.GetDriverByName("GTiff") dsOut = driver.Create(outFile, GDALRgbiDS.RasterXSize, GDALRgbiDS.RasterYSize, 1, gdal.GDT_Float32) CopyDatasetInfo(GDALRgbiDS,dsOut) bandOut=dsOut.GetRasterBand(1) BandWriteArray(bandOut, dataOut) #Deletion of variables, this actually triggers the writing of the output file dsOut =None bandOut = None driver =None
Later, I found myself a much easier and shorter solution.
Here it is:
Stick to 'saga:rastercalculator' (or similar algorithm). Simply build the mathematical formula therein as a new variable where your constant is itself a variable. In other words:
import processing formula = ('a * %s' % (str(constant))) # where 'a' is going to point to yourraster and 'constant' is the numeral you want to multiply your raster by processing.runalg('saga:rastercalculator',yourraster,None,formula,outFile)