Google
 

Friday, June 20, 2008

Converting a colored image to gray scale using C#

This is a simple method that creates a gray scale image from a colored image in C#:

public Image ToGrayScale(Image img)
{
Bitmap bitmap = new Bitmap(img);

for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
Color pixelColor = bitmap.GetPixel(i, j);
byte r = pixelColor.R;
byte g = pixelColor.G;
byte b = pixelColor.B;

byte gray=(byte)(0.299*(float)r+0.587*(float)g+0.114*(float)b);
r = g = b = gray;
pixelColor = Color.FromArgb(r, g, b);

bitmap.SetPixel(i, j, pixelColor);
}
}

Image grayImage = Image.FromHbitmap(bitmap.GetHbitmap());
bitmap.Dispose();
return grayImage;
}


The whole magic is in this line of code:

byte gray=(byte)(0.299*(float)r+0.587*(float)g+0.114*(float)b);

It extracts the Luminance component of the color in the YCbCr color system which represents the intensity of the image.

The rest is easy, all color components (R,G,B) will be the same for the image to be a gray scale.

No comments: