Skip to content

Instantly share code, notes, and snippets.

@SwampThingPaul
Created September 7, 2020 18:49
Show Gist options
  • Save SwampThingPaul/6085a3066910e4c86eefca27bac3874d to your computer and use it in GitHub Desktop.
Save SwampThingPaul/6085a3066910e4c86eefca27bac3874d to your computer and use it in GitHub Desktop.
Code to extract colors from an image based on k-means
library(jpeg)
# Custom function similar to print.palette(...)
RenderPal <- function(x,name){
if ((missing(x)) || (missing(name))){
stop("Internal error, please troubleshoot")
}
n <- length(x)
old <- graphics::par(mar = c(0.5, 0.5, 0.5, 0.5))
on.exit(graphics::par(old))
graphics::image(1:n, 1, as.matrix(1:n), col = x,
ylab = "", xaxt = "n", yaxt = "n", bty = "n")
graphics::rect(0, 0.9, n + 1, 1.1, col = grDevices::rgb(1, 1, 1, 0.8), border = NA)
graphics::text((n + 1) / 2, 1, labels = name, cex = 2, family = "serif")
}
# -------------------------------------------------------------------------
# Read in image
img=readJPEG(...)
# find dimensions of your image
imgDm=dim(img)
# Convert image to rgb data.frame
imgRGB <- data.frame(
x = rep(1:imgDm[2], each = imgDm[1]),
y = rep(imgDm[1]:1, imgDm[2]),
R = as.vector(img[,,1]),
G = as.vector(img[,,2]),
B = as.vector(img[,,3])
)
# How many clusters?
kClusters=10
# Determine kmean cluster based on the number of clusters provided
kMean=kmeans(imgRGB[, c("R", "G", "B")], centers = kClusters)
# Extract the kmean colors
kColours <- rgb(kMean$centers[kMean$cluster,])
# Summary of colors
cols = unique(kColours)
# How are the colors distributed
sort(table(kColours)/sum(table(kColours))*100)
# What is your final palette
RenderPal(cols,"My Palette")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment