r - 从 R 中的图像中提取前 2-3 个十六进制颜色

标签 r image colors

我想知道是否可以从包含团队运动 Logo 的图像文件中提取主要的十六进制颜色。我有以下 Logo 向量:

dput(team.logos[1:5))
c("https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/399.png", 
"https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/2066.png", 
"https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/42.png", 
"https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/311.png", 
"https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/160.png")

使用以下网站 ( https://html-color-codes.info/colors-from-image/ ) - 我可以看到第一张图像 (UAlbany) 中的十六进制颜色值是 #FEBE10 表示黄色,#3F1E6B 紫色,以及白色。

我的问题是 - 有什么方法可以为 R 中的向量中的每个图像抓取这些十六进制值(这样我就不必手动加载每个图像并单击以查找每个十六进制值)。

谢谢!

最佳答案

使用成像器包的另一个选项...

require('imager')
require('data.table')

team.logos <- c("https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/399.png", 
  "https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/2066.png", 
  "https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/42.png", 
  "https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/311.png", 
  "https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/160.png")

#this function takes an image in imager's cimg format and 
#returns the hex colour codes for any colours covering more than 
#a threshold proportion of pixels (default is set to 0.05)
getHexPrimaries <- function(img, pcnt.threshold = 0.05){

    #convert cimg to workable format
    channel.labels <- c('R','G','B','A')[1:dim(img)[4]]
    img <- as.data.table(as.data.frame(img))
    img[,channel := factor(cc ,labels=channel.labels)]
    img <- dcast(img, x+y ~ channel, value.var = "value")

    #sort by unique rgb combinations and identify the primary colours
    colours.sorted <- img[, .N, by=list(R,G,B)][order(-N)]
    colours.sorted[ , primary := N/sum(N) > pcnt.threshold]

    #convert to hex
    hex.primaries <- 
      apply(colours.sorted[primary==TRUE], 1, function(row){
        hex <- rgb(row[1], row[2], row[3], maxColorValue=1)
        hex
      })

    hex.primaries
}

hex.list <- lapply(team.logos, function(logo.url) {
  download.file(logo.url,'temp.png', mode = 'wb')
  img <- load.image('temp.png')
  getHexPrimaries(img)
  })

关于r - 从 R 中的图像中提取前 2-3 个十六进制颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54412166/

相关文章:

在 dplyr 的 group_by 中有条件地删除重复行

javascript - 在 javascript 中制作 plotly 树状图

html - 哪个更好用 HTML/CSS 来显示 img?

禁用时Android TextView 颜色不会改变

python - 如何使用 python 和 win32 api 将彩色文本写入文本框?

colors - gnuplot 背景颜色

r - dplyr unnest_tokens 不工作

R:在谷歌搜索一个字符串并返回点击数

python - 如何为draw.text中的文本分配不同的颜色

html - 使较小的图像覆盖较大的 div 并保持宽高比