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
Original Image
The Color Distribution
Choose your own image

   * 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) {
    var red = parseFloat(args[0]);
    var green = parseFloat(args[1]);
    var blue = parseFloat(args[2]);
    var total = red + green + blue;
    red /= total;
    green /= total;
    blue /= total;
    var d = pixels.data;
    var redArray = new Uint32Array(256);
    var greenArray = new Uint32Array(256);
    var blueArray = new Uint32Array(256);
    var greyArray = new Uint32Array(256);
    var numPixels = d.length;
    for (var i = 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