Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import chroma from 'chroma-js';
const cluster = (colors, centers) => {
const centerCounts = {};
for(let color of colors) {
let bestCenter = null;
let bestCenterDist = Number.MAX_VALUE;
for(let center in centers) {
const dist = chroma.distance(color, centers[center]);
if(dist < bestCenterDist) {
bestCenter = center;
bestCenterDist = dist;
}
centerCounts[bestCenter] = (centerCounts[bestCenter] || 0) + 1;
}
}
return Object.keys(centerCounts).map(center => ({center: centers[center], count: centerCounts[center]}));
}
const THRESHOLD = 30;
const groupClusters = centers => centers.slice(1).reduce((newCenters, center) => {
let minThreshold = Number.MAX_VALUE;
let minIdx = null;
for(let newCenterIdx in newCenters) {
const newCenter = newCenters[newCenterIdx];
const dist = chroma.distance(newCenter.center, center.center)
if(dist < minThreshold) {
minThreshold = dist;
minIdx = newCenterIdx;
}
}
if(minThreshold < THRESHOLD) {
const newCenter = newCenters[minIdx];
if(newCenter.count < center.count) {
newCenters[minIdx].center = center.center;
}
newCenters[minIdx].count = newCenter.count += center.count;
console.log('Clustered', newCenter, center);
return newCenters;
}
return newCenters.concat([center]);
}, [centers[0]]);
const significance = centers => {
const sum = centers.reduce((sum, {count}) => sum+count, 0);
return centers.map(center => Object.assign({significance: center.count/sum}, center));
}
const sort = centerCounts => centerCounts.sort(({count: countA}, {count: countB}) => countB-countA);
const filterHueless = centers => centers.filter(({center}) => {
const hsl = center.hsl();
console.log(center.toString(), center.name(), ...center.hsl());
if(isNaN(hsl[0])) return false;
return hsl[2] <= 0.80 && hsl[2] >= 0.2 && hsl[1] >= 0.05;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment