[GIS] Getting multiband raster’s min and max values with Python in QGIS

multi-bandpyqgisqgisrasterstatistics

Is there anyway to have access to minimum and maximum pixel values from multi-band raster using Python in QGIS? This is QGIS and I loaded 3 different bands as rasters.

Histogram Min and Max

If there's a way to have access to them. How to do it?

GetDefaultHistogram gives different values for minimum and maximum. See below:

Intel

Is there a way to get the scale numbers from the histogram? For all bands?

Best Answer

Next code works with multi band raster. It uses QgsRasterDataProvider objects to calculate statistic through QgsRasterBandStats objects.

layer = iface.activeLayer()

extent = layer.extent()

provider = layer.dataProvider()

for band in range(1, layer.bandCount() + 1):
    stats = provider.bandStatistics(band, QgsRasterBandStats.All, extent, 0)
    min = stats.minimumValue
    max = stats.maximumValue
    print 'min: {:.2f}, max: {:.2f}'.format(min, max)

After running the code with RGB raster of next image:

enter image description here

I got printed, at Python Console of QGIS, next values:

min: 62.00, max: 255.00
min: 89.00, max: 255.00
min: 90.00, max: 255.00

They are identical to reported in Metadata Layer Properties.