Click here to Skip to main content
13,193,442 members (45,334 online)
Rate this:
Please Sign up or sign in to vote.
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:
public static Bitmap GetDifferences(this Image img1, Image img2)
    Bitmap parentImage = (Bitmap)img1.GetGrayScaleVersion();
    Bitmap comparer = (Bitmap)img2.GetGrayScaleVersion();
    Bitmap difference = (Bitmap)img2;
    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:
public static Image GetGrayScaleVersion(this Image original)
    //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
    //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
    return newBitmap;
Posted 30-Jan-13 3:14am
Updated 30-Jan-13 3:17am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web01 | 2.8.171018.2 | Last Updated 31 Jan 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100