Serge's World

Blogging about software development, astronomy, genealogy and more.

Image Processing in C#: Part 2 - Converting an Image to Greyscale

Converting an image to greyscale is a relatively easy effect to apply to an image. For each pixel in the image, we take the three colour components (red, green and blue), and then combine the values.

Most people would think that you just take the average of the three colours, but the problem with that is the human eye has different sensitivities to different frequencies, so what we need to do is add in the colours at different ratios.

So, to make the colour ratios correct, we multiply the red, green and blue components by 0.299, 0.587 and 0.114 respectively. We then assign the value to all the components of the pixel.

Greyscale image

public void ApplyGreyscale()
{
    byte A, R, G, B;
    Color pixelColor;

    for (int y = 0; y < bitmapImage.Height; y++)
    {
        for (int x = 0; x < bitmapImage.Width; x++)
        {
            pixelColor = bitmapImage.GetPixel(x, y);
            A = pixelColor.A;
            R =  (byte)((0.299 * pixelColor.R) + (0.587 * pixelColor.G) + (0.114 * pixelColor.B));
            G = B = R;

            bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));
        }
    }

}

The full source used in the series is available from https://github.com/sjmeunier/image-processor.

Originally posted on my old blog, Smoky Cogs, on 19 Nov 2009

Tag Cloud

Algorithms (3) Android (10) Astronomy (25) Audio (1) Audiobooks (1) Barcodes (9) C# (69) Css (1) Deep sky (6) Esoteric languages (3) Family (3) Fractals (10) Gaming (1) Genealogy (14) General (2) Geodesy (3) Google (1) Graphics (3) Hubble (2) Humour (1) Image processing (23) Java (8) Javascript (5) jQuery (3) Jupiter (3) Maths (22) Moon (5) Music (4) Pets (5) Programming (88) Saturn (1) Science (1) Spitzer (4) Sun (4) Tutorials (68) Unity (3) Web (9) Whisky (13) Windows (1) Xamarin (2)