1

I would like to write an array from a single band image to a 3 band vrt where each band has the ColorInterpretation() tag of red, green, blue respectively.

My code below;

from osgeo import gdal
import os

#IM = "/path/to/image.tif"
IM = im

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

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

The output is:

[[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 ..., 
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]
3
[[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 ..., 
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]
4
[[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 ..., 
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]
5

So setting the ColorInterpretation() (unlike when using GTiff, see here), but all values are zero. Why?!

#### UPDATE ####

I have been running this through ipython and just noticed this error on the command line:

Error 1: Writing through VRTSourcedRasterBand is not supported
1

You can't write data to a VRT. It's a "Virtual Raster", and is actually just an XML file. Try something like:

gdal_translate -of VRT -b1 -b1 -b1 in.tif out.vrt

Then open the out.vrt in python and set the colour interpretation.

You can write the vrt xml in python instead of using the commandline, but it's easier to use the subprocess module to run the gdal_translate command.

  • Thanks Luke, would I then again use gdal_translate to write out the .vrt as a .tif after setting the colour interpretation? – kungphil Oct 11 '13 at 10:11
  • I have tried the option as described above, it worked well until writing the vrt to tif (using gdal_merge.py). Is there an option to override default assignment of color interpretation? – kungphil Oct 13 '13 at 3:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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