Friday, 18 January 2019

Speeding up band math in R 'raster' package


I have some GeoTiff rasters with over 100 bands in total, but they are not huge: resolution is about 1200x600 and total size is less than 7 mb. I'm trying to do a simple NDVI calculation:


raster <- stack('path_to_raster_1', 'path_to_raster_2')
red <- 60 # red band number
NIR <- 75 # NIR band number
f_NDVI <- function(x){
(x[NIR]-x[red])/(x[NIR]+x[red])

}
NDVI <- calc(raster, f_NDVI)

The calculation runs extremely slow and takes about 10 minuets.


Is there a way to optimise it and why is the calculation so slow in my case?



Answer



I expect it will be much quicker this way (using a vectorized approach in the NDVI function)


f_NDVI <- function(x) {
(x[,1]-x[,2])/(x[,1]+x[,2])
}


# subset the two layers you need
s <- raster[[c(60, 75)]]

NDVI <- calc(s, f_NDVI)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...