A utility for calculating the color distribution of an image in JavaScript
A lot of image processing starts with getting the distribution of colors in an image. This is a quick little JavaScript routine to get the
Red, Green, Blue and Grey color distribution. All it does is go through every pixel, creates a histogram
/** * Computes the histogram, returning a struct with Red, Green, Blue and Grey. The * grey scale balance is set from the arguments. */Filters.histogram=function(pixels,args){varred=parseFloat(args[0]);vargreen=parseFloat(args[1]);varblue=parseFloat(args[2]);vartotal=red+green+blue;red/=total;green/=total;blue/=total;vard=pixels.data;varredArray=newUint32Array(256);vargreenArray=newUint32Array(256);varblueArray=newUint32Array(256);vargreyArray=newUint32Array(256);varnumPixels=d.length;for(vari=0;i<numPixels;i+=4){redArray[d[i]]++;greenArray[d[i+1]]++;blueArray[d[i+2]]++;greyArray[Math.floor(red*d[i]+green*d[i+1]+blue*d[i+2])]++;}return{red:redArray,green:greenArray,blue:blueArray,grey:greyArray};}
Published on 20 January 2015
Brian Hoover is a full stack software engineer with many years of experience. He's also a facilitator at the University of Phoenix