title: How can I find the average of N colors?
body: <p>I'm looking for a way to find the average of an unspecified number of colors. I spent a lot of time looking for a way to do this. First I tried converting my colors to CMYK and averaging them, but that didn't provide the result I expected. Then I saw that in several different places, converting the colors to CIE L*a*b* space and then averaging is the preferred way of doing this. So I looked up how to convert RGB colors to LAB space and converted into Javascript the necessary algorithms to make this happen.</p>
  
  <p>Now that I have my colors in LAB space, I thought it would be as simple as finding the average of my colors, so I wrote this function to do the trick:</p>
  
  <pre><code>color.mixRGB = function() {
      var cols = Array.prototype.slice.call(arguments),
          i = cols.length,
          lab = {l: 0, a: 0, b: 0};
  
      while(i--) {
          if (typeof cols[i].r === "undefined" &amp;&amp; typeof cols[i].g === "undefined" &amp;&amp; typeof cols[i] === "undefined") {
              console.log("Not enough parameters supplied for color " + i + ".");
              return;
          }
  
          if(cols[i].r === 0 &amp;&amp; cols[i].g === 0 &amp;&amp; cols[i].b === 0) {
              cols.splice(i, 1);
          } else {
              cols[i] = color.RGBtoLAB(cols[i]);
              lab.l += cols[i].l;
              lab.a += cols[i].a;
              lab.b += cols[i].b;            
          }
      }
  
      lab.l /= cols.length;
      lab.a /= cols.length;
      lab.b /= cols.length;
  
      return color.LABtoRGB(lab);
  };
  </code></pre>
  
  <p>If I enter RGB (255, 0, 0) and RGB(0, 0, 255) into the function, I get RGB(202, -59, 136). This color is nothing near what Color Hexa says is the average of those two RGBs, which is RGB (128, 0, 128), a.k.a purple. </p>
  
  <p>I went back over all my code, and so far I've managed to determine that the problem does not lie with any of my conversion algorithms by double- and triple-checking them against <a href="http://colorhexa.com" rel="nofollow">Color Hexa</a> and <a href="http://easyrgb.com" rel="nofollow">EasyRGB</a>. That means either a) the issue must lie with how I'm averaging the colors or b) I've been misinformed and I shouldn't attempt to mix colors in CIE L*a*b* space.</p>
  
  <p>What exactly am I missing here? Using my current algorithm, why is averaging RGB (255, 0, 0) and RGB (0, 0, 255) not giving me the same results that Color Hexa (or even visual estimation) provides? (<a href="http://jsfiddle.net/yeDPc/10/" rel="nofollow">here's a fiddle</a> of my problem)</p>