Thursday, 11 February 2016

qgis - Getting layer extent in PyQGIS?


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 ?



Answer



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)

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...