Last active
January 26, 2018 18:06
-
-
Save perfectmak/d8860c20e1a394698711ba227e8ec12b to your computer and use it in GitHub Desktop.
Simple Implementation of Color Quantization in Javascript (Node.js)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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