I would like to know if the STATISTICS_VALID_PERCENT (percentage of valid (not nodata) pixels) information is accessible through the GDAL Python API?

It seems to be missing from the GetStatistics Function.

As a work around, I have been scraping this information from the PAMDataset (XML file) generated through the GetStatistics(False, True) call.

Is there a better way?


"Better" is subjective, so I won't claim that this is. But I much prefer using rasterio to "raw" GDAL or its python bindings. So if I wanted to know the fraction of cells with valid values, I would do the following:

Rasterio Approach

import rasterio
with rasterio.open('path/to/my/image.tif', 'r') as src:
    meta = src.meta.copy()
    data = src.read(1)

pct_valid = 100 * (data != meta['nodata']).sum() / (meta['width'] * meta['height'])

"Raw" GDAL

Alternatively, here's how you'd do it with GDAL's python bindings directly:

import gdal
gtif = gdal.Open('path/to/my/image.tif')
data = gtif.GetRasterBand(1).ReadAsArray()
nd_val = band.GetNoDataValue()

pct_valid = 100 * (data != nd_val).sum() / (band.XSize * band.YSize)
gtif = None

Also consider

The raster_stats package may be even more concise, but I think it would required to you generate a vector layer encompassing the whole raster.


  1. rasterio: https://rasterio.readthedocs.io/en/stable/
  2. raster_stats: https://pythonhosted.org/rasterstats/index.html
  • Thanks for the response. I agree that rasterio is generally easier to use and provides several advantages over the straight GDAL API. I would however prefer to stay within the confines of GDAL for my particular use case. – Brent Edwards Mar 14 at 13:20
  • hey @BrentEdwards added a GDAL-based approach – Paul H Mar 14 at 16:13
  • Thanks Paul H! This should work in cases where the raster is small enough to be read directly into an array and thus avoiding the pain of windowing in GDAL. – Brent Edwards Mar 14 at 16:32

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.