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.
You might modify this to accommodate 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 rasterLayer = QgsRasterLayer('F:/temp/zonalstat/raster1.tif') # QGIS 3.22.6 - QgsZonalStatistics(QgsVectorLayer *polygonLayer, QgsRasterLayer *rasterLayer, const QString &attributePrefix=QString(), int rasterBand=1, QgsZonalStatistics::Statistics stats=QgsZonalStatistics::Statistics(QgsZonalStatistics::Count|QgsZonalStatistics::Sum|QgsZonalStatistics::Mean)) zoneStat = QgsZonalStatistics(polygonLayer, rasterLayer, '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.