2

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?

2
  • By using QgsRasterDataProvider objects to calculate statistic through QgsRasterBandStats objects.
    – xunilk
    Jul 26, 2017 at 23:22
  • The colors: RED on band 1, GREEN on band 2, BLUE on band 3, are correct?? I mean they represent the colors of each band for the specific .tiff? Because in literature I have read in papers, I think band 3 = RED and band 4 = NIR. Am I missing something here? Jun 14, 2021 at 17:51

1 Answer 1

6

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.

2
  • that is helpful, thanks! But still that is not quite the info I wanted. I want to get these values, if possible. (check the next answer)
    – Berna
    Jul 28, 2017 at 15:33
  • @Berna I found this works, but it might not match what you see in histogram until you load the actual min/max range of values, e.g. in the raster layer properties. It looks like QGIS histogram dialog shows the estimated stats of your raster until you do this.
    – Steven Kay
    Jul 31, 2017 at 18:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.