Convert hexadecimal color code to color name

How can I translate the hexadecimal representation of a color into its corresponding name?

For example, consider the following colors:

rainbow(4) # "#FF0000FF" "#80FF00FF" "#00FFFFFF" "#8000FFFF" 

What are their names (hoping that a name exists for each code)?

I discovered the col2rgb() function, but that doesn’t mean what I need.

+6
source share
3 answers

You can use the convenience function color.id from the plotrix * package:

Given the color specified as a hexadecimal string, find the closest match in the table of known (named) colors.

 library(plotrix) sapply(rainbow(4), color.id) # $`#FF0000FF` # [1] "red" "red1" # # $`#80FF00FF` # [1] "chartreuse" "chartreuse1" # # $`#00FFFFFF` # [1] "cyan" "cyan1" # # $`#8000FFFF` # [1] "purple" 

* Credits to Jim Lemon and his answer here: Convert hex color code to color names .

+3
source

This may not be the most elegant solution, but it should do its job:

 color.names <- function(d) { # get RGB components of d and convert to data frame z2 <- as.data.frame(t(col2rgb(d))) # get RGB components of standard colors and convert them to data frame z <- as.data.frame(t(sapply(colors(distinct=T),col2rgb))) colnames(z) <- colnames(z2) z$name <- rownames(z) # EDIT: original answer used 'merge', which messed up the order library(dplyr) z2 %>% left_join(z) %>% select(name) } color.names(rainbow(4)) # name # 1 red # 2 <NA> # 3 cyan # 4 <NA> 

The color.names function uses the same input as col2rgb , i.e.

any of the three types of R-colors, i.e. either a color name (as indicated in color ()), a hexadecimal string of the form "#rrggbb" or "#rrggbbaa" (see rgb), or a positive integer i palette () [i].

so that you can use it to get the names of standard colors by doing color.names(1:8)

For efficiency of calculations, a data set with standard colors can be pre-calculated, as in this example:

 init.color.names <- function() { z <- as.data.frame(t(sapply(colors(distinct=T),col2rgb))) colnames(z) <- colnames(z2) z$name <- rownames(z) library(dplyr) function(d) { z2 <- as.data.frame(t(col2rgb(d))) z2 %>% left_join(z) %>% select(name) } } cl <- init.color.names() cl(1:3) cl(rainbow(4)) 
+5
source

Probably better, but indexing is used here:

 colors()[match(rgb(t(col2rgb(rainbow(4))), maxColorValue = 255), c(rgb(t(col2rgb(colors())), maxColorValue = 255)))] ## [1] "red" NA "cyan" NA 
+3
source

Source: https://habr.com/ru/post/982339/


All Articles