8

I have a large number of GeoTIFFs for which I would like to add and store symbology as Color table. What is the easiest way for doing that? I would like to use Python, maybe with GDAL.

2
  • I would need a color table, I am going to edit my question.
    – defelix
    Jun 13, 2019 at 10:37
  • 1
    Look at band.setColorTable
    – user2856
    Jun 13, 2019 at 11:12

1 Answer 1

13

Assuming your rasters are integer-type, you can create a ColorTable, specify the color for each value using the SetColorEntry() method and then apply the ColorTable to the raster using the SetRasterColorTable() method to the individual band. The SetColorEntry(pixel_val, (r, g, b)) method takes two arguments, where the first one is the pixel value and the second one is an RGB tuple.

The following snippet* shows how to create a ColorTable with 5 different colors (for 5 different values):

import gdal

# specify GeoTIFF file name, open it using GDAL and get the first band
fn = 'my_raster.tif'
ds = gdal.Open(fn, 1)
band = ds.GetRasterBand(1)

# create color table
colors = gdal.ColorTable()

# set color for each value
colors.SetColorEntry(1, (112, 153, 89))
colors.SetColorEntry(2, (242, 238, 162))
colors.SetColorEntry(3, (242, 206, 133))
colors.SetColorEntry(4, (194, 140, 124))
colors.SetColorEntry(5, (214, 193, 156))

# set color table and color interpretation
band.SetRasterColorTable(colors)
band.SetRasterColorInterpretation(gdal.GCI_PaletteIndex)

# close and save file
del band, ds

*Snippet slightly adapted from Chris Garrard's Geoprocessing with Python.

You want to create a ColorTable for a bunch of different rasters. To accomplish this you can store all your files in a folder and loop through each one of them. One possible approach to this would be:

import glob
import os

import gdal

# change working directory
os.chdir(r'path\to\your\rasters')

# get all the raster's file names and ignore other files
rasters = glob.glob('*.tif')

# iterate through each file name
for fn in raster:
   # do the processing

Another option is use to the gdaldem command line utility which, amongst many other things, lets you color an image. For more info about how to use this command line utility refer to the documentation or one of the following two answers:

1
  • 2
    When not having discrete colours, but having a colour scale, one can use: colors.CreateColorRamp(1, (112, 153, 89), 2, (242, 238, 162)) colors.CreateColorRamp(2, (242, 238, 162), 3, (242, 206, 133)) etc. instead of setting a color to every exact value.
    – Gert
    Oct 1, 2019 at 10:27

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