Using QGIS Zonal Stats Plugin from Python Console?

The below code worked for me QGis 1.8.0

You might modify this to accomodate multiple files with some loop..

from qgis.analysis import QgsZonalStatistics

#specify polygon shapefile vector
polygonLayer = QgsVectorLayer('F:/temp/zonalstat/zonePoly.shp', 'zonepolygons', "ogr") 

# specify raster filename
rasterFilePath = 'F:/temp/zonalstat/raster1.tif'

# usage - QgsZonalStatistics (QgsVectorLayer *polygonLayer, const QString &rasterFile, const QString &attributePrefix="", int rasterBand=1)
zoneStat = QgsZonalStatistics (polygonLayer, rasterFilePath, 'pre-', 1)
zoneStat.calculateStatistics(None)

Here is way to get what you want in SAGA GIS. This probably isn't the solution you want, but it works. I'll look into the reasons why my plugins fails and update it as soon as possible.

Install SAGA GIS (should also be available via apt-get or aptitudbe in your linux distribution).

  • Start SAGA, load in your Raster and vector shape (Menu Modules -> File -> GDAL/OGR import). You can see the process below.
  • Execute Module "Grid statistics for polygons" (Menu Modules -> Shape -> Grid -> Grid-values). Values are added directly to the table. The Dialog should look like thisenter image description here
  • Go to the tab "Data" in the workspace, rightclick on your vector layer and choose to "save as" to export the shape with the added attributes. You could also display the attribute table via rightclick and then click on table show

This works for the dataset you sent me. It is also possible to call SAGA modules in QGIS via SEXTANTE as a BATCH process. To do this simply activate the SAGA modules in the SEXTANTE options.


zoneStat = QgsZonalStatistics (polygonLayer, rasterFilePath, 'pre-', 1)
zoneStat.calculateStatistics(None)

calculates by default just Count, Sum and Mean (as you can tell from Raster -> Zonal Statistics in QGIS Desktop, it can do a lot more).

If you, for instance, want to compute just the Mean you have to use:

zoneStat = QgsZonalStatistics (polygonLayer, rasterFilePath, 'pre-', 1, QgsZonalStatistics.Mean)
zoneStat.calculateStatistics(None)

see API for all options.