01.Blogs :
CCTING  

Unbelievable Performance - Unsafe Image Comparing

Approach one: Safe approach to compare two images

Two approaches of comparing two same size bitmap (Assume all pixel size as 4 = PNG (RGBA).
R=REd
G= GREEN
B=BLUE
A=Alpha (Transparency)
so the pixel size = 4..
(i not sure whether this is true, but it does work !!, i hope those who knows give some comment)
The result:
Safe approach very slow,, 1 comparison / 1000 ms almost take my CPU utilizatin 100%
Unsafe approach very fast, 1 comparison / 1000 ms almost take my CPU utilization less than 1%

10 comparison / 1000ms with unsafe ==> 20% CPU utilization.

So.. hahahaha nice right unsafe thing.

Here my source code.. have fun

Approach ONE: Safe approach
public
static double SafeCompare(ref Bitmap bmp1,ref Bitmap bmp2)
{
   int iMismatch = 0;
   for (int x = 0; x < bmp1.Width; x++)
        for (int y = 0; y < bmp1.Height; y++)
            
if (bmp1.GetPixel(x, y) != bmp2.GetPixel(x, y))  
                 iMismatch++;

   double percent = (double)iMismatch / (double)
          (bmp1.Height*bmp1.Width);
  
    return
percent * 100.0;
}

Approach TWO: UnSafe approach

public static double UnsafeCompare(ref Bitmap myBit, ref Bitmap myBit2)
{

System.Drawing.Imaging.BitmapData data = myBit.LockBits(new Rectangle(0, 0, myBit.Width, myBit.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, myBit.PixelFormat);

System.Drawing.Imaging.BitmapData data2 = myBit2.LockBits(new Rectangle(0, 0, myBit.Width, myBit.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, myBit.PixelFormat);

int iDifferent = 0;

int PixelSize = 4;

unsafe{

//REDUNDANT has happened later i correct :)
byte
* imgPtr = (byte*)data.Scan0;
byte* imgPtr2 = (byte*)data2.Scan0;

for (int y = 0; y < data.Height; y++){
   int Y = y * data.Stride;
   byte* row = (byte*)data.Scan0 + Y;
   byte* row2 = (byte*)data2.Scan0 + Y;

   for (int x = 0; x < data.Width; x++){
      int Blue= x * PixelSize;
      int Green = Blue+1;
      int Red = Green+1;
     
if (row[Red] != row2[Red] ||row[Green]!=row2[Green] ||row[Blue]!=row2[Blue])
         iDifferent++;
   }
  }
 }
 myBit.UnlockBits(data);
 myBit2.UnlockBits(data2);
 return Convert.ToDouble(iDifferent) /Convert.ToDouble(myBit.Width*myBit.Height)*100.0;

}

posted on Monday, June 06, 2005 12:06 PM by CCTING

# @ Monday, June 06, 2005 7:57 AM

ignore alpha value :D Er.. i believe blue is not sensitive to eyes.. ignore blue element again.. hahaha i am not good in graphic.. so.. 请多多指教

CCTING


 
03.UPDATE CALENDAR :
<June 2005>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

05.MY LINKS :

07.Subscriptions :

Subscriptions


© Copyright 2005 Microsoft Corporation. All Rights Reserved.
Terms of Use | Privacy Statement | Code of Conduct | Hosted by MaximumASP for Microsoft
WHO-BAR