Click here to Skip to main content
15,881,139 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a method, that is used to extract difference from parent image. It works fine, but the problem is, it eats more time. Please tell me a faster way..!!!

My Method:
C#
public static Bitmap GetDifferences(this Image img1, Image img2)
{
    Bitmap parentImage = (Bitmap)img1.GetGrayScaleVersion();
    Bitmap comparer = (Bitmap)img2.GetGrayScaleVersion();
    Bitmap difference = (Bitmap)img2;

    difference.MakeTransparent(Color.Violet);
    for (int y = 0; y < img1.Height; y++)
    {
        for (int x = 0; x < img1.Width; x++)
        {
            if ((parentImage.GetPixel(x, y).R - comparer.GetPixel(x, y).R) == 0)
            {
                difference.SetPixel(x, y, Color.Transparent);
            }
        }
    }

    return difference;
}


Dependency Method:
C#
public static Image GetGrayScaleVersion(this Image original)
{
    //http://www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale
    //create a blank bitmap the same size as original
    Bitmap newBitmap = new Bitmap(original.Width, original.Height);

    //get a graphics object from the new image
    Graphics g = Graphics.FromImage(newBitmap);

    //create some image attributes
    ImageAttributes attributes = new ImageAttributes();

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

    //draw the original image on the new image
    //using the grayscale color matrix
    g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
        0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

    //dispose the Graphics object
    g.Dispose();

    return newBitmap;

}
Posted
Updated 30-Jan-13 3:17am
v2

1 solution

Simple. Don't ever use GetPixel/SetPixel. They're VERY slow compared to doing the same operations accessing the pixel data arrays.

Search the articles for "Image processing for dummies" and you'll find a bunch of articles on how to do it, MUCH faster.
 
Share this answer
 
Comments
Balaganesan Ravichandran 31-Jan-13 4:06am    
Thanks Dave, Your reply really helps me to figure out the issue, I`m still not getting your point fully (Processing with pixel data arrays).
But Bitmap.LockBits did works for me. Now function runs 2x faster. Still not statisfied.. :-(
Dave Kreskowiak 31-Jan-13 12:51pm    
It should run a LOT faster than that, so I think you need to re-read those articles and rethink how your doing what it is you are.

Without seeing your code, it's impossible to tell you what to do.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900