Geekpedia Programming Tutorials






Using the ColorMatrix in C#

In this tutorial you will go through a few easy examples of using the ColorMatrix object with which we apply 3 different effects to a single picture (negative colors, grayscale, color translation). We also learn how to resize the form depending on the size of the loaded picture.

On Sunday, March 4th 2007 at 12:03 AM
By Andrew Pociu (View Profile)
*****   (Rated 4.7 with 13 votes)
Contextual Ads
More C# Resources
Advertisement
Download this Visual Studio 2005 project Download this project (Visual Studio 2005)

We won't be going deep into the ColorMatrix object, instead we'll see 3 samples of how the ColorMatrix is being used to apply effects to a picture.
First we start with designing the form:

Form

btnInvert, btnGrayscale, btnTranslate and btnLoad are all the buttons that we need here, and then there's a PictureBox entitled picPicture that dock fills the form. There's also a openPicture OpenFileDialog

The objects that we'll use in this application are to be declared at the beginning of the application:


Image imgPicture;

Bitmap bmpPicture;

System.Drawing.Imaging.ImageAttributes iaPicture;

System.Drawing.Imaging.ColorMatrix cmPicture;

Graphics gfxPicture;

Rectangle rctPicture;


This is everything we need to start manipulating a picture. First we need to add functionality to the btnLoad button; this will load a picture into the PictureBox and also resize the form to fit the size of the picture. In my Visual Studio project I defined a minimum width and height for the form so that it doesn't get too small when you open a tiny picture.

Here comes the click event of the Load button:


private void btnLoad_Click(object sender, EventArgs e)

{

    // Open dialog to browse for picture

    if (openPicture.ShowDialog() == DialogResult.OK)

    {

        // Store the picture in an Image object from the file

        imgPicture = Image.FromFile(openPicture.FileName);

        // Set the picture in the PictureBox

        picPicture.Image = imgPicture;

        picPicture.Size = picPicture.Image.Size;

        // Set the size of the PictureBox and Form to fit the picture

        this.Size = picPicture.Image.Size;

        this.Width += 16;

        this.Height += 85;

    }

}


Original ColorMatrix

You'd probably think it's time to move to the Invert, Grayscale and Translate buttons. First we're going to create two methods, one that prepares the picture for being transformed and one that applies the effect to the picture. The one that prepares the picture checks if there's a picture, initializes a bitmap object and initializes an ImageAttributes object.


private void PreparePicture()

{

    // If there's a picture

    if (imgPicture != null)

    {

        // Create new Bitmap object with the size of the picture

        bmpPicture = new Bitmap(imgPicture.Width, imgPicture.Height);

        // Image attributes for setting the attributes of the picture

        iaPicture = new System.Drawing.Imaging.ImageAttributes();

    }

}


We should also create a FinalizePicture() method where we apply the effect to the picture and displays it in the PictureBox:


private void FinalizePicture()

{

    // Set the new color matrix

    iaPicture.SetColorMatrix(cmPicture);

    // Set the Graphics object from the bitmap

    gfxPicture = Graphics.FromImage(bmpPicture);

    // New rectangle for the picture, same size as the original picture

    rctPicture = new Rectangle(0, 0, imgPicture.Width, imgPicture.Height);

    // Draw the new image

    gfxPicture.DrawImage(imgPicture, rctPicture, 0, 0, imgPicture.Width, imgPicture.Height, GraphicsUnit.Pixel, iaPicture);

    // Set the PictureBox to the new inverted colors bitmap

    picPicture.Image = bmpPicture;

}



Negative Picture / Invert Colors

The first effect we're going to apply today is the one of turning the colors of an image into their negative counterpart. The Click event of btnInvert prepares the picture, creates a negative matrix by setting the RGB (Red, Green and Blue) elements of the matrix to their negative value (-1).


private void btnInvert_Click(object sender, EventArgs e)

{

    PreparePicture();

    cmPicture = new System.Drawing.Imaging.ColorMatrix();

    // Change the elements

    cmPicture.Matrix00 = -1;

    cmPicture.Matrix11 = -1;

    cmPicture.Matrix22 = -1;

    FinalizePicture();

}


Invert ColorMatrix


Grayscale Picture

How about adding that early 20th century look to your pictures? We're going to get the image through a ColorMatrix again. However, this time we're going to work lower level on it:


private void btnGrayscale_Click(object sender, EventArgs e)

{

    PreparePicture();

    cmPicture = new System.Drawing.Imaging.ColorMatrix(new float[][]

    {

        new float[]{0.5f, 0.5f, 0.5f, 0, 0},

        new float[]{0.5f, 0.5f, 0.5f, 0, 0},

        new float[]{0.5f, 0.5f, 0.5f, 0, 0},

        new float[]{0, 0, 0, 1, 0, 0},

        new float[]{0, 0, 0, 0, 1, 0},

        new float[]{0, 0, 0, 0, 0, 1}

    });

    FinalizePicture();

}


Grayscale ColorMatrix

