'Downscaling sentinel-2 bands to 10m using R language
I'm trying to calculate NDRE using sentinel-2 bands in R language.
The formula for NDRE = (nir-re)/(nir+re)
nir- Near InfraRed (Band8)
re - RedEdge (Band5)
My Code:
library(raster)
library(RStoolbox)
re_path <- "D:/R/T43PHS_20190223T050811_B05.jp2"
nir_band <- "D:/R/T43PHS_20190223T050811_B08.jp2"
re <- raster(re_path)
nir <- raster(nir_band)
plot((nir-re)/(nir+re), main="NDRE")
writeRaster(x = ((nir-re)/(nir+re)),
filename="D:/R/T43PHS_20190223T050811.tif",
format = "GTiff", # save as a CDF
datatype='FLT4S'
)
But there seems to be an error due to difference in Bands5 and Band8 resolution.
Error in compareRaster(e1, e2, extent = FALSE, rowcol = FALSE, crs = TRUE, : different resolution
You can download Band5 and Band8 Here
I want to convert or downscale the 20m band into 10m band using R language and then calculate the indices, I tried using resample()
in R I got the output "tiff" file but there is so much loss of information.
Thank you in advance
Solution 1:[1]
You need to tranlate jp2 into the correct format.
Band Resolutions:
- B2:B4,B8 = 10 m
- B5:B7 = 20 m
Adapted the "jp2_to_GTiff" function from here, with revision:
jp2_to_GTiff <- function(jp2_path) {
sen2_GDAL <- raster(readGDAL(jp2_path))
names(sen2_GDAL) <- as.character(regmatches(jp2_path,gregexpr("B0\\d", jp2_path)))
return(sen2_GDAL)
}
## Your files:
re_path <- "D:/R/T43PHS_20190223T050811_B05.jp2"
nir_band <- "D:/R/T43PHS_20190223T050811_B08.jp2"
## Call the function
re <- jp2_to_GTiff(re_path)
nir <- jp2_to_GTiff(nir_band)
## Resample from raster package, then write:
re_10mr <- resample(re, nir, method='bilinear')
writeRaster(x = ((nir-re_10mr)/(nir+re_10mr)),
filename="D:/R/T43PHS_20190223T050811.tif",
format = "GTiff", # save as a CDF
datatype='FLT4S')
Note that the function uses a default GDAL conversion. The command line utility can be used as described here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |