2

for a qgis 1.8 python plugin I want to query the mean of all pixel values of a raster layer within a defined buffer around the current mouse position, not for an existing point layer.

For the buffer sth like this should work:

feat.geometry().asPoint() 
(3.5176e+06,5.4062e+06)

buff_geom = feat.geometry().buffer(1000, 5)

buff_geom.asPolygon()
[[(3.5186e+06,5.4062e+06), (3.51855e+06,5.4059e+06), (3.51841e+06,5.40562e+06),     (3.51819e+06,5.4054e+06), (3.51791e+06,5.40525e+06), (3.5176e+06,5.4052e+06), (3.51729e+06,5.40525e+06), (3.51701e+06,5.4054e+06),...]]

but now I try to find a solution to query all raster pixels within the buffer zone and calculate the mean, but I don't know how and if this is possible in QGIS 1.8 at all.
All I found is QgsZonalStatistics, but that doesn't work for my task.

Does anybody have a solution for this or a better idea, how to solve this?

Thanks.

1 Answer 1

4

finally with some help from Anita I found following solution working for QGIS 1.8. Maybe useful for others:

import qgis.analysis
from PyQt4.QtGui import *

vpoly = QgsVectorLayer("Polygon", "pointbuffer", "memory")
feature = QgsFeature()
feature.setGeometry(QgsGeometry.fromPoint(QgsPoint(3517601,5406205)).buffer(10000,5))
provider = vpoly.dataProvider()
vpoly.startEditing()
provider.addFeatures( [feature] ) 
vpoly.commitChanges()
stats=qgis.analysis.QgsZonalStatistics(vpoly,"/path/to/corine2006_z0_test_gk3.tif")
stats.calculateStatistics(None)
allAttrs = provider.attributeIndexes()
provider.select(allAttrs)
provider.nextFeature(feature)
attrs = feature.attributeMap()
for (k,attr) in attrs.iteritems():
  if k==2:
    MessageBox.information(qgis.utils.iface.mainWindow(),'Info',attr.toString())

This is a solution for QGIS 2.0:

    vpoly = QgsVectorLayer("Polygon", "pointbuffer", "memory")
    feature = QgsFeature()
    feature.setGeometry(QgsGeometry.fromPoint(QgsPoint(3517601,5406205)).buffer(10000,5))
    provider = vpoly.dataProvider()
    provider.addFeatures( [feature] )
    vpoly.commitChanges()
    stats = qgis.analysis.QgsZonalStatistics(vpoly,"/path/to/corine2006_z0_test_gk3.tif")
    stats.calculateStatistics(None)
    allAttrs = provider.attributeIndexes()       
    for feature in vpoly.getFeatures():
        mean_value = feature.attributes()[2]
        MessageBox.information(qgis.utils.iface.mainWindow(),'Info',str(mean_value))
2
  • Just a little headsup: You don't need to start an edit session, if you are writing directly to the provider (and not via the QgsVectorLayer.addFeatures() method) Commented Jul 17, 2013 at 7:58
  • I see, I removed vpoly.startEditing() and it still works. Thanks.
    – dassau
    Commented Jul 17, 2013 at 9:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.