Search code examples
rcolorsrasterr-raster

Adjust the saturation and brightness of RGB raster colours


In my example I have a r raster:

library(raster)
r <- raster(ncol=10, nrow=10) 
set.seed(1)
r1 <- setValues(r, rpois(100, 150))
r2 <- setValues(r, rpois(100, 200))
r3 <- setValues(r, rpois(100, 150))
r <- stack(r1, r2, r3)
names(r)=c("R","G","B")

Now, I'd like to adjust the saturation and brightness of RGB colours in this r raster and save the changes on a new image in tif format. I try several packages, but anyone modifies directly raster or terra images without format modifications.

Please any help with it?


Solution

  • Note that you can set the RGB channels with "terra"

    library(terra)
    r <- rast(ncol=10, nrow=10) 
    set.seed(1)
    r1 <- setValues(r, rpois(100, 150))
    r2 <- setValues(r, rpois(100, 200))
    r3 <- setValues(r, rpois(100, 150))
    r <- c(r1, r2, r3)
    names(r)=c("R","G","B")
    
    RGB(r) <- 1:3
    plot(r)
    

    Change the saturation

    x <- colorize(r, to="hsv")
    x$saturation <- x$saturation / 2
    RGB(x, type="hsv") <- 1:3
    rr <- colorize(x, to="rgb")
    plot(rr)
    

    And with writeRaster, the RGB channels are preserved (with file formats that support that)

    s <- writeRaster(rr, "test.tif", overwrite=TRUE)
    s
    #class       : SpatRaster 
    #dimensions  : 10, 10, 3  (nrow, ncol, nlyr)
    #resolution  : 36, 18  (x, y)
    #extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
    #coord. ref. : lon/lat WGS 84 (EPSG:4326) 
    #source      : test.tif 
    #colors RGB  : 1, 2, 3 
    #names       : red, green,  blue 
    #min values  : 157,   172, 150.5 
    #max values  : 198,   232, 205.5