Skip to content

Instantly share code, notes, and snippets.

@phargogh
Created December 17, 2019 19:55
Show Gist options
  • Save phargogh/21ccefc8b065846d53211c332ce4229f to your computer and use it in GitHub Desktop.
Save phargogh/21ccefc8b065846d53211c332ce4229f to your computer and use it in GitHub Desktop.
A function to get pixel values from a GDAL landcover raster
import collections
from osgeo import gdal
RasterStats = collections.namedtuple('RasterStats', ['min', 'max'])
def get_raster_values_from_attr_table(filepath, band_index):
gdal_dataset = gdal.OpenEx(filepath, gdal.OF_RASTER)
band = gdal_dataset.GetRasterBand(1)
attr_table = band.GetDefaultRAT()
if attr_table:
value_column_index = 0
for col_index in range(attr_table.GetColumnCount()):
if attr_table.GetNameOfCol(col_index).lower() == 'value':
value_column_index = col_index
break
raster_values = set()
for row_index in attr_table.GetRowCount():
raster_values.add(attr_table.GetValueAsInt(
row_index, value_column_index))
return raster_values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment