将Lab颜色值转换为RGB和HEX在R中

3

使用R将RGB值转换为HEX值很容易:

    x <- c("165 239 210", "111 45 93")
    sapply(strsplit(x, " "), function(x)
    rgb(x[1], x[2], x[3], maxColorValue=255))
    #[1] "#A5EFD2" "#6F2D5D"

如何将CIELab值转换为RGB和HEX?

x <- c("20 0 0", "50 0 0")
[...code...]
#[1] "#303030" "#777777"

请查看?convertColor - Andrew Gustar
2个回答

5

这里有一种使用 library(colorspace) 的方法

library(colorspace)

z <- c("20 0 0", "50 0 0")
b <- do.call(rbind, lapply(strsplit(z, split = " "), as.numeric))
b <- LAB(b)
as(b, "RGB")
#output:
              R          G          B
[1,] 0.02989077 0.02989025 0.02989294
[2,] 0.18418803 0.18418480 0.18420138

它不能直接转换为十六进制,但可以转换为:RGB、XYZ、HSV、HLS、LAB、极坐标LAB、LUV、极坐标LUV。


0

使用 tidyverse 风格和 convertColor 函数。

convert_lab2rgb <- function(x){
    x %>% 
    unlist() %>% 
    convertColor(from='Lab', to='sRGB') %>%
    as.vector()
}


convert_rgb2hex <- function(x){
    x %>% 
    unlist() %>% 
    `*`(255) %>% 
    round() %>% 
    as.hexmode() %>% 
    paste(collapse='') %>% 
    paste0('#', ., collapse='')    
}


c("20 0 0", "50 0 0") %>% 
    map(~ str_split(., pattern=' ')[[1]]) %>% 
    map(as.numeric) %>%
    map(convert_lab2rgb) %>% 
    map(convert_rgb2hex)


## #303030'
## #777777'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接