Wednesday 4 May 2011

Converting Colored Image to Grayscale using C#

Grayscale images also known as black-and-white images carry only intensity information and composed exclusively of  shades of gray, varying from black at the weakest intensity and white at the strongest. To convert any color to a grayscale representation of its luminance, first one must obtain the values of its red, green, and blue (RGB) primaries in linear intensity encoding, by gamma expansion. Then, add together 30% of the red value, 59% of the green value, and 11% of the blue value (these weights depend on the exact choice of the RGB primaries, but are typical).

In C#, a colored image can be converted to grayscale by drawing an image using a Graphics object and rendering it with attributes whose color matrix is set to calculate the color intensities of each pixel according to the grayscale distribution mentioned earlier.

public Bitmap ConvertToGrayscale(Bitmap original)
{
    // Create the grayscale ColorMatrix
    ColorMatrix colorMatrix = new ColorMatrix(
        new float[][] 
        {
            new float[] {.3f, .3f, .3f, 0, 0},           // 30% Red
            new float[] {.59f, .59f, .59f, 0, 0},        // 59% Green
            new float[] {.11f, .11f, .11f, 0, 0},        // 11% Blue
            new float[] {0, 0, 0, 1, 0},                 // Alpha scales to 1
            new float[] {0, 0, 0, 0, 1}                  // W is always 1
        });

    ImageAttributes attributes = new ImageAttributes();
    attributes.SetColorMatrix(colorMatrix);

    // Create a blank bitmap the same size as original and draw
    // the source image at it using the grayscale color matrix.    
    using (Graphics g = Graphics.FromImage(new Bitmap(original.Width, original.Height))
    {
        g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
           0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
    }
    return newBitmap;
}

No comments:

Post a Comment