Skip to content

Instantly share code, notes, and snippets.

@perfectmak
Last active January 26, 2018 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perfectmak/d8860c20e1a394698711ba227e8ec12b to your computer and use it in GitHub Desktop.
Save perfectmak/d8860c20e1a394698711ba227e8ec12b to your computer and use it in GitHub Desktop.
Simple Implementation of Color Quantization in Javascript (Node.js)
function quantize(k, colors) {
if (k > colors.length) {
throw Error(`K (${k}) is greater than colors (${colors.length}).`)
}
const centers = getRandomKCenters(k, colors)
let centerDistances = []
for(let i = 0; i < colors.length; i++) {
for(let j = 0; j < centers.length; j++) {
centerDistances.push(distance(centers[j], colors[i]))
}
const minimumDistance = Math.min(...centerDistances)
const nearestCentroidForI = centerDistances.indexOf(Math.min(...centerDistances))
colors[i] = centers[nearestCentroidForI]
centerDistances.length = 0 // clear distance array
}
return colors
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment