Geo-reference an image in R

dataViz
Published

August 13, 2016

R is actually great for working with spatial data (for example, see here and here for fantastic graphs and maps made with R), however, you often need data that is actually spatial to get started! What do you do if you have an image, a map, let’s say, that is not geo-referenced in any way?

The regular answer to this problem is to use software such as QGIS to manually enter GPS coordinates, with the help of Google Maps or something similar. But R can be used for this too, and it’s quite easy to do.

First, we load some necessary packages. Here, I’m working with .tiff files that I will change into Geo-tiffs. For other formats, you will need some other packages (such as png, for example).

library(raster)
library(rgdal)

Next, we read in the non-spatial image using the raster command. By plotting this in RStudio, the image can be cropped in the preview window, if you want to crop it down the area of interest. This is also useful if the image came with extra, non-map parts (logos etc.).

Map <- raster("1.tiff")
Map
plot(Map)
map2 <- crop(Map, drawExtent(show = TRUE, col = "red"))
plot(map2)

Now we can enter in the maximal points of the image, xmin/xmax and ymin/ymax, respectively. These coordinates refer to an area of São Paulo, Brazil. The x-axis is longitude, the y-axis latitude. You can get the coordinates from www.gps-coordinates.net for the area you need. We also need to tell R what type of map projection we are going to write into the image. Here we’ll use "+proj=longlat +datum=WGS84".

xmin(map2) <- -46.67449772357941
xmax(map2) <- -46.524503231048584
ymin(map2) <- -23.638627166908787
ymax(map2) <- -23.517227011061372
crs(map2) <- "+proj=longlat +datum=WGS84"

This part is the main piece of work. But after it’s done, you’ve got yourself a geo-referenced image. Here, we’ll write it to the geo-tiff format I mentioned earlier.

writeRaster(map1, "Gmap1.tiff", "GTiff")

Simple! 😈