Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to get some advice on the most efficient way to return a list of unique values of a discrete-valued raster using Python and GDAL.

I had thought that the most obvious way would be to examine the raster's attribute table, but if I do band.GetDefaultRAT() on the band of a raster dataset that contains an attribute table (the table is visible in ArcCatalog, anyway), the result is always None:

>>> rat = band.GetDefaultRAT()
>>> rat == None

In that case, I end up having to scan through each cell of the raster and build a list of unique values manually. Is this the only way to do it?

Or is there a way to build an attribute table with Python and GDAL, then query it for a list of unique values?

share|improve this question
Which version of GDAL are you using btw? – R.K. Sep 13 '12 at 7:29
stupid question but what is RAT? – nickves Sep 13 '12 at 9:28
RAT stands for Raster Attribute Table. – Markus M. May 3 at 2:59
up vote 10 down vote accepted

If I understood correctly, you can use np.unique function from numpy lib:

from osgeo import gdal
import numpy as np

ds = gdal.Open("myimg.ext")
band =  ds.GetRasterBand(1)
array = np.array(band.ReadAsArray())
values = np.unique(array)

or you can one-shot it:

values = np.unique(np.array(ds.GetRasterBand(1).ReadAsArray()))
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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