在C# 影像處理中bitmap的像數值提取主要可分為三種方式 :

  • 提取像素法
  • 內存法
  • 指標法

以灰階影像處理進行效能比較之效果如下,由此測試可發現"內存法"與"指標法"速度遠快於"像素法",而"指標法"又略快於"內存法"。

 

 

 

提取像素法

private void pixcel(Bitmap bitmap, int width, int height){
     for (int i = 0; i < width; i++)
        for (int j = 0; j < height; j++){
          double r = bitmap.GetPixel(i, j).R;
           double g = bitmap.GetPixel(i, j).G;
           double b = bitmap.GetPixel(i, j).B;

          byte gray = (byte)(.299 * r + .587 * g + .114 * b);
                    bitmap.SetPixel(i, j, Color.FromArgb(gray, gray, gray));
        }
}

 

內存法

private void interal(Bitmap bitmap, int width, int height){
     int length = height * width * 3;
     byte[] colors = new byte[length];

     BitmapData data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
     IntPtr scan0 = data.Scan0;
     Marshal.Copy(scan0, colors, 0, length);
     double gray = 0;
     for (int i = 0; i < length; i += 3){
         gray = colors[i + 2] * .299 + colors[i + 1] * 0.587 + colors[i] * 0.114;
         colors[i + 2] = colors[i + 1] = colors[i] = (byte)gray;
     }
     Marshal.Copy(colors, 0, scan0, length);
     bitmap.UnlockBits(data);
}

 

指標法

private void point(Bitmap bitmap, int width, int height){
     Rectangle rect = new Rectangle(0, 0, width, height);
     BitmapData BmData;
     IntPtr srcScan;

        //將srcBitmap鎖定到系統內的記憶體的某個區塊中,並將這個結果交給BitmapData類別的srcBimap
     BmData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

         //位元圖中第一個像素數據的地址。它也可以看成是位圖中的第一個掃描行
         //目的是設兩個起始旗標srcPtr,為srcBmData的掃描行的開始位置
     srcScan = BmData.Scan0;

     unsafe //啟動不安全代碼
     {
       byte* srcP = (byte*)srcScan;
       int srcOffset = BmData.Stride - width * 3;
       for (int y = 0; y < height; y++){
           for (int x = 0; x < width; x++, srcP += 3){
             byte gray = (byte)(.299 * *(srcP + 2) + .587 * *(srcP + 1) + .114 * *srcP);
             *(srcP + 2) = *(srcP + 1) = *(srcP) = gray;
          }
          srcP += srcOffset;
        }
     }

     bitmap.UnlockBits(BmData);
}

 

使用指標法專案需進行設定。先對專案點選右鍵後選擇"屬性"。選擇"建置"後將"容許Unsafe程式碼"打勾。

 

arrow
arrow

    Lung-Yu,Tsai 發表在 痞客邦 留言(0) 人氣()