Wednesday, 7 August 2019

pyqgis - Using QGIS Zonal Stats Plugin from Python Console?


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.



Answer



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)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...