From 68f6cd5dac271162d20eb82d1b06101abb88bac6 Mon Sep 17 00:00:00 2001 From: Dongdong Kong Date: Mon, 12 Aug 2024 17:04:54 +0800 Subject: [PATCH] add `rast2colormap` --- DESCRIPTION | 2 +- NAMESPACE | 2 ++ R/tools_rast.R | 17 +++++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 1fa4b0c..ef6a27a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -25,7 +25,7 @@ Suggests: rmarkdown, covr VignetteBuilder: knitr -RoxygenNote: 7.2.3 +RoxygenNote: 7.3.2 Roxygen: list(markdown = TRUE) Encoding: UTF-8 Depends: diff --git a/NAMESPACE b/NAMESPACE index fbf8cfb..b45e242 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -25,6 +25,7 @@ export(overlap_fraction) export(plot) export(rast) export(rast2SpatialGrid) +export(rast2colormap) export(rast2poly) export(rast_array) export(rast_cellId) @@ -43,6 +44,7 @@ export(st_range) export(st_read) export(st_rect) export(st_write) +export(value2colormap) export(write_shp) import(sf) importFrom(data.table,as.data.table) diff --git a/R/tools_rast.R b/R/tools_rast.R index 009c1e1..c74a102 100644 --- a/R/tools_rast.R +++ b/R/tools_rast.R @@ -73,3 +73,20 @@ rast_dim <- function(f) { listk(lon, lat) } + +#' @export +value2colormap <- function(x, brks, cols) { + col2dt <- function(cols) col2rgb(cols) %>% t() %>% as.data.table() + colormap = col2dt(cols) + ind = findInterval(x, brks) # %>% summary() + colormap[ind, ] |> as.matrix() +} + +#' @export +rast2colormap <- function(r, brks, cols, fout = "out.tif") { + x = values(r) + r2 = c(r, r, r) + val = val_colormap(x, brks, colors) + values(r2) = val + writeRaster(r2, fout) +}