首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

超酷圖像效果:銳化濾鏡 C# 實作

     編輯:關於C語言

銳化效果原理

使用拉普拉斯算子 (Laplacian Kernel) 突出顏色劇烈變化的邊緣像素:

-1 -1 -1
-1  9 -1
-1 -1 -1

中心權重 9,周圍 8 鄰域各 -1,強化高頻分量。

完整實作代碼


private void btnSharpen_Click(object sender, EventArgs e) {
    try {
        int w = pictureBox1.Image.Width;
        int h = pictureBox1.Image.Height;
        Bitmap src = (Bitmap)pictureBox1.Image;
        Bitmap dst = new Bitmap(w, h);

        int[] lap = { -1, -1, -1, -1, 9, -1, -1, -1, -1 };

        for (int x = 1; x < w - 1; x++) {
            for (int y = 1; y < h - 1; y++) {
                int r = 0, g = 0, b = 0, idx = 0;
                for (int cx = -1; cx <= 1; cx++) {
                    for (int cy = -1; cy <= 1; cy++) {
                        Color p = src.GetPixel(x + cx, y + cy);
                        r += p.R * lap[idx];
                        g += p.G * lap[idx];
                        b += p.B * lap[idx];
                        idx++;
                    }
                }
                // 截斷至 0-255
                r = Math.Clamp(r, 0, 255);
                g = Math.Clamp(g, 0, 255);
                b = Math.Clamp(b, 0, 255);
                dst.SetPixel(x - 1, y - 1, Color.FromArgb(r, g, b));
            }
        }
        pictureBox1.Image = dst;
    } catch (Exception ex) {
        MessageBox.Show(ex.Message, "提示");
    }
}

效果展示

效能提示

  • GetPixel/SetPixel 極慢,實務建議使用 Bitmap.LockBits 直接操作記憶體
  • 邊界像素 (x=0, y=0, x=w-1, y=h-1) 未處理,保持原樣或另行填充
  • Math.Clamp (.NET Core 2.0+/Standard 2.1+) 簡化截斷邏輯
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved