Извлечение верхних 2-3 шестнадцатеричных цветов из изображений в R - PullRequest
0 голосов
/ 29 января 2019

Мне интересно, можно ли извлечь основные шестнадцатеричные цвета из файлов изображений, содержащих логотипы командных видов спорта.У меня есть следующий вектор логотипов:

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 (поэтому мне не нужно вручную загружать каждое изображение и нажимать, чтобы найти каждое шестнадцатеричное значение).

Спасибо!

Ответы [ 2 ]

0 голосов
/ 29 января 2019

Еще один вариант использования пакета тепловизора ...

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

0 голосов
/ 29 января 2019

Дайте это попробовать.Библиотека png позволяет загрузить RGB-файл, а затем необходимо преобразовать три канала в шестнадцатеричные коды.
Я подтвердил, что коды верны для первого изображения, удачи с остальными.

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

plot(NA, xlim = c(0, 2), ylim = c(0, 5), type = "n", xaxt = "n", yaxt = "n", xlab = "", ylab = "")
library(png)

for (filen in seq_along(logos)) {
  #download and read file
  #this will overwrite the file each time, 
  #create a list if you would like to save the files for the future.
  download.file(logos[filen], "file1.png")
  image1<-readPNG("file1.png")

  #plot if desired
  #plot(NA, xlim = c(0, 2), ylim = c(0, 5), type = "n", xaxt = "n", yaxt = "n", xlab = "", ylab = "")
  rasterImage(image1, 0, filen-1, 1, filen)

  #convert the rgb channels to Hex
  outR<-as.hexmode(as.integer(image1[,,1]*255))
  outG<-as.hexmode(as.integer(image1[,,2]*255))
  outB<-as.hexmode(as.integer(image1[,,3]*255))
  #paste into to hex value
  hex<-paste0(outR, outG, outB)
  #remove the white and black
  hex<-hex[hex != "ffffff" & hex != "000000"]
  #print top 5 colors
  print(head(sort(table(hex), decreasing = TRUE)))
}

Вот пример выходных данных, шестнадцатеричный цвет с количеством пикселей с этим цветом.

 print(head(sort(table(hex), decreasing = TRUE)))
 #hex
 #c3c4c6 00275d 00265c c2c3c5 001e57 00255c 
 #67929  39781    838    744    649    633 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...