5

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/Area_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/user/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.

2
  • 2
    Try the rescaleImage function in the RStoolbox package. Commented Jan 23, 2021 at 21:57
  • Thank you a lot @JeffreyEvans. It works perfectly using rescaleImage function
    – sermomon
    Commented Jan 23, 2021 at 22:25

1 Answer 1

7

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)
1
  • 1
    The RStoolbox is no longer available on CRAN. The code originally presented works just fine. The issue is that there are NA's in the data so min and max need a na.rm=TRUE argument so that results are not also NA as you were getting in the resulting raster. Now, of course the call would be terra::app() replacing raster::calc Commented Nov 16, 2023 at 3:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.