求此 C#程式碼(OTSU) 解釋註解 PART3 。

// simple routine to convert to gray scale

public void Convert2GrayScaleFast(Bitmap bmp)

{

BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),

ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

unsafe

{

byte* p = (byte*)(void*)bmData.Scan0.ToPointer();

int stopAddress = (int)p + bmData.Stride * bmData.Height;

while ((int)p != stopAddress)

{

p[0] = (byte)(.299 * p[2] + .587 * p[1] + .114 * p[0]);

p[1] = p[0];

p[2] = p[0];

p += 3;

}

}

bmp.UnlockBits(bmData);

}

// simple routine for thresholdin

public void threshold(Bitmap bmp, int thresh)

{

BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),

ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

unsafe

{

byte* p = (byte*)(void*)bmData.Scan0.ToPointer();

int h= bmp.Height;

int w = bmp.Width;

int ws = bmData.Stride;

for (int i = 0; i < h; i++)

{

byte *row=&p[i*ws];

for (int j = 0; j < w * 3; j += 3)

{

row[j] = (byte)((row[j] > (byte)thresh) ? 255 : 0);

row[j+1] = (byte)((row[j+1] > (byte)thresh) ? 255 : 0);

row[j + 2] = (byte)((row[j + 2] > (byte)thresh) ? 255 : 0);

}

}

}

bmp.UnlockBits(bmData);

}

}

}

1 個解答

評分
  • Tai
    Lv 5
    7 年前
    最佳解答

    Convert2GrayScaleFast() => 就是套了各 RGB 轉 Gray 的公式

    threshold(bmp, threshold) => 內部將 bmp 轉成灰階, 而 threshold 想必是剛才算的 Otsu threshold, 之後 > threshold 為 255 (白色), < threshold 為 0 (黑色), 作成黑白圖

    • Commenter avatar登入以對解答發表意見
還有問題?馬上發問,尋求解答。