1

I'm trying to write a Python script in QGIS 2.18.16 to use zonal statistics of a multi-band raster (GeoTIFF) using a polygon shapefile.

QGIS crashes turning off so I can't get any error message to correct my code.

I'm working in Ubuntu 16.04 64 bit.

Am I doing something wrong or is there a bug in QGIS?

import processing 
vectorlayer = qgis.utils.iface.mapCanvas().layer(0)
rasterfile = qgis.utils.iface.mapCanvas().layer(1).source()

processing.runalg("qgis:zonalstatistics", rasterfile, 3, vectorlayer, "Zonal_", True, "/media/giacomo/4A48-5E67/prova/out.shp")
2
  • 2
    Did you type print vectorlayer and print rasterfile to ensure you're using the correct order of layers?
    – Joseph
    Jan 31, 2018 at 15:12
  • Hi. Yes, it is a multiple bands raster.
    – ilFonta
    Feb 3, 2018 at 11:53

1 Answer 1

0

I solved in this way.

from qgis.analysis import QgsZonalStatistics

pathFileRaster = "G:\\prova\\VHVV.tif"
pathFileVector = "G:\\prova\\ROI_polygons_Rothamsted_2014-2015\\ROI_polygons_Rothamsted_2014-2015.shp"

pathFileRasterQgs = QgsRasterLayer(pathFileRaster, "stack")
pathFileVectorQgs = QgsVectorLayer(pathFileVector, "ROI", 'ogr')

nBands = pathFileRasterQgs.bandCount()
listBands = range(1, (nBands+1))

for iBand in listBands:

    calc = QgsZonalStatistics(pathFileVectorQgs, \
    pathFileRaster , \
    'b_', \
    int(iBand), \
    QgsZonalStatistics.Mean #because I need only the mean)

    calc.calculateStatistics(None)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.