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.
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: