How to convert pixels to gray scale?

An SO User picture An SO User · Jun 14, 2013 · Viewed 11.7k times · Source

Ok, I am using Processing which allows me to access pixels of any image as int[]. What I now want to do is to convert the image to gray-scale. Each pixel has a structure as shown below:

...........PIXEL............
[red | green | blue | alpha]
<-8--><--8---><--8--><--8-->  

Now, what transformations do I need to apply to individual RGB values to make the image gray-scale ??
What I mean is, how much do I add / subtract to make the image gray-scale ?

Update

I found a few methods here: http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/

Answer

Geeky Guy picture Geeky Guy · Jun 14, 2013

For each pixel, the value for the red, green and blue channels should be their averages. Like this:

int red = pixel.R;
int green = pixel.G;
int blue = pixel.B;

pixel.R = pixel.G = pixel.B = (red + green + blue) / 3;

Since in your case the pixel colors seem to be stored in an array rather than in properties, your code could end up looking like:

int red = pixel[0];
int green = pixel[1];
int blue = pixel[2];

pixel[0] = pixel[1] = pixel[2] = (red + green + blue) / 3;

The general idea is that when you have a gray scale image, each pixel's color measures only the intensity of light at that point - and the way we perceive that is the average of the intensity for each color channel.