Skip to content

gdal color tables

1 message · Barry Rowlingson

#
Here's a solution:

makePalette <- function(colourvector){
  cmat = cbind(t(col2rgb(colourvector)),255)
  res = apply(cmat,1,function(x){sprintf('<Entry c1="%s" c2="%s"
c3="%s" c4="%s"/>',x[1],x[2],x[3],x[4])})
  res = paste(res,collapse="\n")
  res
}


Then:

 write a raster tiff

 writeRaster(iom,"test.tif",overwrite=TRUE,datatype="INT1U")


Then use makePalette to create the colortable lines:

cat(makePalette(iom at legend@colortable)) # replace
iom at legend@colortable with your colour table vector

That spits out a bunch of <Entry> lines. Stick them in your .vrt file thus:

<VRTDataset rasterXSize="413" rasterYSize="397">
  <VRTRasterBand dataType="Byte" band="1">
    <ColorInterp>Palette</ColorInterp>
<SimpleSource>
<SourceFilename relativeToVRT="1">test.tif</SourceFilename>
</SimpleSource>
    <ColorTable>
<Entry c1="0" c2="0" c3="0" c4="255"/>
<Entry c1="230" c2="0" c3="77" c4="255"/>
<Entry c1="255" c2="0" c3="0" c4="255"/>
<Entry c1="204" c2="77" c3="242" c4="255"/>
<Entry c1="204" c2="0" c3="0" c4="255"/>
[etc]
   </ColorTable>
  </VRTRasterBand>
</VRTDataset>

Note you have to fill in the rasterXSize and rasterYSize, and the
source filename. Also you'll need to get the geotransform of the
original and stick that in otherwise your raster is geolocated at
(1:Nrows, 1:Ncolumns).

If I do all that, I get a raster created by R that I can read into
QGis and is coloured according to my colour scheme, as long as I open
*test.vrt* in QGis and *not* test.tif.

I'm sorry this isn't (yet) a one-shot solution, and its a bit of a
construction set. Like I said, two minute job, twenty minute job to do
properly... I've spent ten minutes on it :)

Barry




On Sun, Dec 23, 2012 at 9:25 PM, Rowlingson, Barry
<b.rowlingson at lancaster.ac.uk> wrote: