Unity 3D : Gamma 曲線校正

前言 :

今天講 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;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值