[GIS] Converting raster stack to RGB GeoTIFF for use as a background image in maps using R

exportgeotiff-tiffr

I've been trying to use R to download google maps images as rasters, then convert them into GeoTIFF files which can be imported as a geo-referenced background layer in GIS programs.

I've been searching for hours now, but I can't seem to figure out how to save a colored geotiff file. I can make Geotiff files which contain only the raster data with no saved color maps, but I've been unable to figure out how to add color maps to the GeoTIFFs.

Here's my code so far:

## Install and load required packages
install.packages('openmap')
require(ggmap)
require(raster)
require(dismo)

## Get region of interest
region <- c(11.03,12,-1.1,-0.04)
e = extent(region)

## Download google maps image of region
map <- gmap(e,rgb = T)

## Plot map
plotRGB(map)

## Write a geotiff raster (does not contain RGB info!)
writeRaster(x = map,
            filename = 'GoogleMap.tif',
            format = 'GTiff',
            overwrite = T
            )

The resulting raster can by imported by other programs as a raster layer, but the colormap is undefined.

And ideas on how to add RGB info to the resulting geoTIFF?

Heres a link to an example GeoTIFF which works in the GIS software I'm using

Perhaps I am misunderstanding what a geotiff is. I assumed a geotiff was just a TIFF file with georeferencing metadata… but perhaps is there a difference between geotiffs and just normal tiff with georeferenced metadata?

I'm thinking this because the dismo::gmap function outputs georeferenced gif files which do exactly what I need, as they can be read by normal image viewers and they also can be plotted correctly in GIS software, unlike the geotiffs which I made, which cannot be read by image viewers.

Best Answer

I wasn't able either to export with raster, but an alternative would be to use writeJPEG() from package jpeg. Note that:

  • writeJPEG() expects an array as input: using as.array(r) does the trick
  • writeJPEG() expects RGB values between 0-1. In my case, reading with raster, they were 0-255, so just rescale!

Your example didn't work for me, but here is one, using the R logo, importing it with raster() adding some (truly beautiful) art, and exporting to jpg:

library(raster)
library(jpeg)

r <- stack(system.file("img","Rlogo.jpg",package="jpeg"))

r$Rlogo.1 <- getValues(r$Rlogo.1)/2

plotRGB(r)

writeJPEG(as.array(r)/255, "out.jpeg")