# Converting an image to grey scale

A quick little utility for converting an image to grey scale. All this is doing is taking the original image and averaging the RGB values for each pixels and then redrawing the image in the lower canvas.
Original Image
Conversion By default, this is going to use a weighted average of the RGB values to create the grey scale, as documented on Wikipedia.
Note that the RGB values are not absolute. Their value will be normalized to 1.

Red: {( parameters.red | displayNumber: 4 )} Green: {( parameters.green | displayNumber: 4 )} Blue: {( parameters.blue | displayNumber: 4 )}
Grey Scale

Code Explanation This is a very simple filter. The arguments are the Red/Green/Blue balance that should be used to create the grey scale. The filter than goes through and sets the Red, Green and Blue pixels of the img to the same value for all three, resulting in a grey scale image.

Filters.greyscale = 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 numPixels = d.length;
var r,g,b,v;
for (var i = 0; i < numPixels; i+= 4) {
r = d[i];
g = d[i+1];
b = d[i+2];
v = Math.floor(red*r + green*g + blue*b);
d[i] = d[i+1] = d[i+2] = v;
}
return pixels;
}

Published on 21 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