4

I'm building a plugin from QGIS, and I need to extract the values from the quartiles from a band in a raster layer. Does anyone knows how it is done?

  • Welcome to gis.stackexchange! Please note that a good question on this site is expected to show some degree of research on your part, i.e. what you have tried and - if applicable - code so far. For more info, you can check our faq. – underdark Apr 26 '16 at 18:19
  • Don't forget to accept answers which solved your problem :-) – user35594 Aug 25 '17 at 19:51
4

You can use an adaptation of the next code (by using the path of your particular raster):

from osgeo import gdal
import numpy as np

raster = "/home/zeito/pyqgis_data/utah_demUTM2.tif"

dataset = gdal.Open(raster)
band = dataset.GetRasterBand(1)

print "rows = %d columns = %d" % (band.YSize, band.XSize)

BandType = gdal.GetDataTypeName(band.DataType)

print "Data type = ", BandType

data = band.ReadAsArray(0, 0, band.XSize, band.YSize)

p25 = np.percentile(data, 25) # return 25th percentile.
p50 = np.percentile(data, 50) # return 50th percentile.
p75 = np.percentile(data, 75) # return 75th percentile.

print "p25 = {} p50 = {} p75 = {} ".format (p25, p50, p75)

dataset = None

After running the code at the Python Console of QGIS the results were:

rows = 791 columns = 1680
Data type =  Int16
p25 = 1529.0 p50 = 1739.0 p75 = 2072.0 

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.