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

C# 影像處理:Gamma 校正完整實作與原理解析

     編輯:關於C語言

Gamma 校正原理

Gamma 值描述人眼對光線亮度的非線性感知曲線。顯示裝置(螢幕)輸出亮度與輸入訊號通常呈冪次關係:

輸出亮度 ∝ 輸入訊號γ

Gamma 校正即透過反函數預先補償,使最終視覺感知趨於線性。

C# 核心實作

利用 System.Drawing 的 ImageAttributes.SetGamma 方法,由 GDI+ 硬體加速處理:


public static Bitmap KiGamma(Bitmap bmp, float val)
{
    if (bmp == null) return null;
    if (Math.Abs(val - 1.0f) < float.Epsilon) return bmp; // 無變化快速返回

    try
    {
        Bitmap result = new Bitmap(bmp.Width, bmp.Height);
        using (Graphics g = Graphics.FromImage(result))
        using (ImageAttributes attr = new ImageAttributes())
        {
            attr.SetGamma(val, ColorAdjustType.Bitmap);
            g.DrawImage(bmp, 
                new Rectangle(0, 0, bmp.Width, bmp.Height),
                0, 0, bmp.Width, bmp.Height,
                GraphicsUnit.Pixel, attr);
        }
        return result;
    }
    catch
    {
        return null; // 建議記錄異常而非吞沒
    }
}

參數說明

  • val = 1.0:無變化
  • val < 1.0:提亮影像(補償螢幕過暗)
  • val > 1.0:壓暗影像(補償螢幕過亮)
  • 建議範圍:0.2 ~ 5.0

效能與記憶體優化

  1. using 區塊:確保 Graphics、ImageAttributes 及時釋放非託管資源
  2. 避免頻繁建構:批次處理時重用 ImageAttributes 實例
  3. 大圖處理:考慮分塊處理或使用 Bitmap.LockBits 直接操作像素

進階擴展:查表法 (LUT) 實作

對於即時影像處理,預計算 256 級查表更高效:


byte[] gammaLUT = new byte[256];
for (int i = 0; i < 256; i++)
{
    gammaLUT[i] = (byte)(255 * Math.Pow(i / 255.0, 1.0 / gamma));
}
// 套用至各色通道

應用場景

  • 照片編輯器亮度/對比度調整
  • 跨裝置色彩一致性校正
  • 醫學影像增強顯示
  • 遊戲引擎 HDR 色調映射
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved