John Fox <jfox <at> mcmaster.ca> writes: > I'm interested in locating the named colour that's "closest" to an arbitrary RGB colour. The best that I've > been able to come up is the following, which uses HSV colours for the comparison: > > r2c <- function(){ > hexnumerals <- 0:15 > names(hexnumerals) <- c(0:9, LETTERS[1:6]) > hex2decimal <- function(hexnums){ > hexnums <- strsplit(hexnums, "") > decimals <- matrix(0, 3, length(hexnums)) > decimals[1, ] <- sapply(hexnums, function(x) > sum(hexnumerals[x[1:2]] * c(16, 1))) > decimals[2, ] <- sapply(hexnums, function(x) > sum(hexnumerals[x[3:4]] * c(16, 1))) > decimals[3, ] <- sapply(hexnums, function(x) > sum(hexnumerals[x[5:6]] * c(16, 1))) > decimals > } > colors <- colors() > hsv <- rgb2hsv(col2rgb(colors)) > function(cols){ > cols <- sub("^#", "", toupper(cols)) > dec.cols <- rgb2hsv(hex2decimal(cols)) > colors[apply(dec.cols, 2, function(dec.col) > which.min(colSums((hsv - dec.col)^2)))] > } > } > > rgb2col <- r2c() > > I've programmed this with a closure so that hsv gets computed only once. > > > I vaguely recall a paper or discussion concerning colour representation in R but can't locate it. >
Dear John, Are you thinking of Zeileis A, Hornik K, Murrell P (2009). “Escaping RGBland: Selecting Colors for Statistical Graphics.” Computational Statistics & Data Analysis, 53, 3259–3270. doi:10.1016/j. csda.2008.11.033. or the vignette from the colorspace package that covers some of the same territory. How about if you compute color distances in Lab or Luv spaces? These so-called uniform color spaces are based on human discrimination data for small color distances so should be better at finding the nearest color, I would think. Untried though. Don't forget that these are based on a standard color calibration, sRGB, I think in the case of R and your display may or may not be close to that, so expect some error from that as well. best, Ken > Any suggestions would be appreciated. > > John > > ------------------------------------------------ > John Fox > Sen. William McMaster Prof. of Social Statistics > Department of Sociology > McMaster University > Hamilton, Ontario, Canada > http://socserv.mcmaster.ca/jfox/ > > -- Kenneth Knoblauch Inserm U846 Stem-cell and Brain Research Institute Department of Integrative Neurosciences 18 avenue du Doyen Lépine 69500 Bron France tel: +33 (0)4 72 91 34 77 fax: +33 (0)4 72 91 34 61 portable: +33 (0)6 84 10 64 10 http://www.sbri.fr/members/kenneth-knoblauch.html ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.