I am using the Zonal Stats plugin in QGIS to extract raster statistics from overlaying polygons (I have shapefiles of species distribution and I want to extract environmental data from within each species' range). I have 300 or so files I need to get data from and so would like to write a script to run in the python console, however I am a complete novice with python and have no idea how to do this.
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)
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.
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 this
- 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.