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.
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]) print(mean)
import numpy as np import rasterio with rasterio.open(path) as f: array = f.read(1, masked=True) mean = np.ma.mean(array) print(mean)