I have the following code which I have no problem executing within QGIS (2.8.6) via the python console. What the script does is it adds the two raster layers in my directory via the Raster Calculator:
from osgeo import gdal
from osgeo import ogr
from gdalconst import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
from qgis.analysis import *
from qgis.gui import *
import sys
import glob
import re
import os, fnmatch
import numpy as np
import numpy.ma as ma
import math
import subprocess
qgisprefix = '/usr'
# configure paths for QGIS
os.environ['PATH'] = qgisprefix+'/bin'
os.environ['LD_LIBRARY_PATH'] = qgisprefix+'/lib'
sys.path.insert(0, qgisprefix+'/share/qgis/python')
sys.path.insert(1, qgisprefix+'/share/qgis/python/plugins')
# disable QGIS debug messages
os.environ['QGIS_DEBUG'] = '-1'
# configure QGIS paths
QgsApplication.setPrefixPath(qgisprefix, True)
# initalise QGIS (load providers)
QgsApplication.initQgis()
#Load all the rasters
outputFolder = "/home/usr/Desktop/Output/"
extent = QgsRectangle(264885.85754, 5073773.01243, 614325.85754, 5295173.01243)
numCols = 11648
numRows = 7380
os.chdir("/home/usr/Desktop/")
entries = []
for fname in glob.glob("*.tif"):
fileInfo = QFileInfo(fname)
baseName = fileInfo.baseName()
rasterLayer = QgsRasterLayer(fname, baseName)
QgsMapLayerRegistry.instance().addMapLayer(rasterLayer)
mc = iface.mapCanvas()
Layers = mc.layers()
for each_layer in Layers:
layerR = QgsRasterCalculatorEntry()
layerR.ref = each_layer.name() + '@1'
layerR.raster = each_layer
layerR.bandNumber = 1
entries.append(layerR)
expression = '('+entries[1].ref+'+'+entries[0].ref+')' #re-write that to include all rasters
calc = QgsRasterCalculator(expression, "/home/usr/Desktop/Output/final.tif",'GTiff',extent,numCols,numRows,entries)
calc.processCalculation()
When I try to execute the same code outside QGIS in a standalone script, I get no errors but there is nothing in my Output
folder. What should I adapt in order to be able to run the script outside of QGIS?