Thursday, 5 March 2015

Quantile in QGIS python Plugin


QGIS is very powerful when it comes to styling Vector Data. When it comes to Raster data, ArcGIS still has some advantages including Styling based on Quantiles. See my earlier post: For this I want to create a plugin. I got stuck when I want to determine quantiles for my raster (.tif) in a QGIS python Plugin based on this tutorial.


I got my raster stored as variable "layer". Now I want to determine quantiles. For this I could use a grass command called quantile. (r.quantile) however I don't know how to call this command in my plugin and how to store the output.



Bonus: Next I want to set my raster classes equal to the percentile score or store the output as a style for QGIS (.qml)



Answer



1) In GRASS GIS, if you look the documentation of r.quantile the process is


The raster


enter image description here


In the GRASS shell


GRASS 7.0.3 (Geol):~ >  r.quantile -r my_raster quantiles=5
Computing histogram
100%
Computing bins

Binning data
100%
Sorting bins
100%
Computing quantiles
157.930000:181.119995:1
181.119995:205.669998:2
205.669998:223.830002:3
223.830002:269.630000:4


Now, You can choose:


a) to use the quantiles as a new "rule" colour table for the original layer with r.colors
b) to create a new layer with the quantile classification:


r.quantile my_raster -r quantiles=5  --quiet | r.recode my_raster  out=elev_quant5 rules=-

enter image description here


Now with PyQGIS, using the processing module (you cannot apply a), no r.colors )


 import processing
layer = processing.getObject("my_raster")
processing.runalg("grass7:r.quantile",layer,5,True,"testo.txt")

# and
processing.runalg("grass7:r.recode",layer,"testo.txt",False,35.388374,"result.tif")

Result


enter image description here


2) But more simply, you can use pure Python with osgeo (GDAL) or rasterio (read the raster) and Numpy or scikit-image (percentiles) to do that


No comments:

Post a Comment