NDVI calculation from Landsat 8 images with R and Terra package - Tutorial
/On the exploration for advanced tools for spatial analysis we took a chance on making raster algebra with R and the Terra package tutorial. This is an applied example of NDVI calculation from the red and near infrared bands from a Landsat 8 image. The script covers all steps from band load, array algebra and export as geospatial raster.
For this tutorial you need R and the spatial library Terra installed under a Conda environment. Please install the environment following this tutorial: hatarilabs.com/ih-en/how-to-install-the-r-spatial-library-terra-on-a-conda-enviroment-tutorial
Tutorial
Code
library(terra)
library(repr)
redFile <- '../Landsat8/LC08_L1TP_042035_20180603_20180615_01_T1_B4_clip.tif'
nirFile <- '../Landsat8/LC08_L1TP_042035_20180603_20180615_01_T1_B5_clip.tif'
redBand <- rast(redFile)
nirBand <- rast(nirFile)
red <- redBand[[1]]
nir <- nirBand[[1]]
ndviCal <- function(red, nir) {
ndviArray <- (nir - red)/(nir + red)
return(ndviArray)
}
iniTime <- Sys.time()
#ndviBand <- ndviCal(redBand,nirBand)
ndviBand <- ndviCal(red,nir)
endTime <- Sys.time()
print(endTime - iniTime)
Time difference of 0.319994 secs
options(repr.plot.width=20, repr.plot.height=12)
plot(ndviBand, main="Landsat-NDVI")
writeRaster(ndviBand, '../Output/NDVIByR.tif', overwrite=TRUE)
Input data
You can download the input data from this link.