Convert an image to gray scale
An image in a computer consists of three main color channels, they are RED, GREEN, and BLUE. So each pixle in an image has three values one for each channel ranging from 0 up 255. In order to get the gray scale of an image one channel should be used instead, and each pixle then will have only one value called the Gray level. To obtain the Gray level for a pixle of an image, we should use the following formula: Gray = 0.3 * RED + 0.6 * GREEN + 0.1 * BLUE This method applies the previous formula on the pixels of a given image resulting the gray level of the image. public Image ToGrayScale(Image im)
{
int R, G, B, Gray;
// create a Bitmap Object to access pixels.
Bitmap Bm = new Bitmap(im);
for (int i = 0; i < Bm.Size.Height; i++)
{
for (int j = 0; j < Bm.Size.Width; j++)
{
// for each pixel get the the channel colors
R = Bm.GetPixel(j, i).R;
G = Bm.GetPixel(j, i).G;
B = Bm.GetPixel(j, i).B;
// Apply the formula
Gray = (int)(0.3 * R) + (int)(0.6 * G) + (int)(0.1 * B);
Bm.SetPixel(j, i, Color.FromArgb(Gray, Gray, Gray));
}
}
return Bm;
}