I think the best way to read in a raster for any purpose with Python/GDAL is by using a scanline and the unpack struct function. The code is more compact, the control is more effective and the execution time is faster than the one with 'ReadAsArray'. The scanline/struct method depends on fmttypes and their values can be supplied in a dictionary. In the next code I include a complete example of use to determine, by using the Python Console Editor of QGIS, the total average and the average by columns (only the first average value is printed) for values of a raster loaded in the Map View.
from osgeo import gdal
import struct
layer = iface.activeLayer()
provider = layer.dataProvider()
fmttypes = {'Byte':'B', 'UInt16':'H', 'Int16':'h', 'UInt32':'I', 'Int32':'i', 'Float32':'f', 'Float64':'d'}
path= provider.dataSourceUri()
dataset = gdal.Open(path)
band = dataset.GetRasterBand(1)
totHeight = 0
totColumns = 0
BandType = gdal.GetDataTypeName(band.DataType)
column_means = []
for x in range(band.XSize):
scanline = band.ReadRaster(x, 0, 1, band.YSize,1, band.YSize, band.DataType)
values = struct.unpack(fmttypes[BandType] * band.YSize, scanline)
for value in values:
totHeight += value
totColumns += value
column_means.append(totColumns/float(band.YSize))
totColumns = 0
average = totHeight / float((band.XSize * band.YSize))
print "Average = %0.5f" % average
print "First mean = %0.5f" % column_means[0]
dataset = None
The results (Average = 1824.71801, First mean = 1685.04298) were reached in only one second for my raster of 791 rows x 1680 columns (1,328,880 pixels) and 'Int16' band type.
processing.runalg("saga:leastcostpath", ...)