14

I am looking for a tool from the GDAL that is able to reclassify a raster containing multiple discrete values. So far, I have found Reclassify rasters using GDAL and Python; however it seems that only single values can be handled here.

Is there something like a native tool from the suite?

user2856
  • 65,736
  • 6
  • 115
  • 196
Arne
  • 815
  • 2
  • 8
  • 22

3 Answers3

17

gdal_calc can be used for a reclassification of many classes.

For example, you can change values below (and equal) 12 to 10, values of 20, 30, 40, 50 stays the same, and values between above 50 and 62 are changed to 60:

  python gdal_calc.py -A input.tif --outfile=output.file --calc="10*(A<=12)+20*(A==20)+30*(A==30)+40*(A==40)+50*(A==50)+60*((A>50)*(A<=62))" --NoDataValue=0
Jot eN
  • 972
  • 8
  • 21
  • Note that the GDAL documentation (http://www.gdal.org/gdal_calc.html) implies that gdal_calc.py will work with multiple rasters, since you can choose any capitalized letter of the alphabet. I was unable to get it to work with more than two inputs at a time. It accepted more inputs without producing an error, but my tests showed that only the first two were used. – David A May 14 '18 at 19:48
8

gdal_reclassify is an unofficial Python tool, based on Python GDAL bindings, able to reclassify according to several classes of values.

Requirements:

python
numpy
gdal binaries
python-gdal bindings

Example:

python gdal_reclassify.py source_dataset.tif destination_dataset.tif -c "<30, <50, <80, ==130, <210" -r "1, 2, 3, 4, 5" -d 0 -n true -p "COMPRESS=LZW"
Antonio Falciano
  • 14,333
  • 2
  • 36
  • 66
3

If you're working in a python script then use the .ReadAsArray method. You can then reclassify using numpy.

import numpy as np
sample = np.random.randint(low = 0, high = 9, size =(5,5))
print(sample)
sample[sample == 4] = 40
sample[sample <= 2] = -20
print(sample)
RoperMaps
  • 2,166
  • 11
  • 23
  • 2
    Downside of this is that the entire raster has to fit into memory. With gdal_calc.py reading the raster in smaller chunks is handled for you. – Iamlukesky Oct 11 '19 at 11:04