所謂內存法,是把圖像先鎖定到記憶體中再進行處理,效率遠高於逐點呼叫 GetPixel,安全性又高於直接使用指標的寫法。當初寫圖像處理時,網上多見 GetPixel 的實現,而內存法往往只被提及卻少有具體範例,因此這裡做一個完整示範。
1. LockBits 與 UnlockBits:使用 LockBits 可在系統記憶體中鎖定現有位圖以便程式化修改,每呼叫一次 LockBits,都應對應呼叫一次 UnlockBits。
2. Scan0:圖像第一個位元組的地址。
3. Stride:步幅,也就是掃描寬度,形象說就是一行的長度。
4. PixelFormat:資料實際的像素格式。
對每個像素點做加權平均(方法不唯一)。
/// 灰化實現方法
void Image_Ashing()
{
if (pbshowbox.Image != null)
{
int Height = this.pbshowbox.Image.Height;
int Width = this.pbshowbox.Image.Width;
Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
Bitmap MyBitmap = (Bitmap)this.pbshowbox.Image;
BitmapData oldData = MyBitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
BitmapData newData = bitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
{
byte* pin = (byte*)(oldData.Scan0.ToPointer());
byte* pout = (byte*)(newData.Scan0.ToPointer());
for (int y = 0; y < oldData.Height; y++)
for (int x = 0; x < oldData.Width; x++)
{
byte Result = (byte)(pin[0] * 0.1 + pin[1] * 0.2 + pin[2] * 0.7);//加權平均
pout[0] = pout[1] = pout[2] = Result;
pin += 3; pout += 3;
}
pin += oldData.Stride - oldData.Width * 3;
pout += newData.Stride - newData.Width * 3;
}
bitmap.UnlockBits(newData);
MyBitmap.UnlockBits(oldData);
this.pbshowbox.Image = bitmap;
}
else { MessageBox.Show("請先打開一張圖片!"); }
}
當某像素與周圍像素差異較大時取加權平均,這裡採用 3×3 高斯模板 {1,2,1,2,4,2,1,2,1},累加後除以 16,並對 RGB 做 0–255 的溢出處理。
使用拉普拉斯模板 {-1,-1,-1,-1,9,-1,-1,-1,-1},突出顯示顏色值較大的像素點,同樣需要邊界判斷與溢出鉗制。
將像素值與相鄰像素值相減後加 128,作為新的像素值;實作時用 pin_1、pin_2 兩個指標分別指向相鄰兩行,逐行逐列做差值運算。
顏色值取反,即用 255 減去各通道值,操作最為直觀。
先求 RGB 平均 avg,若 avg > 128 則置 255,否則置 0,形成強烈黑白對比的效果。
以上六種效果都遵循同一套「LockBits → unsafe 指標遍歷 → UnlockBits」的框架,只是核心運算不同。部分效果看起來不明顯,往往是因為預覽圖被縮小了,實際處理後差異相當顯著。