Some graphic editors apply different effects along to grayscale so that the image doesn't appear too exposed / bright.

Translate Picture

This effect is probably oddest of them all, but very useful. It can be used for different effects, from brightning the image to colorizing it. Right now we're going to colorize it to green with a .50 intensity. You can change the values in the last line of the matrix for a different color or try equal values at each value for other effects.


private void btnTranslate_Click(object sender, EventArgs e)

{

    PreparePicture();

    cmPicture = new System.Drawing.Imaging.ColorMatrix(new float[][]

    {

        new float[] {1, 0, 0, 0, 0},

        new float[] {0, 1, 0, 0, 0},

        new float[] {0, 0, 1, 0, 0},

        new float[] {0, 0, 0, 1, 0},

        new float[] {.0f, .50f, .0f, .0f, 1}

    });

    FinalizePicture();

}


This tutorial is supposed to give you a prime insight into the ColorMatrix object and what can be done with it. There is a multitude of algorithms out there that you can apply to the image using the ColorMatrix object.

Translate ColorMatrix
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by puneet on Monday, May 14th 2007 at 04:22 AM

wow this is a nice project ...

by bill on Wednesday, June 27th 2007 at 04:08 PM

yes, this is cool, bit i think there\'s a problem with the inverting function : it seems that it do not invert pure \"black\" (#000000) to white.
Then, if you try to invert a pure black and white jpg (for example : http://myspace-995.vo.llnwd.net/00590/59/91/590031995_l.jpg)
then you got some weird results :/
Very good tutorial anyway :)

by Chintankumar Patel on Monday, November 12th 2007 at 03:41 AM

really cool article but as bill said \"there a problem with inverting function\"
here is the corrected code for the inver button

private void btnInvert_Click(object sender, EventArgs e)
{
PreparePicture();
cmPicture = new System.Drawing.Imaging.ColorMatrix(new float[][]
{
new float[] {-1, 0, 0, 0, 0},
new float[] {0, -1, 0, 0, 0},
new float[] {0, 0, -1, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {1, 1, 1, 1, 1}
});
FinalizePicture();
}

by void on Thursday, December 13th 2007 at 12:08 PM

Why do you have 6 rows in the GrayScale example?
Also why do the last three rows have 6 columns?
cmPicture = new System.Drawing.Imaging.ColorMatrix(new float[][]
{
new float[]{0.5f, 0.5f, 0.5f, 0, 0},
new float[]{0.5f, 0.5f, 0.5f, 0, 0},
new float[]{0.5f, 0.5f, 0.5f, 0, 0},
new float[]{0, 0, 0, 1, 0, 0},
new float[]{0, 0, 0, 0, 1, 0},
new float[]{0, 0, 0, 0, 0, 1}
});

The ColorMatrix class says its a 5x5 array. I ran a small example which showed that the last row is ignored here and so are and extra columns.
In essense this matrix is equivalent to:

cmPicture = new System.Drawing.Imaging.ColorMatrix(new float[][]
{
new float[]{0.5f, 0.5f, 0.5f, 0, 0},
new float[]{0.5f, 0.5f, 0.5f, 0, 0},
new float[]{0.5f, 0.5f, 0.5f, 0, 0},
new float[]{0, 0, 0, 1, 0},
new float[]{0, 0, 0, 0, 1},
});

Was this a typo?
Looks like the constructor is doing the fixing for you.

by Kevin on Thursday, July 10th 2008 at 10:31 AM

The suggested correction to invert above is still not quite right, as it also inverts the Alpha channel. The following will work:

private void btnInvert_Click(object sender, EventArgs e)
{
PreparePicture();
cmPicture = new System.Drawing.Imaging.ColorMatrix(new float[][]
{
new float[] {-1, 0, 0, 0, 0},
new float[] {0, -1, 0, 0, 0},
new float[] {0, 0, -1, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {1, 1, 1, 0, 1}
});
FinalizePicture();
}

Also, with the Greyscale conversion, the coefficients in the matrix should be 0.333 rather than 0.5 for equal weights to RGB. Alternatively a better conversion would be to weight them differently based on colour perception:

private void btnGrayscale_Click(object sender, EventArgs e)
{
PreparePicture();
cmPicture = new System.Drawing.Imaging.ColorMatrix(new float[][]
{
new float[] {0.30f, 0.30f, 0.30f, 0, 0},
new float[] {0.59f, 0.59f, 0.59f, 0, 0},
new float[] {0.11f, 0.11f, 0.11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
FinalizePicture();
}

by Gagan Shrestha on Thursday, October 2nd 2008 at 11:52 PM

hi i know a very little about color matrix class
can any body tell me what is the values of the color matrix does what in the transforming the image
please if u can, email me

by iwan on Friday, December 12th 2008 at 06:57 AM

does anybody have some idea how to correct white balance with colorMatrix?

by aravinth on Wednesday, February 18th 2009 at 02:15 PM

thanks for your solution

by gmculp on Thursday, March 4th 2010 at 05:35 PM

This is terrific. Thanks!


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons