3

I am using the Zonal Statistics tool of QGIS 2.18.9 to calculate the mean value of a raster within a grid of rectangles. When I do it "manually", everything works. But as I have to do this for a lot of grids and raster files (more than 100), I want to automate this. I tried by different ways :

1)Using Graphical Modeler It failed because you can't specify what you want to get (min, max,mean ...) so it creates all the column with only zeros inside.

2)I tried with a python script. So I wrote a script and I run it in the Python console of QGIS. I tried to different ways :

2) a) I read this article : http://spatialgalaxy.net/2012/01/27/qgis-running-scripts-in-the-python-console/ And I succeeded in running his script. I modified it to get what I want :With Class But python returns me : "NameError: global name 'QgsVectorLayer' is not defined"

So as the man in the article tells about a "simple" way. I tried it too.

2)b) Still using python, this time I am not creating class. I just write it directly. As for 2)a) I tried a simple code that I found there : How to use QGIS Zonal Stats Plugin from Python Console? It works. So I changed it to obtain what I want :With the "simple" way it gave me nothing, but when I write "zoneStat.calculateStatistics(None) " in the Python Console it returns 3 and change nothing in my Vector Layer. Same thing when I want to run it line by line without python script : when I write in the command it returns me 3 also.

So, to put it in a nutshell : I try to run a python script to automate the QGSZonalStatistics method. With classes it does not recognize QgsVectorLayer (so perhaps I forgot to import something) With a simple dirty script or only by writing in the command, it returns 3 without further information. I read on a forum that it should return 0 if it created the columns.

  • vector_layer_name is in fact a raster, I made a mistake. Its name would rather be raster_layer_name – J.Delannoy Jun 21 '17 at 12:35
  • Please always present code and errors as text rather than pictures so that they are available to future searches. – PolyGeo Jun 21 '17 at 13:01
  • Ok, I will do it now ;) – J.Delannoy Jun 21 '17 at 13:04
2

Soo I just found the solution for the 2)a) if someone once needs it, I added those lines :

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
from qgis.utils import iface

Then it ran but nothing changed. After re-opening Python the column was created !!!

And one last thing : Be careful to Reload AND import again your script for each change (pretty heavy)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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