Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Desaturation RGB Image #1060

Closed
dominicroye opened this issue Mar 9, 2023 · 2 comments
Closed

Desaturation RGB Image #1060

dominicroye opened this issue Mar 9, 2023 · 2 comments

Comments

@dominicroye
Copy link

I just found the colorize function in the terra package, and I was trying to desaturate an RGB image.

Until now, I used to apply a custom function with app(). But it is even with parallel slow, so I wondered how to change the saturation with colorize.

saturation <- function(rgb, s = .5){
  
  hsl <- plotwidgets::rgb2hsl(as.matrix(rgb))
  hsl[2, ] <- s

  rgb_new <- as.vector(t(plotwidgets::hsl2rgb(hsl)))
  
  return(rgb_new)
  
}

I finally tried the following:

library(terra)

r <- rast(system.file("ex/logo.tif", package="terra"))   

rh <- colorize(r, to = "hsl")
rh[[2]] <- rh[[2]]*0.1
rh

colorize(rh, to = "rgb")
Error: [] input color scheme should be one of 'hsv', 'hsi' or 'hsl'

Unfortunately, when I convert the hsl back to RGB, I get an error about the color scheme. How should I proceed?

Thanks!!

@rhijmans
Copy link
Member

rhijmans commented Mar 9, 2023

It took a couple of small adjustments to make this work.

The app solution with plotwidgets::hsl2rgb

saturation <- function(rgb, s = .5){
  hsl <- plotwidgets::rgb2hsl(as.matrix(rgb))
  hsl[2, ] <- s
  as.vector(t(plotwidgets::hsl2rgb(hsl)))
}
library(terra)
r <- rast(system.file("ex/logo.tif", package="terra"))   
a <- app(r, saturation)

And now with colorize.

rh <- colorize(r, to = "hsl")
# you can now replace all values of a layer like this
rh[[2]] <- .5
# but you need to reset the colorspace
set.RGB(rh, 1:3, "hsl")

b <- colorize(rh, to = "rgb")

This does seem faster.

@vorpalvorpal
Copy link

The need to use set.RGB in between the two colorize steps is not documented in the help file for colorize which just says you can use "rgb" as the to argument for colorize. I was completely stuck trying to do the same thing until I found this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants