I made a simple color mapping application using JavaScript and jsfiddle. I kept a lot of my previous work to gather random images from either imgur or 500px. The image loads, then catalogs the number of instances of a color in each pixel.
imgd = context.getImageData(0,0,canvas.width,canvas.height).data;
for (var i = 0, n = imgd.length; i < n; i += 4) {
var r = imgd[i];
var g = imgd[i+1];
var b = imgd[i+2];
//i+3 is alpha, who cares
var r1 = colorVals[Math.floor(r/16)];
var r2 = colorVals[r-Math.floor(r/16)*16];
var g1 = colorVals[Math.floor(g/16)];
var g2 = colorVals[g-Math.floor(g/16)*16];
var b1 = colorVals[Math.floor(b/16)];
var b2 = colorVals[b-Math.floor(b/16)*16];
var curColor = "#"+r1+r2+g1+g2+b1+b2;
if (colors[curColor]) {
colors[curColor]++;
} else {
colors[curColor] = 1;
closeColors[curColor] = [r,g,b];
}
}
sortable = [];
for (var hex in colors) {
sortable.push([hex,colors[hex]]);
}
That part was fairly straightforward, and I didn't really want to do other, more productive, work, so I tried to get rid of colors that were "close" to each other. This algorithm proved to be a little more challenging. Basically, I needed a way to find colors that had red, green, and blue within some number of pixels of each other. Stepping through the entire array and eliminating colors proved to be a long process, so I simplified it down and only compared the first 1000 colors. This algorithm is below.
function checkColors() {
if (i<1000 && i<sortable.length-1) {
var myColor = sortable[i][0];
var myr = closeColors[myColor][0];
var myg = closeColors[myColor][1];
var myb = closeColors[myColor][2];
var yourColor = sortable[i+1][0];
var yr = closeColors[yourColor][0];
var yg = closeColors[yourColor][1];
var yb = closeColors[yourColor][2];
if (Math.abs(myr-yr)<15 && Math.abs(myg-yg) <15 && Math.abs(myb-yb)<15) {
sortable.splice(i+1,1);
} else {
i++;
}
checkColors();
} else {
//update divs here
}
}
I used this function structure in order to stop the div
elements from displaying the colors until some of them were deleted.
I think the code mostly works, although there are still colors on the list that are within my limits. I'm sick of dealing with it, and I think it's setup for future coding plans. The code is at jsfiddle and below.