Unity - A.unity - New Unity Project 14 - PC, Mac & Linux Standalone DX11_5  


using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    public Texture2D t;

    void Start () {
        transform.localScale = new Vector3 ((float)t.width/(float)t.height, 1);
        Texture2D tt = new Texture2D (t.width, t.height);
        for(int y = 1; y < t.height-1; y++){
            for(int x = 1; x < t.width-1; x++){
                Color c = t.GetPixel(x, y);
                float c2 = (c.r + c.g + c.b) / 3; // 原理,三原色取平均
//                float c2 = c.grayscale; // 在 Unity 最棒的做法
                tt.SetPixel(x, y, new Color(c2, c2, c2));
            }
        }
        tt.Apply ();
        renderer.material.mainTexture = tt;
    }
}

// 使用 YUV 實作 灰階 & RGB 轉 YUV & YUV 轉 RGB  ---------------------------

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

    public Texture2D t;

    void Start () {
        transform.localScale = new Vector3 ((float)t.width/(float)t.height, 1);
        Texture2D tt = new Texture2D (t.width, t.height);
        for(int y = 0; y < t.height; y++){
            for(int x = 0; x < t.width; x++){
                Color c = t.GetPixel(x, y);

                float r = c.r;
                float g = c.g;
                float b = c.b;

                // RGB 轉 YUV
                float Y = (r * 0.299f) + (g * 0.587f) + (b * 0.114f);
                float U = -(r * 0.147f) - (g * 0.289f) + (b * 0.436f);
                float V = (r * 0.615f) - (g * 0.515f) - (b * 0.1f);

                // YUV 轉 RGB
                float R = Y + (V * 1.14f);
                float G = Y - (U * 0.39f) - (V * 0.58f);
                float B = Y + (U * 2.03f);

                tt.SetPixel(x, y, new Color(Y, Y, Y)); // Y 即 灰階
                // tt.SetPixel(x, y, new Color(R, G, B));
            }
        }
        tt.Apply ();
        renderer.material.mainTexture = tt;
    }
}



arrow
arrow
    全站熱搜

    黃彥霖 發表在 痞客邦 留言(2) 人氣()