Skip to content

Instantly share code, notes, and snippets.

@rtanglao
Created April 28, 2015 06:38
Show Gist options
  • Save rtanglao/c1bc9ddf1e2d47cd1927 to your computer and use it in GitHub Desktop.
Save rtanglao/c1bc9ddf1e2d47cd1927 to your computer and use it in GitHub Desktop.
colour rgb to nearest colour name
> nearColour <- function(r,g,b){
+ ctable = col2rgb(colors())
+ cdiff = ctable - c(r,g,b)
+ cdist = cdiff[1,]*cdiff[1,]+cdiff[2,]*cdiff[2,]+cdiff[3,]*cdiff[3,]
+ return(colors()[cdist == min(cdist)])
+ }
> rgb2 = col2rgb("#FEFDFC")
> rgb2[[1,1]]
[1] 254
> rgb2[[2,1]]
[1] 253
> rgb2[[3,1]]
[1] 252
> nearColour(254,253,252)
[1] "gray99" "grey99"
> nearColour(255,255,255)
[1] "white" "gray100" "grey100"
> nearColour(0,0,0)
[1] "black" "gray0" "grey0"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment