2013-12-08 81 views
1

今天我想嘗試一下新的圖像處理在C#中。C#快速img合併

Szenario如下:我有兩個黑白圖像。現在我想從兩個圖像中獲取所有白色像素(x,y)並將它們放入返回圖像中。所以最後我的image3包含了來自image1和image2的所有白色像素。 我使用不安全的指針,因爲它們更快。

所以在我的代碼檢查,如果在此搜索(X,Y)==圖像2中(X,Y),因爲它是不太可能,這兩個圖片有在同一地點

我的做法正確的白色像素現在:

private unsafe static Bitmap combine_img(Bitmap img1, Bitmap img2) 
    { 
     Bitmap retBitmap = img1; 

     int width = img1.Width; 
     int height = img1.Height; 
     BitmapData image1 = retBitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); 
     BitmapData image2 = img2.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); // here an error 

     byte* scan1 = (byte*)image1.Scan0.ToPointer(); 
     int stride1 = image1.Stride; 

     byte* scan2 = (byte*)image2.Scan0.ToPointer(); 
     int stride2 = image2.Stride; 

     for (int y = 0; y < height; y++) 
     { 
      byte* row1 = scan1 + (y * stride1); 
      byte* row2 = scan2 + (y * stride2); 

      for (int x = 0; x < width; x++) 
      { 
       if (row1[x] == row2[x]) 
        row1[x] = 255; 
      } 
     } 

     img1.UnlockBits(image1); 
     img2.UnlockBits(image2); 

     return retBitmap; 
    } 

不幸的是,當試圖鎖定第二個圖像時,它返回一個錯誤,說圖像已被鎖定!

+0

如果您在兩個參數上傳遞相同的圖像,這並不奇怪。即使情況並非如此,您應該添加驗證圖像是否相同的代碼,以及是否正確處理該情況;否則照常繼續。 – Theraot

+1

只需交換兩個LockBits語句。如果它現在抱怨retBitmap被鎖定,那麼它們確實會引用相同的位圖數據。如果不是,那麼它被鎖定在別處。 UnlockBits()屬於finally {block}。 –

回答

1

的問題是,這奇怪我沒有通過相同的圖像,在這裏更正後的代碼:

private unsafe static void combine_img(Bitmap img1, Bitmap img2) 
    { 
     BitmapData image1 = img1.LockBits(new Rectangle(0, 0, img1.Width, img1.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); 
     BitmapData image2 = img2.LockBits(new Rectangle(0, 0, img2.Width, img2.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); 

     int bytesPerPixel = 3; 

     byte* scan1 = (byte*)image1.Scan0.ToPointer(); 
     int stride1 = image1.Stride; 

     byte* scan2 = (byte*)image2.Scan0.ToPointer(); 
     int stride2 = image2.Stride; 

     for (int y = 0; y < img1.Height; y++) 
     { 
      byte* row1 = scan1 + (y * stride1); 
      byte* row2 = scan2 + (y * stride2); 

      for (int x = 0; x < img1.Width; x++) 
      { 
       if (row2[x * bytesPerPixel] == 255) 
        row1[x * bytesPerPixel] = row1[x * bytesPerPixel - 1] = row1[x * bytesPerPixel-2] = 255; 
      } 
     } 
     img1.UnlockBits(image1); 
     img2.UnlockBits(image2); 
    } 
0

我猜你的第二個圖像不是24位的圖像。 Mayber嘗試類似:

BitmapData image2 = img2.LockBits(new Rectangle(0, 0, img2.Width, img2.Height), ImageLockMode.ReadWrite, img2.PixelFormat); 

在這種情況下,你總是會通過這條線(我認爲),但問題是,你不會知道你在實際處理24位的圖像或32位圖像。