傳統用 Texture2D 來做速度太慢,甚至使用 Texture2D.GetPixel(x, y).grayscale 也太慢,而且不能對細節微調。所以今天為大家展示用 ComputeShader ( GPU ) 將圖片轉成灰階。只要是你之前都使用 Texture2D 來做影像處理的話,那你今後可以用 ComputeShader 來取代,畢竟速度快上幾千倍嘛。不要說 Lag 了,以前不能 Realtime 的現在都能 Realtime,好了,唬爛到此結束,讓我們看以下程式碼。
C # :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
public Texture2D inputTexture;
public RawImage outputImage;
public ComputeShader shader;
void Start ()
{
RenderTexture t = new RenderTexture (inputTexture.width, inputTexture.height, 24);
t.enableRandomWrite = true;
t.Create ();
outputImage.texture = t;
int k = shader.FindKernel ("CSMain");
shader.SetTexture (k, "inputTexture", inputTexture);
shader.SetTexture (k, "outputTexture", t);
shader.Dispatch (k, inputTexture.width, inputTexture.height, 1);
}
}
Compute Shader :
#pragma kernel CSMain
// ( CPU -> GPU )
Texture2D inputTexture;
// ( GPU -> CPU )
RWTexture2D <float4> outputTexture;
[numthreads(1, 1, 1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
float R = inputTexture[id.xy].r;
float G = inputTexture[id.xy].g;
float B = inputTexture[id.xy].b;
float A = 1;
float Y = R * 0.299 + G * 0.587 + B * 0.114; // RGB 轉 灰階
outputTexture[id.xy] = float4(Y, Y, Y, A); // 丟回 CPU
}