8

I'm trying to write a processing script using grass r.neighbors algorithm for rasters. When you use the Gui for this algorithm, you can leave the GRASS layer extent field blanc to use the minimal extent. On the contrary, when used in the python console, I can't find how to input this kind of "default" value.enter image description here

I saw on https://docs.qgis.org/2.2/en/docs/user_manual/processing/console.html that it seems to be mandatory to input the four coordinates for an extent parameter. I tried using iface.mapCanvas().extent() but the object returned is not accepted as a parameter and I can't find how to get its coordinates..

Is there a way to get the xmin, ymin, xmax, ymax of the layer in PyQGIS to input them in the algorithm? Am I doing it totally wrong ?

  • Thanks for your answers, I found this solution by my side too... In fact it was also answered in a similar way in gis.stackexchange.com/questions/213428/… but parentheses after extent are missing so it was not working... – Clement Jun 29 '17 at 8:47
11

The answer is almost completely contained in a post I recently wrote.

The extent is returned as a QgsRectangle() object with the following code:

layer = iface.activeLayer() # load the layer as you want
ext = layer.extent()

For getting the coordinates of the vertices for the current layer, you may run this code:

xmin = ext.xMinimum()
xmax = ext.xMaximum()
ymin = ext.yMinimum()
ymax = ext.yMaximum()
coords = "%f,%f,%f,%f" %(xmin, xmax, ymin, ymax) # this is a string that stores the coordinates

Finally, you may run the following code for using the r.neighbors module from the Python Console:

processing.runalg("grass7:r.neighbors",layer,0,3,False,False,"",coords,0,None)
5

you were on the right track you just need to go a step further. See the QGIS documentation for QgsRectangle

Basically, you do:

  • get the current Layer

    layer = iface.activeLayer()
    
  • get the extent which is a QgsRectangle object

    ex = layer.extent()
    
  • and there extract the Values with:

    xmax = ex.xMaximum()
    ymax = ex.yMaximum()
    xmin = ex.xMinimum()
    ymin = ex.yMinimum()
    

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.