Skip to content

Instantly share code, notes, and snippets.

@greenpencil
Created April 2, 2019 23:07
Show Gist options
  • Save greenpencil/3e051e1665b818c4e147ace614ea370f to your computer and use it in GitHub Desktop.
Save greenpencil/3e051e1665b818c4e147ace614ea370f to your computer and use it in GitHub Desktop.
library("jpeg")
gamma.correct <- function(color) {
if(color > 0.04045) {
return((color + 0.055) / (1.0 + 0.055) ^ 2.4)
} else {
return(color / 12.92)
}
}
files <- list.files("E:\\Downloads\\yarn")
pngList <- list()
for(filename in files){
tempPNG <- readJPEG(paste0("E:\\Downloads\\yarn\\",filename)) # Downloads & loads PNGs
pngList[[filename]] <- tempPNG # And assigns them to a list.
}
meanRGB <- t(sapply(pngList, function(ll){
apply(ll[, , -4], 3, mean)
}))
#RBG to XYZ
for(ii in 1:length(pngList)){
tempName <- rownames(meanRGB)[ii]
meanRGB[tempName,1] <- gamma.correct(meanRGB[tempName,1])
meanRGB[tempName,2] <- gamma.correct(meanRGB[tempName,2])
meanRGB[tempName,3] <- gamma.correct(meanRGB[tempName,3])
x <- meanRGB[tempName,1] * 0.649926 + meanRGB[tempName,2] * 0.103455 + meanRGB[tempName,3] * 0.197109
y <- meanRGB[tempName,1] * 0.234327 + meanRGB[tempName,2] * 0.743075 + meanRGB[tempName,3] * 0.022598
z <- meanRGB[tempName,1] * 0.0000000 + meanRGB[tempName,2] * 0.053077 + meanRGB[tempName,3] * 1.035763
meanRGB[tempName, 1] <- x / (x + y + z);
meanRGB[tempName, 2] <- y / (x + y + z);
}
# Plot:
boxParameter <- 6000 #6000 # To alter dimensions of raster image bounding box
par(bg = gray(8/9))
plot(meanRGB, type = "n", asp = 1)
for(ii in 1:length(pngList)){ # Go through each flag
tempName <- rownames(meanRGB)[ii]
Coords <- meanRGB[tempName, 1:2] # Get coordinates from MDS
rasterImage(pngList[[tempName]], # Plot each flag with these boundaries:
Coords[1]-40/boxParameter, Coords[2]-40/boxParameter,
Coords[1]+40/boxParameter, Coords[2]+40/boxParameter)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment