2016-08-16 73 views
0

我嘗試比較兩個圖像之間的100x100像素的小塊。 我用LockBits操作之後本地memcmp PInvoke的電話,這是我的代碼:c#位圖塊比較

private void CompareBlock(Bitmap bmp1,Bitmap bmp2) 
    { 
     Rectangle lockRect = new Rectangle(0, 0, bmp1.Width, bmp1.Height); 
     BitmapData bmData = bmp1.LockBits(lockRect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb); 
     BitmapData bmData2 = bmp2.LockBits(lockRect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb); 
     IntPtr scan0 = bmData.Scan0; 
     IntPtr scan02 = bmData2.Scan0; 
     int BytesPerPixel = 4;//images are 32bpprgb 
     Size BlockSize = new Size(100,100); 
     if (memcmp(scan0, scan02, (BlockSize.Width * BlockSize.Height * BytesPerPixel))==0)//need to compare only the the first 100x100 pixels block. 
     { 
      Console.WriteLine("Equal"); 
      //do somthing with the block; 
     } 
    } 

我不知道我做錯了什麼,但這個程序實際上進入狀態,並打印"Equal"這是不正確(根據給定的圖像)。

我將不勝感激任何幫助。

謝謝。

//代碼更新的測試

 private void CompareBlock(Bitmap bmp1,Bitmap bmp2) 
    { 
     Rectangle lockRect = new Rectangle(0, 0, bmp1.Width, bmp1.Height); 
     BitmapData bmData = bmp1.LockBits(lockRect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb); 
     BitmapData bmData2 = bmp2.LockBits(lockRect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb); 
     IntPtr scan0 = bmData.Scan0; 
     IntPtr scan02 = bmData2.Scan0; 
     int BytesPerPixel = 4; 
     Size BlockSize = new Size(100,100); 

     for (int y = 0; y < BlockSize.Height; y++) 
     { 
      if (memcmp(scan0, scan02, BlockSize.Width * BytesPerPixel) == 0)//need to compare only the the first 100x100 pixels block. 
      { 
       scan0 = IntPtr.Add(scan0, stride);//not sure about that advancement 
       scan02 = IntPtr.Add(scan02, stride2);//not sure about that advancement 

       //do somthing with the block; 
      } 
      else 
       break; 
     } 
    } 

enter image description here enter image description here

+0

幾天前,我推薦[此項目](http://www.codeproject.com/Tips/240428/Work-with-bitmap-faster-with-Csharp)給需要鎖定位圖的人。它可能有助於解決您的問題。 –

回答

0

我不認爲你的代碼是做什麼你認爲它是。

BitmapData的Scan0值給出了位圖中第一個像素的地址。您然後遍歷內存空間的X字節(BlockSize.Width * BlockSize.Height * BytesPerPixel),它是100 x 100 x 32.

這不會給你一個100x100塊,但只是前幾個掃描行。您需要使用BitmapData.Stride屬性執行一些算術運算,以計算掃描線中的像素數。您只需要每個掃描線的前100xBytesPerPixel字節,然後提前您的存儲器指針跳過,直到下一個掃描線開始。

+0

我更新了代碼..是你的意思嗎?我必須遍歷每行來比較一個塊? :( 我不確定當前的代碼是否正常工作...請問您能看一下嗎? – Slashy

+0

是的,這是正確的方法,您必須迭代每一行,位圖數據不保存在二維陣列,但在一系列的掃描線(這可能會更長,位深度乘以該位圖寬度 - 所以這就是爲什麼我們使用的跨越 - 這使我們的位圖的單行的準確內存佔用 – PhillipH

+0

我。」我必須在這裏做很長時間的工作...需要比較我的屏幕的每個塊...爲**整個**屏幕。:( – Slashy