3

I have a single band image which I would like to copy to a 3 bands of a new image and set the ColorInterpretation to red, green and blue respectively. I have tried two approaches, one using the GTiff driver, explained below, and the other using the VRT driver.

My code is;

from osgeo import gdal
import os

IM = "path/to/image.tif" # single band image

### read image ###
ds = gdal.Open(IM)
X = ds.RasterXSize
Y = ds.RasterYSize
band = ds.GetRasterBand(1).ReadAsArray()

### write to 3 bands ###
driver = gdal.GetDriverByName("GTiff")
outPath = os.path.join(os.path.split(IM)[0], "test_image.tif")
outIM = driver.Create(outPath, X, Y, 3, gdal.GDT_Int16)
for i in range(1, 4):
    outIM.GetRasterBand(i).SetRasterColorInterpretation(2 + i)
    outIM.GetRasterBand(i).WriteArray(band)
    print outIM.GetRasterBand(i).GetRasterColorInterpretation()
outIM = None

The output is:

1
0
0

I have also tried using the SetColorInterpretation().

My question is, how do I set the ColorInterpretation metatag using the GTiff driver?

2 Answers 2

2

To set the band colour correctly you need to specify this in the driver.Create call using options:

outIM = driver.Create(outPath, X, Y, 3, gdal.GDT_Int16, options = [ 'PHOTOMETRIC=RGB' ])

This answer was provided by Evan Rouault on the gdal nabble. See full answer here http://osgeo-org.1560.x6.nabble.com/SetColorInterpretation-for-a-GeoTiff-using-GDAL-not-working-td5091839.html

1

To set the colour interpretation for each raster band, you should use the GDAL colour interpretation values:

  • gdal.GCI_RedBand = 3
  • gdal.GCI_GreenBand = 4
  • gdal.GCI_BlueBand = 5

For example, assuming your spectral bands are ordered as RGB:

from osgeo import gdal

im = gdal.Open('ImageName.tif', 1)  # open image in read-write mode
for i in range(3):
    band = im.GetRasterBand(i + 1)
    band.SetColorInterpretation(i + 3)
    del band
del im

Here are some other GCI values you might find useful (for example, when using a HSI colour profile):

  • gdal.GCI_AlphaBand = 6
  • gdal.GCI_HueBand = 7
  • gdal.GCI_SaturationBand = 8
  • gdal.GCI_LightnessBand = 9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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