首页 > 解决方案 > 从R中的图像中提取前2-3个十六进制颜色

问题描述

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

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 中的向量中的每个图像刮取这些十六进制值(所以我不必手动加载每个图像并单击以查找每个十六进制值)。

谢谢!

标签: rimagecolors

解决方案


使用成像器包的另一种选择...

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)
  })


推荐阅读