I have a bitmap that contains a polygon NDVI and nodata space. How do I get the average value of the polygon only, and not the entire raster.

enter image description here

  • 1
    @BERA Yes, I have QGIS, but I have to process a lot of rasters, and this is an intermediate step, so I would like to do without this system. – Константин Apr 7 at 17:00
  • What are you open to using? gdal command-line utilities, gdal c++ apis, gdal python bindings, python packages that use gdal? – mikewatt Apr 7 at 19:02
  • @mikewatt I use gdal command-line utilities and gdal python bindings – Константин Apr 7 at 21:02

Assuming the nodata value is defined, you could you could do something like this with the Python bindings. mask = array != nodata gives a boolean array which contains True for valid pixels and False for nodata pixels, and array[mask] uses numpy's boolean indexing to return only non-nodata values.

import gdal
import numpy as np

ds = gdal.Open(path)
band = ds.GetRasterBand(1)
nodata = band.GetNoDataValue()
assert nodata is not None
array = band.ReadAsArray()
mask = array != nodata
mean = np.mean(array[mask])

Although I would always recommend rasterio over the Python bindings. You could use boolean indexing as above, or read it as a masked array and use numpy's masked array routines:

import numpy as np
import rasterio

with rasterio.open(path) as f:
    array = f.read(1, masked=True)
    mean = np.ma.mean(array)

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.