Skip to contents

Write a reflectance raster to a GeoTIFF, optionally scaling float values to an integer datatype. The scale factor is embedded in GeoTIFF band metadata so terra::rast() reads back float values transparently — no manual rescaling required.

Usage

hsi_write_scaled(
  x,
  filename,
  scale_factor = 10000L,
  overwrite = FALSE,
  datatype = "INT2U",
  ...
)

Arguments

x

A SpatRaster with hyperspectral data.

filename

Character. Output file path. Always writes to disk.

scale_factor

Numeric. Scale factor applied before writing. Default 10000 gives 4 decimal places of precision. Ignored for float datatypes.

overwrite

Logical. Overwrite existing file. Default FALSE.

datatype

Character. Output datatype. One of "INT1U", "INT2U", "INT2S", "INT4U", "INT4S", "FLT4S", "FLT8S". Default "INT2U". Integer types apply scale_factor and are range-checked before writing. Float types write values as-is with no scaling or range validation. Use "FLT4S" for sensors with low SNR such as SWIR.

...

Additional arguments passed to terra::writeRaster().

Value

A SpatRaster with values written to filename.

Details

For integer datatypes, values are multiplied by scale_factor before writing and the reciprocal is stored as GDAL scale metadata. An error is raised if any value exceeds the maximum storable value for the chosen datatype at the given scale factor. Integer storage reduces file size by approximately 50% relative to float32 before compression.

For float datatypes ("FLT4S", "FLT8S"), scale_factor has no effect and no range validation is performed.

Choose the datatype based on sensor characteristics. VNIR sensors with high SNR are well suited to "INT2U" at the default scale factor. Sensors with lower SNR, such as SWIR, should use "FLT4S" to avoid quantization degrading meaningful signal.

Examples

if (FALSE) { # \dontrun{
x <- terra::rast("REFLECTANCE.tif")

# Default: scaled uint16 for VNIR
x_scaled <- hsi_write_scaled(
  x,
  filename = "REFLECTANCE_scaled.tif",
  gdal = c("COMPRESS=DEFLATE", "PREDICTOR=2")
)

# Float32 for SWIR
x_scaled <- hsi_write_scaled(
  x,
  filename = "REFLECTANCE_swir.tif",
  datatype = "FLT4S"
)

terra::rast("REFLECTANCE_scaled.tif")
} # }