TransWikia.com

Rescale NDVI (-1:1) to 0-255 using R

Geographic Information Systems Asked by Sergio Morell on January 31, 2021

I am trying to rescale my NDVI band (-1:1) to 0:255. I am trying to follow the approach in this post: Rescale raster in R , but I am getting NA values.

# my ndvi

ndvi

class      : RasterLayer 
band       : 5  (of  5  bands)
dimensions : 10120, 15200, 153824000  (nrow, ncol, ncell)
resolution : 0.25, 0.25  (x, y)
extent     : 747400, 751200, 4309040, 4311570  (xmin, xmax, ymin, ymax)
crs        : +proj=utm +zone=30 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs 
source     : D:/a4_v21/airborne_imagery/Oliva_2019/GeoTIFF_025/0796_2-5_2019_NDVI.tif 
names      : X0796_2.5_2019_NDVI.5 
values     : -1, 0.8059701  (min, max)

I define the rescale function and I try to rescale the raster:

rescale <- function(x, x.min = NULL, x.max = NULL, new.min = 0, new.max = 1) {
  if(is.null(x.min)) x.min = min(x)
  if(is.null(x.max)) x.max = max(x)
  new.min + (x - x.min) * ((new.max - new.min) / (x.max - x.min))
}

ndvi <- rescale(ndvi, x.min=-1, x.max=1, new.min=0, new.max=255)

I get the following results:

class      : RasterLayer 
dimensions : 10120, 15200, 153824000  (nrow, ncol, ncell)
resolution : 0.25, 0.25  (x, y)
extent     : 747400, 751200, 4309040, 4311570  (xmin, xmax, ymin, ymax)
crs        : +proj=utm +zone=30 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs 
source     : C:/Users/sergi/AppData/Local/Temp/Rtmpiu6LVs/raster/r_tmp_2021-01-23_222619_14736_96336.grd 
names      : X0796_2.5_2019_NDVI.5 
values     : NA, NA  (min, max)

How can I fix this error? I can’t understand where the problem is.

One Answer

SOLVED using rescaleImage() function in RStoolbox:

library(RStoolbox)

ndvi <- rescaleImage(x= ndvi, xmin = -1, xmax = 1, ymin=0, ymax=255)

Now I get the expected results:

ndvi

class      : RasterLayer 
dimensions : 10120, 15200, 153824000  (nrow, ncol, ncell)
resolution : 0.25, 0.25  (x, y)
extent     : 747400, 751200, 4309040, 4311570  (xmin, xmax, ymin, ymax)
crs        : +proj=utm +zone=30 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs 
source     : memory
names      : layer 
values     : 0, 230.2612  (min, max)

Answered by Sergio Morell on January 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP