close

Unity 基本的圖片二值化

我當然都是講重點的拉.......... !

一個很重要的圖片設定,依我的習慣我會使用sprite(2D and UI)選項,

重要的是Read/Write Enable,因為程式會需要讀到圖片,而這個錯誤在執行後沒有被Debug出來,

所以記得把它打勾。

接下來只要用一個簡單的Quad和Material,就可以先實作這個物件(Material使用Unlit/Texture),

程式碼直接掛在Quad就可。另外還要記得放上你的Texture到程式上。

看圖片就對拉 !

二話不說直接上程式碼(C#)

 

using UnityEngine;
using System.Collections;

public class Binarization : 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    RGB和UV的计算都是没有用的!  
                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();
        GetComponent<Renderer>().material.mainTexture = tt;
    }
}

 

執行前用的圖片

/p>

執行後的二值化圖片/p>

 

專案參考囉

以後相關的相片處理都以這種方式處理,你可以的...... 哈哈

Source in google drive :  https://drive.google.com/open?id=0B-oXUfCJkMv_aE50QTVkYmlvVjA

版本 in Unity 5.6.1f1 

arrow
arrow
    全站熱搜

    Tars 發表在 痞客邦 留言(0) 人氣()