前言 :
今天講 Gamma 曲線,所以我週末約了小姐姐外拍,多幫我弄幾張有版權的測試圖,不然感覺都沒圖片可以測了…
回歸正題,我們可以直接看執行結果的第一張原圖,他是偏暗的,我們想要給他加亮,就能用 Gamma 曲線來做,輸出結果就是第二張圖,效果還行。
整體曲線分布如下圖,我這張測試圖片使用 Gamma 0.7 所以幅度只有輕微彎曲,你們可以比較一下。
公式 1 :
公式 2 : s = c * r ^ γ
r : 輸入值
s : 輸出值
c : 常數 ( 縮放值 )
γ : Gamma值
如果 Gamma 設為 2.2 ,你要做反向 Gamma 可以將值設為 1 / Gamma ,大約等於 0.45。所以 2.2 與 0.45 的 Gamma 是對稱關係,如下圖:
執行結果 :
C # :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test6 : MonoBehaviour
{
public Texture2D inputTexture;
public RawImage imgGamma;
public RawImage imgOutput;
[Range(0.04f, 25f)]
public float gamma = 0.45f;
void Start()
{
// Draw Gamma Texture
Texture2D t = new Texture2D(256, 256);
float[] table = new float[t.width];
CreatTable_Gamma(table, gamma);
for (int x = 0; x < t.width; x++)
{
int y = (int)(table[x] * 255);
t.SetPixel(x, y, Color.red);
}
t.Apply();
imgGamma.texture = t;
// Draw Texture
Texture2D t2 = new Texture2D(inputTexture.width, inputTexture.height);
Color[] colors = new Color[t2.width * t2.height];
int i = 0;
foreach (Color color in inputTexture.GetPixels())
{
float r = table[(int)(color.r * 255)];
float g = table[(int)(color.g * 255)];
float b = table[(int)(color.b * 255)];
colors[i] = new Color(r, g, b);
i++;
}
t2.SetPixels(colors);
t2.Apply();
imgOutput.texture = t2;
}
void CreatTable_Gamma(float[] table, float nPercent)
{
float val;
for (int i = 0; i < 256; i++)
{
val = Mathf.Pow(i / 255.0f, nPercent);
if (val > 1) val = 1;
if (val < 0) val = 0;
table[i] = val;
}
}
}