r - 从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 中的向量中的每个图像刮取这些十六进制值(所以我不必手动加载每个图像并单击以查找每个十六进制值)。
谢谢!
解决方案
使用成像器包的另一种选择...
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)
})
推荐阅读
- asp.net-identity - 本地登录后 User.Identity.Name 为空
- javascript - 如何在 Node.js 中的单个请求中运行 Google Vision API 标签检测和安全搜索检测?
- c# - RadCartesianChart 设置
- javascript - 环境变量 - 未定义
- javascript - 使用 DataTable search() 搜索唯一值
- netcdf - 如何将 netcdf 文件中的变量重新网格化到另一个网格,以使通量、质量和其他场保持守恒
- c# - ASP.NET Core(Razor 页面)- 如何下载特定文件夹(客户端)中的文件
- c++17 - Eclipse CDT 在使用 std::index_sequence 时报告错误错误
- amazon-web-services - 删除 AWS S3 中的对象
- node.js - 使用 SINON 在 NODE 中的 ES6 类中模拟构造函数