[GIS] SetColorInterpretation() for a GeoTiff using GDAL not working

colorgdalgeotiff-tiffosgeopython

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?

Best Answer

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