方法类似于@Richard Ambler 的解决方案来比较测试 rgb 向量和
来自colours() 输出的大量颜色映射。
下面的函数rgb2col带有给定的测试rgb值返回近似匹配的颜色名称
数据:
library(scales) #for function show_col
DF = read.table(text="Color Count red green blue
ED1B24 16774 237 27 36
000000 11600 0 0 0
23B14D 5427 35 177 77
FFFFFF 5206 255 255 255
FEF200 3216 254 242 0
ED1B26 344 237 27 38",header=TRUE,stringsAsFactors=FALSE)
#from https://gist.github.com/mbannert/e9fcfa86de3b06068c83
rgb2hex <- function(r,g,b) rgb(r, g, b, maxColorValue = 255)
功能:
rgb2col = function(r,g,b) {
#create colour name vs. rgb mapping table
colourMap = data.frame(colourNames = colours(),t(col2rgb(colours())))
#input test colours
testDF = data.frame(colourNames="testCol",red = r,green = g,blue = b)
#combine both tables
combDF = rbind(testDF,colourMap)
#convert in matrix representation
combMat= (as.matrix(combDF[,-1]))
#add row labels as colour names
rownames(combMat) = combDF[,1]
#compute euclidean distance between test rgb vector and all the colours
#from mapping table
#using dist function compute distance matrix,retain only upper matrix
#find minimum distance point from test vector
#find closest matching colour name
approxMatchCol = which.min(as.matrix(dist(combMat,upper=TRUE))[1,][-1])
#compare test colour with approximate matching colour
scales::show_col(c(rgb2hex(r,g,b),rgb2hex(colourMap[approxMatchCol,2:4])))
#return colour name
return(approxMatchCol)
}
输出:
sapply(1:nrow(DF),function(x) rgb2col(DF[x,"red"],DF[x,"green"],DF[x,"blue"]))
#firebrick2 black seagreen white yellow firebrick2
# 135 24 574 1 652 135
情节: