Basic image processing in C# using matrix

I can still remember an evening in Pure maths class of Ramees sir in ideal we were talking about matrix and integration. That time Mohamed Soofi made an statement that the Photoshop like apps use some kind of matrix operation to perform some image processing works, and I found the way how matrix is used there. 

This C# code converts a RGB coloured bitmap to grayscale and this use the basic matrix 

public static Bitmap ToGrayscale(Bitmap original)

Bitmap newBitmap = new Bitmap(original.Width, original.Height);

Graphics g = Graphics.FromImage(newBitmap);

ColorMatrix colorMatrix = new ColorMatrix(
new float[][] 
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
}); //create the grayscale ColorMatrix

ImageAttributes attributes = new ImageAttributes();

attributes.SetColorMatrix(colorMatrix); //set the color matrix attribute

g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

return newBitmap;


I don’t know whether Soofi is still remember that incident.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s