Search code examples
rgdalgeotiffterra

How do I ignore/force scale and offset when reading a COG with R terra


I am loading a large number of HLS.S30 and HLS.L30 COGs from LPCLOUD as SpatRasters using the terra package. I noticed that the pixel values in some of them ended up being integers (between 0 and 1000), and others floats (between 0 and 1). Inspecting the files with terra::describe showed that some had a " Offset: 0, Scale:0.0001" field, and others didn't, which is what I assume creates this inconsistency.

Is there a way to ignore these scale/offset, or force a scale=1, offset=0 when reading date with terra::rast, perhaps in the GDAL options?

Reproducible example (requires NASA Earthdata login):

library(terra)

setGDALconfig("GDAL_HTTP_UNSAFESSL", value = "YES")
setGDALconfig("GDAL_HTTP_COOKIEFILE", value = ".rcookies")
setGDALconfig("GDAL_HTTP_COOKIEJAR", value = ".rcookies")
setGDALconfig("GDAL_DISABLE_READDIR_ON_OPEN", value = "EMPTY_DIR")
setGDALconfig("CPL_VSIL_CURL_ALLOWED_EXTENSIONS", value = "TIF")

url1 <- "https://data.lpdaac.earthdatacloud.nasa.gov/lp-prod-protected/HLSS30.020/HLS.S30.T32ULC.2022237T103641.v2.0/HLS.S30.T32ULC.2022237T103641.v2.0.B08.tif"
url2 <- "https://data.lpdaac.earthdatacloud.nasa.gov/lp-prod-protected/HLSS30.020/HLS.S30.T31UGT.2022237T103641.v2.0/HLS.S30.T31UGT.2022237T103641.v2.0.B08.tif"

r1 <- rast(url1, vsi=TRUE)
r2 <- rast(url2, vsi=TRUE)
r1[1]
r2[2]
describe(url1)
describe(url2)


Solution

  • You should be able to set or remove the scale and offset with terra::scoff. For example, you can do

    scoff(r1) <- NULL
    scoff(r2) <- NULL
    

    Or the equivalent

    scoff(r1) <- cbind(1, 0)
    scoff(r2) <- cbind(1, 0)