[GIS] How to calculate zonal statistics from multi-band raster for each polygon using python

pyqgispythonqgisraster

I want to calculate the zonal statastics from multi band raster for a polygon layer. When I am using this snippet of code:

vectorlayer=qgis.utils.iface.mapCanvas().layer(0)
rasterfile = qgis.utils.iface.mapCanvas().layer(1).source()
zonalstats = qgis.analysis.QgsZonalStatistics(vectorlayer,rasterfile,"Zonal_")
zonalstats.calculateStatistics(None)

it is updating the field names but the values are NULL in the attribute table. So if I want to get the values to be updated, how can I do that?

Best Answer

Not sure why you're getting NULL values but the following code worked for me (note that I call the QGIS Zonal Statistics tool from the Processing plugin and I want to load the result):

vectorlayer = qgis.utils.iface.mapCanvas().layer(0)
rasterfile = qgis.utils.iface.mapCanvas().layer(1).source()
processing.runandload('qgis:zonalstatistics', rasterfile, 3, vectorlayer, "Zonal_", True, None)

The following is the help description for the parameters required which you can edit in your code:

>>>processing.alghelp("qgis:zonalstatistics")
    ALGORITHM: Zonal Statistics
        INPUT_RASTER <ParameterRaster>
        RASTER_BAND <ParameterNumber>
        INPUT_VECTOR <ParameterVector>
        COLUMN_PREFIX <ParameterString>
        GLOBAL_EXTENT <ParameterBoolean>
        OUTPUT_LAYER <OutputVector>

Hope this helps!