2

I've been trying to find a way to do a quick and easy comparison between two Bitmaps and I've come up with two methods:

private static Bitmap Resize(Bitmap b, int nWidth, int nHeight)
{
    Bitmap result = new Bitmap(nWidth, nHeight);
    using (Graphics g = Graphics.FromImage((Image)result))
    {
        g.InterpolationMode = InterpolationMode.NearestNeighbor;
        g.DrawImage(b, 0, 0, nWidth, nHeight);
    }
    return result;
}

public static Decimal CompareImages(Bitmap b1, Bitmap b2, int Approx = 64)
{
    Bitmap i1 = Resize(b1, Approx, Approx);
    Bitmap i2 = Resize(b2, Approx, Approx);
    int diff = 0;

    for (int row = 1; row < Approx; row++)
    {
        for (int col = 1; col < Approx; col++)
        {
            if (i1.GetPixel(col, row) != i2.GetPixel(col, row))
                diff++;
        }
    }

    i1.Dispose();
    i2.Dispose();

    return Math.Round((Decimal)(diff / (Approx ^ 2)), 2);
}

public static Decimal CompareImagesExact(Bitmap b1, Bitmap b2)
{
    int h = b1.Height > b2.Height ? b1.Height : b2.Height;
    int w = b1.Width > b2.Width ? b1.Width : b2.Width;
    int diff = 0;
    for (int row = 1; row < h; row++)
    {
        for (int col = 1; col < w; col++)
        {
            if (b1.GetPixel(col, row) != b2.GetPixel(col, row))
                diff++;
        }
    }

    return Math.Round((Decimal)(diff / ((h * w) ^ 2)), 2);
}

What I'm asking are if these are valid ways to compare Bitmaps? Are there any problems I could face when using these? And are there any more efficient ways of doing this?

Prime
  • 2,410
  • 1
  • 20
  • 35
  • 6
    Seems valid, but `GetPixel` is incredibly inefficient. Check out `LockBits`. – Ry- Oct 31 '13 at 02:09
  • Thanks I'll take a look into it, I've never seen or used LockBits before. – Prime Oct 31 '13 at 02:17
  • this [post](http://stackoverflow.com/q/2031217/2145211) could be useful – Harrison Oct 31 '13 at 02:36
  • You know about the `using`, but you're not using it on your Bitmaps. And yeah, `LockBits`, not `GetPixel` – Ed S. Oct 31 '13 at 02:47
  • @Harrison The answers on that post seem to only return if they're EXACTLY the same or not, I need to get a certain percentage of how many pixels are different from the original. @EdS. I don't like having the extra indentations in my code, so I only use `using` for a quick resolution and use `Dispose()` if I need the code to look more level and cleaner. – Prime Oct 31 '13 at 03:05
  • Does your code actually include the "((h * w) ^ 2)" part? Because it doesn't really return the correct percentage... :-B – C.B. Oct 31 '13 at 17:08

0 Answers0