I composed this script in PyQGIS to perform the zonal statistics on a vector layer as for all its features at once, it works perfectly, when the script is finished, I inspected the attribute table and indeed it is fine for every feature in the vector layor.
from qgis.analysis import QgsZonalStatistics
from qgis.core import QgsRasterLayer, QgsVectorLayer
v_layer = QgsVectorLayer("gadm40_DEU_4.shp", "gadm", "ogr")
r_layer = QgsRasterLayer("Deutschland.vrt", "dem")
zone_stat = QgsZonalStatistics (v_layer, r_layer,
attributePrefix = 'dem_',
rasterBand = 1,
stats = QgsZonalStatistics.Statistics(
QgsZonalStatistics.Count|
QgsZonalStatistics.Max|
QgsZonalStatistics.Mean|
QgsZonalStatistics.Median|
QgsZonalStatistics.Min|
QgsZonalStatistics.StDev
)
)
zone_stat.calculateStatistics(None)
My goal is to do the same but not for whole vector layor at once, so iterate over features then do the zonal statistics because after each iteration I would to do something from the result on this feature.
I tried somwthing like this but it didnt work, is there a method to do it, so without writing the result to the vector layor just only return them with each iteration and I can do whatever I want with them?
My try:
from qgis.analysis import QgsZonalStatistics
from qgis.core import QgsRasterLayer, QgsVectorLayer
v_layer = QgsVectorLayer("gadm40_DEU_4.shp", "gadm", "ogr")
r_layer = QgsRasterLayer("Deutschland.vrt", "dem")
for i, feature in enumerate(v_layer.getFeatures()):
feature_geometry = feature.geometry()
#this approach doesnt work
zone_stat = QgsZonalStatistics (feature_geometry, r_layer,
attributePrefix = 'dem_',
rasterBand = 1,
stats = QgsZonalStatistics.Statistics(
QgsZonalStatistics.Count|
QgsZonalStatistics.Max|
QgsZonalStatistics.Mean|
QgsZonalStatistics.Median|
QgsZonalStatistics.Min|
QgsZonalStatistics.StDev
)
)
zone_stat.calculateStatistics(None)
feature_name = feature['NAME_4']
print(feature_name)
break #breaking for test purposes